├── .clang-format ├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── README.md ├── WebBench ├── LICENSE ├── Makefile ├── README.md ├── debian │ ├── changelog │ ├── control │ ├── copyright │ ├── dirs │ └── rules ├── socket.c ├── tags ├── test.sh ├── webbench ├── webbench.1 └── webbench.c ├── config.ini ├── pages ├── 403.html ├── 404.html ├── bookmark.html └── index.html ├── version_0.1 ├── .DS_Store ├── include │ ├── httpparse.h │ ├── httpresponse.h │ ├── server.h │ ├── ssocket.h │ └── utils.h ├── src │ ├── base │ │ └── noncopyable.h │ ├── httpparse.cpp │ ├── httpresponse.cpp │ ├── main.cpp │ ├── server.cpp │ ├── ssocket.cpp │ └── utils.cpp └── test │ ├── test.cpp │ └── test_utils.cpp ├── version_0.2 ├── 403.html ├── 404.html ├── include │ ├── Condition.h │ ├── HttpResponse.h │ ├── MutexLock.h │ ├── ThreadPool.h │ ├── Util.h │ ├── httpparse.h │ ├── noncopyable.h │ ├── server.h │ └── ssocket.h ├── index.html ├── src │ ├── ThreadPool.cpp │ ├── Util.cpp │ ├── httpparse.cpp │ ├── httpresponse.cpp │ ├── main.cpp │ ├── server.cpp │ └── ssocket.cpp └── test │ ├── test.cpp │ └── test_utils.cpp ├── version_0.3 ├── include │ ├── condition.h │ ├── epoll.h │ ├── http_data.h │ ├── http_parse.h │ ├── http_request.h │ ├── http_response.h │ ├── ini_file.h │ ├── ini_section.h │ ├── logger.h │ ├── mutex_lock.h │ ├── noncopyable.h │ ├── server.h │ ├── socket.h │ ├── thread_pool.h │ ├── timer.h │ └── util.h ├── src │ ├── epoll.cpp │ ├── http │ │ ├── http_data.cpp │ │ ├── http_parse.cpp │ │ ├── http_request.cpp │ │ ├── http_response.cpp │ │ └── server.cpp │ ├── main.cpp │ ├── socket.cpp │ ├── thread_pool.cpp │ ├── timer.cpp │ └── util │ │ ├── ini_file.cpp │ │ ├── ini_section.cpp │ │ ├── logger.cpp │ │ └── util.cpp ├── test │ ├── test.cpp │ └── test_utils.cpp └── 开发问题记录.md ├── 性能测试分析.md └── 整体设计.md /.clang-format: -------------------------------------------------------------------------------- 1 | # 语言: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto 2 | Language: Cpp 3 | # 基于某一主题上的修改 4 | BasedOnStyle: Google 5 | Standard: c++11 6 | 7 | #单行长度限制 8 | ColumnLimit: 120 9 | # 缩进宽度 10 | IndentWidth: 2 11 | # 缩进case标签 12 | IndentCaseLabels: true 13 | # 访问说明符(public、private等)的偏移 14 | AccessModifierOffset: -2 15 | 16 | IncludeBlocks: Regroup 17 | 18 | IncludeCategories: 19 | # Standard C Lirary (https://en.cppreference.com/w/c/header) 20 | - Regex: '^<(assert\.h|complex\.h|ctype\.h|errno\.h|fenv\.h|float\.h|inttypes\.h|iso646\.h|limits\.h|locale\.h|math\.h|setjmp\.h|signal\.h|stdalign\.h|stdarg\.h|stdatomic\.h|stdbool\.h|stddef\.h|stdint\.h|stdio\.h|stdlib\.h|stdnoreturn\.h|string\.h|tgmath\.h|threads\.h|time\.h|uchar\.h|wchar\.h|wctype\.h)>$' 21 | Priority: 1 22 | 23 | # Standard C++ Lirary 24 | - Regex: '^<(algorithm|any|array|atomic|bitset|cassert|ccomplex|cctype|cerrno|cfenv|cfloat|charconv|chrono|cinttypes|ciso646|climits|clocale|cmath|codecvt|compare|complex|condition_variable|csetjmp|csignal|cstdarg|cstdbool|cstddef|cstdint|cstdio|cstdlib|cstring|ctgmath|ctime|cwchar|cwctype|deque|exception|experimental/algorithm|experimental/any|experimental/chrono|experimental/coroutine|experimental/deque|experimental/dynarray|experimental/filesystem|experimental/forward_list|experimental/functional|experimental/iterator|experimental/list|experimental/map|experimental/memory_resource|experimental/numeric|experimental/optional|experimental/propagate_const|experimental/ratio|experimental/regex|experimental/set|experimental/simd|experimental/string|experimental/string_view|experimental/system_error|experimental/tuple|experimental/type_traits|experimental/unordered_map|experimental/unordered_set|experimental/utility|experimental/vector|ext/hash_map|ext/hash_set|filesystem|forward_list|fstream|functional|future|initializer_list|iomanip|ios|iosfwd|iostream|istream|iterator|limits|list|locale|map|memory|mutex|new|numeric|optional|ostream|queue|random|ratio|regex|scoped_allocator|set|shared_mutex|span|sstream|stack|stdexcept|streambuf|string|string_view|strstream|support/android|support/fuchsia|support/ibm|support/musl|support/newlib|support/solaris|support/win32|support/xlocale|system_error|thread|tuple|type_traits|typeindex|typeinfo|unordered_map|unordered_set|utility|valarray|variant|vector|version)>$' 25 | Priority: 10 26 | 27 | # Headers in <> with extension. (linux headers) 28 | - Regex: '^<([A-Za-z0-9.\Q/-_\E])+>$' 29 | Priority: 2 30 | 31 | # Headers in <> without extension. (system wide C++ headers) 32 | - Regex: '^<([A-Za-z0-9\Q/-_\E])+>$' 33 | Priority: 11 34 | 35 | # 行注释 "//" 前增加两个空格 36 | SpacesBeforeTrailingComments: 2 37 | 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # idea files 2 | cmake-build-debug 3 | .*/ 4 | CMakeCache.txt 5 | CMakeFiles/ 6 | cmake_install.cmake 7 | Makefile 8 | # Object files 9 | *.o 10 | *.ko 11 | *.obj 12 | *.elf 13 | 14 | 15 | # Libraries 16 | *.lib 17 | *.a 18 | *.la 19 | *.lo 20 | 21 | # Shared objects (inc. Windows DLLs) 22 | *.dll 23 | *.so 24 | *.so.* 25 | *.dylib 26 | 27 | # Executables 28 | *.exe 29 | *.out 30 | *.app 31 | *.i*86 32 | *.x86_64 33 | *.hex 34 | webserver 35 | cmake_install.cmake -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: learn 2 | 3 | sudo: required 4 | 5 | language: 6 | 7 | - cpp 8 | 9 | compiler: 10 | - g++ 11 | 12 | os: 13 | - linux 14 | 15 | install: 16 | - sudo apt-get install cmake 17 | 18 | script: 19 | - cmake . && make 20 | 21 | 22 | branches: 23 | only: 24 | - master 25 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.5) 2 | project(webserver) 3 | 4 | set(CMAKE_CXX_STANDARD 11) 5 | #aux_source_directory(version_0.1/test SRC_DIR) 6 | 7 | 8 | #aux_source_directory(version_0.3/src SRC_DIR) 9 | 10 | #set(SOURCE_FILES 11 | # version_0.2/src/httpparse.cpp 12 | # version_0.2/src/httpresponse.cpp 13 | # version_0.2/src/main.cpp 14 | # version_0.2/src/server.cpp 15 | # version_0.2/src/ssocket.cpp 16 | # version_0.2/src/ThreadPool.cpp 17 | # version_0.2/src/Util.cpp 18 | # ) 19 | 20 | 21 | set(CXX_FLAGS 22 | -Wall 23 | -std=c++11 24 | -lpthread 25 | -Wno-unused-parameter 26 | -O3 27 | ) 28 | 29 | link_libraries(pthread) 30 | 31 | set(CMAKE_BUILD_TYPE "Release") 32 | 33 | set(CMAKE_CXX_COMPILER "g++") 34 | set(CMAKE_CXX_FLAGS_DEBUG "-O3") 35 | 36 | SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3") 37 | 38 | 39 | set(SOURCE_FILES 40 | version_0.3/src/http/http_request.cpp 41 | version_0.3/src/http/http_data.cpp 42 | version_0.3/src/http/http_parse.cpp 43 | version_0.3/src/http/http_response.cpp 44 | version_0.3/src/http/server.cpp 45 | version_0.3/src/util/util.cpp 46 | version_0.3/src/util/ini_file.cpp 47 | version_0.3/src/util/ini_section.cpp 48 | version_0.3/src/util/logger.cpp 49 | version_0.3/src/socket.cpp 50 | version_0.3/src/thread_pool.cpp 51 | version_0.3/src/timer.cpp 52 | version_0.3/src/epoll.cpp 53 | version_0.3/src/main.cpp 54 | ) 55 | 56 | add_executable(webserver ${SOURCE_FILES}) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 marvinle 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A C++ Lightweight Web Server 2 | 3 | 4 | [![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://opensource.org/licenses/MIT) 5 | [![Build Status](https://travis-ci.org/MarvinLe/WebServer.svg?branch=master)](https://travis-ci.org/MarvinLe/WebServer) 6 | 7 | 8 | ## 简介 9 | 10 | 这是一个轻量级的Web服务器,目前支持GET、HEAD方法处理静态资源。并发模型选择: 单进程+Reactor+非阻塞方式运行。 11 | 12 | 测试页面: [http://how2cs.cn:8080/](http://how2cs.cn:8080/) 13 | 14 | 15 | --- 16 | 17 | | Part Ⅰ | Part Ⅱ | 18 | | :---------: | :---------: | 19 | | [整体设计](https://github.com/MarvinLe/WebServer/blob/master/%E6%95%B4%E4%BD%93%E8%AE%BE%E8%AE%A1.md)| [性能测试分析](https://github.com/MarvinLe/WebServer/blob/master/%E6%80%A7%E8%83%BD%E6%B5%8B%E8%AF%95%E5%88%86%E6%9E%90.md) | 20 | 21 | --- 22 | 23 | ## 开发部署环境 24 | 25 | + 操作系统: Ubuntu 16.04 26 | 27 | + 编译器: g++ 5.4 28 | 29 | + 版本控制: git 30 | 31 | + 自动化构建: cmake 32 | 33 | + 集成开发工具: CLion 34 | 35 | + 编辑器: Vim 36 | 37 | + 压测工具:[WebBench](https://github.com/EZLippi/WebBench) 38 | 39 | 40 | 41 | ## Usage 42 | 43 | ``` 44 | cmake . && make 45 | 46 | ./webserver [-f config_file] 47 | ``` 48 | 配置文件可以使用默认的 config.ini 49 | 50 | ## 核心功能及技术 51 | 52 | + 状态机解析HTTP请求,目前支持 HTTP GET、HEAD方法 53 | 54 | + 添加定时器支持HTTP长连接,定时回调handler处理超时连接 55 | 56 | + 使用 priority queue 实现的最小堆结构管理定时器,使用标记删除,以支持惰性删除,提高性能 57 | 58 | + 使用epoll + 非阻塞IO + 边缘触发(ET) 实现高并发处理请求,使用Reactor编程模型 59 | 60 | + epoll使用EPOLLONESHOT保证一个socket连接在任意时刻都只被一个线程处理 61 | 62 | + 使用线程池提高并发度,并降低频繁创建线程的开销 63 | + 同步互斥的介绍 64 | 65 | + 使用RAII手法封装互斥器(pthrea_mutex_t)、 条件变量(pthread_cond_t)等线程同步互斥机制,使用RAII管理文件描述符等资源 66 | 67 | + 使用shared_ptr、weak_ptr管理指针,防止内存泄漏 68 | 69 | 70 | 71 | ## 开发计划 72 | + 添加异步日志系统,记录服务器运行状态 73 | + 增加json配置文件,支持类似nginx的多网站配置 74 | + 提供CGI支持 75 | + 类似nginx的反向代理和负载均衡 76 | + 必要时增加可复用内存池 77 | -------------------------------------------------------------------------------- /WebBench/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /WebBench/Makefile: -------------------------------------------------------------------------------- 1 | CFLAGS?= -Wall -ggdb -W -O 2 | CC?= gcc 3 | LIBS?= 4 | LDFLAGS?= 5 | PREFIX?= /usr/local/webbench 6 | VERSION=1.5 7 | TMPDIR=/tmp/webbench-$(VERSION) 8 | 9 | all: webbench tags 10 | 11 | tags: *.c 12 | -ctags *.c 13 | 14 | install: webbench 15 | install -d $(DESTDIR)$(PREFIX)/bin 16 | install -s webbench $(DESTDIR)$(PREFIX)/bin 17 | ln -sf $(DESTDIR)$(PREFIX)/bin/webbench $(DESTDIR)/usr/local/bin/webbench 18 | 19 | install -d $(DESTDIR)/usr/local/man/man1 20 | install -d $(DESTDIR)$(PREFIX)/man/man1 21 | install -m 644 webbench.1 $(DESTDIR)$(PREFIX)/man/man1 22 | ln -sf $(DESTDIR)$(PREFIX)/man/man1/webbench.1 $(DESTDIR)/usr/local/man/man1/webbench.1 23 | 24 | install -d $(DESTDIR)$(PREFIX)/share/doc/webbench 25 | install -m 644 debian/copyright $(DESTDIR)$(PREFIX)/share/doc/webbench 26 | install -m 644 debian/changelog $(DESTDIR)$(PREFIX)/share/doc/webbench 27 | 28 | webbench: webbench.o Makefile 29 | $(CC) $(CFLAGS) $(LDFLAGS) -o webbench webbench.o $(LIBS) 30 | 31 | clean: 32 | -rm -f *.o webbench *~ core *.core tags 33 | 34 | tar: clean 35 | -debian/rules clean 36 | rm -rf $(TMPDIR) 37 | install -d $(TMPDIR) 38 | cp -p Makefile webbench.c socket.c webbench.1 $(TMPDIR) 39 | install -d $(TMPDIR)/debian 40 | -cp -p debian/* $(TMPDIR)/debian 41 | ln -sf debian/copyright $(TMPDIR)/COPYRIGHT 42 | ln -sf debian/changelog $(TMPDIR)/ChangeLog 43 | -cd $(TMPDIR) && cd .. && tar cozf webbench-$(VERSION).tar.gz webbench-$(VERSION) 44 | 45 | webbench.o: webbench.c socket.c Makefile 46 | 47 | .PHONY: clean install all tar 48 | -------------------------------------------------------------------------------- /WebBench/README.md: -------------------------------------------------------------------------------- 1 | # WebBench 2 | 3 | Webbench是一个在linux下使用的非常简单的网站压测工具。它使用fork()模拟多个客户端同时访问我们设定的URL,测试网站在压力下工作的性能,最多可以模拟3万个并发连接去测试网站的负载能力。 4 | 5 | ## 依赖 6 | ctags 7 | 8 | ## 使用: 9 | 10 | sudo make && sudo make install PREFIX=your_path_to_webbench 11 | 12 | ## 命令行选项: 13 | 14 | 15 | 16 | 17 | | 短参 | 长参数 | 作用 | 18 | | ------------- |:-------------:| -----:| 19 | |-f |--force |不需要等待服务器响应 | 20 | |-r |--reload |发送重新加载请求 | 21 | |-t |--time |运行多长时间,单位:秒" | 22 | |-p |--proxy |使用代理服务器来发送请求 | 23 | |-c |--clients |创建多少个客户端,默认1个" | 24 | |-9 |--http09 |使用 HTTP/0.9 | 25 | |-1 |--http10 |使用 HTTP/1.0 协议 | 26 | |-2 |--http11 |使用 HTTP/1.1 协议 | 27 | | |--get |使用 GET请求方法 | 28 | | |--head |使用 HEAD请求方法 | 29 | | |--options |使用 OPTIONS请求方法 | 30 | | |--trace |使用 TRACE请求方法 | 31 | |-?/-h |--help |打印帮助信息 | 32 | |-V |--version |显示版本号 | 33 | -------------------------------------------------------------------------------- /WebBench/debian/changelog: -------------------------------------------------------------------------------- 1 | webbench (1.5) unstable; urgency=low 2 | 3 | * allow building with both Gnu and BSD make 4 | 5 | -- Radim Kolar Fri, Jun 25 12:00:20 CEST 2004 6 | 7 | webbench (1.4) unstable; urgency=low 8 | 9 | * check if url is not too long 10 | * report correct program version number 11 | * use yield() when waiting for test start 12 | * corrected error codes 13 | * check availability of test server first 14 | * do not abort test if first request failed 15 | * report when some childrens are dead. 16 | * use alarm, not time() for lower syscal use by bench 17 | * use mode 644 for installed doc 18 | * makefile cleaned for better freebsd ports integration 19 | 20 | -- Radim Kolar Thu, 15 Jan 2004 11:15:52 +0100 21 | 22 | webbench (1.3) unstable; urgency=low 23 | 24 | * Build fixes for freeBSD 25 | * Default benchmark time 60 -> 30 26 | * generate tar with subdirectory 27 | * added to freeBSD ports collection 28 | 29 | -- Radim Kolar Mon, 12 Jan 2004 17:00:24 +0100 30 | 31 | webbench (1.2) unstable; urgency=low 32 | 33 | * Only debian-related bugfixes 34 | * Updated Debian/rules 35 | * Adapted to fit new directory system 36 | * moved from debstd to dh_* 37 | 38 | -- Radim Kolar Fri, 18 Jan 2002 12:33:04 +0100 39 | 40 | webbench (1.1) unstable; urgency=medium 41 | 42 | * Program debianized 43 | * added support for multiple methods (GET, HEAD, OPTIONS, TRACE) 44 | * added support for multiple HTTP versions (0.9 -- 1.1) 45 | * added long options 46 | * added multiple clients 47 | * wait for start of second before test 48 | * test time can be specified 49 | * better error checking when reading reply from server 50 | * FIX: tests was one second longer than expected 51 | 52 | -- Radim Kolar Thu, 16 Sep 1999 18:48:00 +0200 53 | 54 | Local variables: 55 | mode: debian-changelog 56 | End: 57 | -------------------------------------------------------------------------------- /WebBench/debian/control: -------------------------------------------------------------------------------- 1 | Source: webbench 2 | Section: web 3 | Priority: extra 4 | Maintainer: Radim Kolar 5 | Build-Depends: debhelper (>> 3.0.0) 6 | Standards-Version: 3.5.2 7 | 8 | Package: webbench 9 | Architecture: any 10 | Depends: ${shlibs:Depends} 11 | Description: Simple forking Web benchmark 12 | webbench is very simple program for benchmarking WWW or Proxy servers. 13 | Uses fork() for simulating multiple clients load. Can use HTTP 0.9 - 1.1 14 | requests, but Keep-Alive connections are not supported. 15 | -------------------------------------------------------------------------------- /WebBench/debian/copyright: -------------------------------------------------------------------------------- 1 | Webbench was written by Radim Kolar 1997-2004 (hsn@netmag.cz). 2 | 3 | UNIX sockets code (socket.c) taken from popclient 1.5 4/1/94 4 | public domain code, created by Virginia Tech Computing Center. 5 | 6 | Copyright: GPL (see /usr/share/common-licenses/GPL) 7 | -------------------------------------------------------------------------------- /WebBench/debian/dirs: -------------------------------------------------------------------------------- 1 | usr/bin -------------------------------------------------------------------------------- /WebBench/debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | # Sample debian/rules that uses debhelper. 3 | # GNU copyright 1997 to 1999 by Joey Hess. 4 | 5 | # Uncomment this to turn on verbose mode. 6 | #export DH_VERBOSE=1 7 | 8 | # This is the debhelper compatability version to use. 9 | export DH_COMPAT=3 10 | 11 | configure: configure-stamp 12 | configure-stamp: 13 | dh_testdir 14 | touch configure-stamp 15 | 16 | build: configure-stamp build-stamp 17 | build-stamp: 18 | dh_testdir 19 | $(MAKE) 20 | touch build-stamp 21 | 22 | clean: 23 | dh_testdir 24 | rm -f build-stamp configure-stamp 25 | 26 | # Add here commands to clean up after the build process. 27 | -$(MAKE) clean 28 | 29 | dh_clean 30 | 31 | install: build 32 | dh_testdir 33 | dh_testroot 34 | dh_clean -k 35 | dh_installdirs 36 | 37 | # Add here commands to install the package into debian/webbench. 38 | $(MAKE) install DESTDIR=$(CURDIR)/debian/webbench 39 | 40 | 41 | # Build architecture-independent files here. 42 | binary-indep: build install 43 | # We have nothing to do by default. 44 | 45 | # Build architecture-dependent files here. 46 | binary-arch: build install 47 | dh_testdir 48 | dh_testroot 49 | dh_installdocs 50 | dh_installman webbench.1 51 | dh_installchangelogs 52 | dh_link 53 | dh_strip 54 | dh_compress 55 | dh_fixperms 56 | # dh_makeshlibs 57 | dh_installdeb 58 | dh_shlibdeps 59 | dh_gencontrol 60 | dh_md5sums 61 | dh_builddeb 62 | 63 | binary: binary-indep binary-arch 64 | .PHONY: build clean binary-indep binary-arch binary install configure 65 | -------------------------------------------------------------------------------- /WebBench/socket.c: -------------------------------------------------------------------------------- 1 | /* $Id: socket.c 1.1 1995/01/01 07:11:14 cthuang Exp $ 2 | * 3 | * This module has been modified by Radim Kolar for OS/2 emx 4 | */ 5 | 6 | /*********************************************************************** 7 | module: socket.c 8 | program: popclient 9 | SCCS ID: @(#)socket.c 1.5 4/1/94 10 | programmer: Virginia Tech Computing Center 11 | compiler: DEC RISC C compiler (Ultrix 4.1) 12 | environment: DEC Ultrix 4.3 13 | description: UNIX sockets code. 14 | ***********************************************************************/ 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | int Socket(const char *host, int clientPort) { 31 | int sock; 32 | unsigned long inaddr; 33 | struct sockaddr_in ad; 34 | struct hostent *hp; 35 | 36 | memset(&ad, 0, sizeof(ad)); 37 | ad.sin_family = AF_INET; 38 | 39 | inaddr = inet_addr(host); 40 | if (inaddr != INADDR_NONE) 41 | memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr)); 42 | else { 43 | hp = gethostbyname(host); 44 | if (hp == NULL) return -1; 45 | memcpy(&ad.sin_addr, hp->h_addr, hp->h_length); 46 | } 47 | ad.sin_port = htons(clientPort); 48 | 49 | sock = socket(AF_INET, SOCK_STREAM, 0); 50 | if (sock < 0) return sock; 51 | if (connect(sock, (struct sockaddr *)&ad, sizeof(ad)) < 0) return -1; 52 | return sock; 53 | } 54 | -------------------------------------------------------------------------------- /WebBench/tags: -------------------------------------------------------------------------------- 1 | Mwebbench webbench.c /^int main(int argc, char *argv[])$/ 2 | Socket socket.c /^int Socket(const char *host, int clientPort)$/ 3 | alarm_handler webbench.c /^static void alarm_handler(int signal)$/ 4 | bench webbench.c /^static int bench(void)$/ 5 | benchcore webbench.c /^void benchcore(const char *host,const int port,con/ 6 | build_request webbench.c /^void build_request(const char *url)$/ 7 | usage webbench.c /^static void usage(void)$/ 8 | -------------------------------------------------------------------------------- /WebBench/test.sh: -------------------------------------------------------------------------------- 1 | ./webbench -t 600 -c 500 -2 --get http://cxyxh.top:8888/getProvData/%E5%8C%97%E4%BA%AC%E5%B8%82/2017 2 | -------------------------------------------------------------------------------- /WebBench/webbench: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imarvinle/WebServer/e94c6af586082e773527deaf8cde75e05177ca4f/WebBench/webbench -------------------------------------------------------------------------------- /WebBench/webbench.1: -------------------------------------------------------------------------------- 1 | -.TH WEBBENCH 1 "14 Jan 2004" 2 | -.\" NAME should be all caps, SECTION should be 1-8, maybe w/ subsection 3 | -.\" other parms are allowed: see man(7), man(1) 4 | -.SH NAME 5 | -webbench \- simple forking web benchmark 6 | -.SH SYNOPSIS 7 | -.B webbench 8 | -.I "[options] URL" 9 | -.br 10 | -.SH "AUTHOR" 11 | -This program and manual page was written by Radim Kolar, 12 | -for the 13 | -.B Supreme Personality of Godhead 14 | -(but may be used by others). 15 | -.SH "DESCRIPTION" 16 | -.B webbench 17 | -is simple program for benchmarking HTTP servers or any 18 | -other servers, which can be accessed via HTTP proxy. Unlike others 19 | -benchmarks, 20 | -.B webbench 21 | -uses multiple processes for simulating traffic 22 | -generated by multiple users. This allows better operating 23 | -on SMP systems and on systems with slow or buggy implementation 24 | -of select(). 25 | -.SH OPTIONS 26 | -The programs follow the usual GNU command line syntax, with long 27 | -options starting with two dashes (`-'). 28 | -A summary of options are included below. 29 | -.TP 30 | -.B \-?, \-h, \-\-help 31 | -Show summary of options. 32 | -.TP 33 | -.B \-v, \-\-version 34 | -Show version of program. 35 | -.TP 36 | -.B \-f, \-\-force 37 | -Do not wait for any response from server. Close connection after 38 | -request is send. This option produce quite a good denial of service 39 | -attack. 40 | -.TP 41 | -.B \-9, \-\-http09 42 | -Use HTTP/0.9 protocol, if possible. 43 | -.TP 44 | -.B \-1, \-\-http10 45 | -Use HTTP/1.0 protocol, if possible. 46 | -.TP 47 | -.B \-2, \-\-http11 48 | -Use HTTP/1.1 protocol (without 49 | -.I Keep-Alive 50 | -), if possible. 51 | -.TP 52 | -.B \-r, \-\-reload 53 | -Forces proxy to reload document. If proxy is not 54 | -set, option has no effect. 55 | -.TP 56 | -.B \-t, \-\-time 57 | -Run benchmark for 58 | -.I 59 | -seconds. Default value is 30. 60 | -.TP 61 | -.B \-p, \-\-proxy 62 | -Send request via proxy server. Needed for supporting others protocols 63 | -than HTTP. 64 | -.TP 65 | -.B \-\-get 66 | -Use GET request method. 67 | -.TP 68 | -.B \-\-head 69 | -Use HEAD request method. 70 | -.TP 71 | -.B \-\-options 72 | -Use OPTIONS request method. 73 | -.TP 74 | -.B \-\-trace 75 | -Use TRACE request method. 76 | -.TP 77 | -.B \-c, \-\-clients 78 | -Use 79 | -.I 80 | -multiple clients for benchmark. Default value 81 | -is 1. 82 | -.SH "EXIT STATUS" 83 | -.TP 84 | -0 - sucess 85 | -.TP 86 | -1 - benchmark failed, can not connect to server 87 | -.TP 88 | -2 - bad command line argument(s) 89 | -.TP 90 | -3 - internal error, i.e. fork failed 91 | -.SH "TODO" 92 | -Include support for using 93 | -.I Keep-Alive 94 | -HTTP/1.1 connections. 95 | -.SH "COPYING" 96 | -Webbench is distributed under GPL. Copyright 1997-2004 97 | -Radim Kolar (hsn@netmag.cz). 98 | -UNIX sockets code taken from popclient 1.5 4/1/94 99 | -public domain code, created by Virginia Tech Computing Center. 100 | -.BR 101 | -This man page is public domain. 102 | -------------------------------------------------------------------------------- /WebBench/webbench.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Radim Kolar 1997-2004 3 | * This is free software, see GNU Public License version 2 for 4 | * details. 5 | * 6 | * Simple forking WWW Server benchmark: 7 | * 8 | * Usage: 9 | * webbench --help 10 | * 11 | * Return codes: 12 | * 0 - sucess 13 | * 1 - benchmark failed (server is not on-line) 14 | * 2 - bad param 15 | * 3 - internal error, fork failed 16 | * 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include "socket.c" 29 | 30 | /* values */ 31 | volatile int timerexpired = 0; 32 | int speed = 0; 33 | int failed = 0; 34 | int bytes = 0; 35 | 36 | /* globals */ 37 | int http10 = 1; /* 0 - http/0.9, 1 - http/1.0, 2 - http/1.1 */ 38 | /* Allow: GET, HEAD, OPTIONS, TRACE */ 39 | #define METHOD_GET 0 40 | #define METHOD_HEAD 1 41 | #define METHOD_OPTIONS 2 42 | #define METHOD_TRACE 3 43 | #define PROGRAM_VERSION "1.5" 44 | int method = METHOD_GET; 45 | int clients = 1; 46 | int force = 0; 47 | int force_reload = 0; 48 | int proxyport = 80; 49 | char *proxyhost = NULL; 50 | int benchtime = 30; 51 | 52 | /* internal */ 53 | int mypipe[2]; 54 | char host[MAXHOSTNAMELEN]; 55 | #define REQUEST_SIZE 2048 56 | char request[REQUEST_SIZE]; 57 | 58 | static const struct option long_options[] = {{"force", no_argument, &force, 1}, 59 | {"reload", no_argument, &force_reload, 1}, 60 | {"time", required_argument, NULL, 't'}, 61 | {"help", no_argument, NULL, '?'}, 62 | {"http09", no_argument, NULL, '9'}, 63 | {"http10", no_argument, NULL, '1'}, 64 | {"http11", no_argument, NULL, '2'}, 65 | {"get", no_argument, &method, METHOD_GET}, 66 | {"head", no_argument, &method, METHOD_HEAD}, 67 | {"options", no_argument, &method, METHOD_OPTIONS}, 68 | {"trace", no_argument, &method, METHOD_TRACE}, 69 | {"version", no_argument, NULL, 'V'}, 70 | {"proxy", required_argument, NULL, 'p'}, 71 | {"clients", required_argument, NULL, 'c'}, 72 | {NULL, 0, NULL, 0}}; 73 | 74 | /* prototypes */ 75 | static void benchcore(const char *host, const int port, const char *request); 76 | static int bench(void); 77 | static void build_request(const char *url); 78 | 79 | static void alarm_handler(int signal) { timerexpired = 1; } 80 | 81 | static void usage(void) { 82 | fprintf(stderr, 83 | "webbench [option]... URL\n" 84 | " -f|--force Don't wait for reply from server.\n" 85 | " -r|--reload Send reload request - Pragma: no-cache.\n" 86 | " -t|--time Run benchmark for seconds. Default " 87 | "30.\n" 88 | " -p|--proxy Use proxy server for request.\n" 89 | " -c|--clients Run HTTP clients at once. Default one.\n" 90 | " -9|--http09 Use HTTP/0.9 style requests.\n" 91 | " -1|--http10 Use HTTP/1.0 protocol.\n" 92 | " -2|--http11 Use HTTP/1.1 protocol.\n" 93 | " --get Use GET request method.\n" 94 | " --head Use HEAD request method.\n" 95 | " --options Use OPTIONS request method.\n" 96 | " --trace Use TRACE request method.\n" 97 | " -?|-h|--help This information.\n" 98 | " -V|--version Display program version.\n"); 99 | } 100 | 101 | int main(int argc, char *argv[]) { 102 | int opt = 0; 103 | int options_index = 0; 104 | char *tmp = NULL; 105 | 106 | if (argc == 1) { 107 | usage(); 108 | return 2; 109 | } 110 | 111 | while ((opt = getopt_long(argc, argv, "912Vfrt:p:c:?h", long_options, &options_index)) != EOF) { 112 | switch (opt) { 113 | case 0: 114 | break; 115 | case 'f': 116 | force = 1; 117 | break; 118 | case 'r': 119 | force_reload = 1; 120 | break; 121 | case '9': 122 | http10 = 0; 123 | break; 124 | case '1': 125 | http10 = 1; 126 | break; 127 | case '2': 128 | http10 = 2; 129 | break; 130 | case 'V': 131 | printf(PROGRAM_VERSION "\n"); 132 | exit(0); 133 | case 't': 134 | benchtime = atoi(optarg); 135 | break; 136 | case 'p': 137 | /* proxy server parsing server:port */ 138 | tmp = strrchr(optarg, ':'); 139 | proxyhost = optarg; 140 | if (tmp == NULL) { 141 | break; 142 | } 143 | if (tmp == optarg) { 144 | fprintf(stderr, "Error in option --proxy %s: Missing hostname.\n", optarg); 145 | return 2; 146 | } 147 | if (tmp == optarg + strlen(optarg) - 1) { 148 | fprintf(stderr, "Error in option --proxy %s Port number is missing.\n", optarg); 149 | return 2; 150 | } 151 | *tmp = '\0'; 152 | proxyport = atoi(tmp + 1); 153 | break; 154 | case ':': 155 | case 'h': 156 | case '?': 157 | usage(); 158 | return 2; 159 | break; 160 | case 'c': 161 | clients = atoi(optarg); 162 | break; 163 | } 164 | } 165 | 166 | if (optind == argc) { 167 | fprintf(stderr, "webbench: Missing URL!\n"); 168 | usage(); 169 | return 2; 170 | } 171 | 172 | if (clients == 0) clients = 1; 173 | if (benchtime == 0) benchtime = 30; 174 | 175 | /* Copyright */ 176 | fprintf(stderr, "Webbench - Simple Web Benchmark " PROGRAM_VERSION 177 | "\n" 178 | "Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n"); 179 | 180 | build_request(argv[optind]); 181 | 182 | // print request info ,do it in function build_request 183 | /*printf("Benchmarking: "); 184 | 185 | switch(method) 186 | { 187 | case METHOD_GET: 188 | default: 189 | printf("GET");break; 190 | case METHOD_OPTIONS: 191 | printf("OPTIONS");break; 192 | case METHOD_HEAD: 193 | printf("HEAD");break; 194 | case METHOD_TRACE: 195 | printf("TRACE");break; 196 | } 197 | 198 | printf(" %s",argv[optind]); 199 | 200 | switch(http10) 201 | { 202 | case 0: printf(" (using HTTP/0.9)");break; 203 | case 2: printf(" (using HTTP/1.1)");break; 204 | } 205 | 206 | printf("\n"); 207 | */ 208 | 209 | printf("Runing info: "); 210 | 211 | if (clients == 1) 212 | printf("1 client"); 213 | else 214 | printf("%d clients", clients); 215 | 216 | printf(", running %d sec", benchtime); 217 | 218 | if (force) printf(", early socket close"); 219 | if (proxyhost != NULL) printf(", via proxy server %s:%d", proxyhost, proxyport); 220 | if (force_reload) printf(", forcing reload"); 221 | 222 | printf(".\n"); 223 | 224 | return bench(); 225 | } 226 | 227 | void build_request(const char *url) { 228 | char tmp[10]; 229 | int i; 230 | 231 | // bzero(host,MAXHOSTNAMELEN); 232 | // bzero(request,REQUEST_SIZE); 233 | memset(host, 0, MAXHOSTNAMELEN); 234 | memset(request, 0, REQUEST_SIZE); 235 | 236 | if (force_reload && proxyhost != NULL && http10 < 1) http10 = 1; 237 | if (method == METHOD_HEAD && http10 < 1) http10 = 1; 238 | if (method == METHOD_OPTIONS && http10 < 2) http10 = 2; 239 | if (method == METHOD_TRACE && http10 < 2) http10 = 2; 240 | 241 | switch (method) { 242 | default: 243 | case METHOD_GET: 244 | strcpy(request, "GET"); 245 | break; 246 | case METHOD_HEAD: 247 | strcpy(request, "HEAD"); 248 | break; 249 | case METHOD_OPTIONS: 250 | strcpy(request, "OPTIONS"); 251 | break; 252 | case METHOD_TRACE: 253 | strcpy(request, "TRACE"); 254 | break; 255 | } 256 | 257 | strcat(request, " "); 258 | 259 | if (NULL == strstr(url, "://")) { 260 | fprintf(stderr, "\n%s: is not a valid URL.\n", url); 261 | exit(2); 262 | } 263 | if (strlen(url) > 1500) { 264 | fprintf(stderr, "URL is too long.\n"); 265 | exit(2); 266 | } 267 | if (0 != strncasecmp("http://", url, 7)) { 268 | fprintf(stderr, 269 | "\nOnly HTTP protocol is directly supported, set --proxy for " 270 | "others.\n"); 271 | exit(2); 272 | } 273 | 274 | /* protocol/host delimiter */ 275 | i = strstr(url, "://") - url + 3; 276 | 277 | if (strchr(url + i, '/') == NULL) { 278 | fprintf(stderr, "\nInvalid URL syntax - hostname don't ends with '/'.\n"); 279 | exit(2); 280 | } 281 | 282 | if (proxyhost == NULL) { 283 | /* get port from hostname */ 284 | if (index(url + i, ':') != NULL && index(url + i, ':') < index(url + i, '/')) { 285 | strncpy(host, url + i, strchr(url + i, ':') - url - i); 286 | // bzero(tmp,10); 287 | memset(tmp, 0, 10); 288 | strncpy(tmp, index(url + i, ':') + 1, strchr(url + i, '/') - index(url + i, ':') - 1); 289 | /* printf("tmp=%s\n",tmp); */ 290 | proxyport = atoi(tmp); 291 | if (proxyport == 0) proxyport = 80; 292 | } else { 293 | strncpy(host, url + i, strcspn(url + i, "/")); 294 | } 295 | // printf("Host=%s\n",host); 296 | strcat(request + strlen(request), url + i + strcspn(url + i, "/")); 297 | } else { 298 | // printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport); 299 | strcat(request, url); 300 | } 301 | 302 | if (http10 == 1) 303 | strcat(request, " HTTP/1.0"); 304 | else if (http10 == 2) 305 | strcat(request, " HTTP/1.1"); 306 | 307 | strcat(request, "\r\n"); 308 | 309 | if (http10 > 0) strcat(request, "User-Agent: WebBench " PROGRAM_VERSION "\r\n"); 310 | if (proxyhost == NULL && http10 > 0) { 311 | strcat(request, "Host: "); 312 | strcat(request, host); 313 | strcat(request, "\r\n"); 314 | } 315 | 316 | if (force_reload && proxyhost != NULL) { 317 | strcat(request, "Pragma: no-cache\r\n"); 318 | } 319 | 320 | if (http10 > 1) strcat(request, "Connection: close\r\n"); 321 | 322 | /* add empty line at end */ 323 | if (http10 > 0) strcat(request, "\r\n"); 324 | 325 | printf("\nRequest:\n%s\n", request); 326 | } 327 | 328 | /* vraci system rc error kod */ 329 | static int bench(void) { 330 | int i, j, k; 331 | pid_t pid = 0; 332 | FILE *f; 333 | 334 | /* check avaibility of target server */ 335 | i = Socket(proxyhost == NULL ? host : proxyhost, proxyport); 336 | if (i < 0) { 337 | fprintf(stderr, "\nConnect to server failed. Aborting benchmark.\n"); 338 | return 1; 339 | } 340 | close(i); 341 | 342 | /* create pipe */ 343 | if (pipe(mypipe)) { 344 | perror("pipe failed."); 345 | return 3; 346 | } 347 | 348 | /* not needed, since we have alarm() in childrens */ 349 | /* wait 4 next system clock tick */ 350 | /* 351 | cas=time(NULL); 352 | while(time(NULL)==cas) 353 | sched_yield(); 354 | */ 355 | 356 | /* fork childs */ 357 | for (i = 0; i < clients; i++) { 358 | pid = fork(); 359 | if (pid <= (pid_t)0) { 360 | /* child process or error*/ 361 | sleep(1); /* make childs faster */ 362 | break; 363 | } 364 | } 365 | 366 | if (pid < (pid_t)0) { 367 | fprintf(stderr, "problems forking worker no. %d\n", i); 368 | perror("fork failed."); 369 | return 3; 370 | } 371 | 372 | if (pid == (pid_t)0) { 373 | /* I am a child */ 374 | if (proxyhost == NULL) 375 | benchcore(host, proxyport, request); 376 | else 377 | benchcore(proxyhost, proxyport, request); 378 | 379 | /* write results to pipe */ 380 | f = fdopen(mypipe[1], "w"); 381 | if (f == NULL) { 382 | perror("open pipe for writing failed."); 383 | return 3; 384 | } 385 | /* fprintf(stderr,"Child - %d %d\n",speed,failed); */ 386 | fprintf(f, "%d %d %d\n", speed, failed, bytes); 387 | fclose(f); 388 | 389 | return 0; 390 | } else { 391 | f = fdopen(mypipe[0], "r"); 392 | if (f == NULL) { 393 | perror("open pipe for reading failed."); 394 | return 3; 395 | } 396 | 397 | setvbuf(f, NULL, _IONBF, 0); 398 | 399 | speed = 0; 400 | failed = 0; 401 | bytes = 0; 402 | 403 | while (1) { 404 | pid = fscanf(f, "%d %d %d", &i, &j, &k); 405 | if (pid < 2) { 406 | fprintf(stderr, "Some of our childrens died.\n"); 407 | break; 408 | } 409 | 410 | speed += i; 411 | failed += j; 412 | bytes += k; 413 | 414 | /* fprintf(stderr,"*Knock* %d %d read=%d\n",speed,failed,pid); */ 415 | if (--clients == 0) break; 416 | } 417 | 418 | fclose(f); 419 | 420 | printf( 421 | "\nSpeed=%d pages/min, %d bytes/sec.\nRequests: %d susceed, %d " 422 | "failed.\n", 423 | (int)((speed + failed) / (benchtime / 60.0f)), (int)(bytes / (float)benchtime), speed, failed); 424 | } 425 | 426 | return i; 427 | } 428 | 429 | void benchcore(const char *host, const int port, const char *req) { 430 | int rlen; 431 | char buf[1500]; 432 | int s, i; 433 | struct sigaction sa; 434 | 435 | /* setup alarm signal handler */ 436 | sa.sa_handler = alarm_handler; 437 | sa.sa_flags = 0; 438 | if (sigaction(SIGALRM, &sa, NULL)) exit(3); 439 | 440 | alarm(benchtime); // after benchtime,then exit 441 | 442 | rlen = strlen(req); 443 | nexttry: 444 | while (1) { 445 | if (timerexpired) { 446 | if (failed > 0) { 447 | /* fprintf(stderr,"Correcting failed by signal\n"); */ 448 | failed--; 449 | } 450 | return; 451 | } 452 | 453 | s = Socket(host, port); 454 | if (s < 0) { 455 | failed++; 456 | continue; 457 | } 458 | if (rlen != write(s, req, rlen)) { 459 | failed++; 460 | close(s); 461 | continue; 462 | } 463 | if (http10 == 0) 464 | if (shutdown(s, 1)) { 465 | failed++; 466 | close(s); 467 | continue; 468 | } 469 | if (force == 0) { 470 | /* read all available data from socket */ 471 | while (1) { 472 | if (timerexpired) break; 473 | i = read(s, buf, 1500); 474 | /* fprintf(stderr,"%d\n",i); */ 475 | if (i < 0) { 476 | failed++; 477 | close(s); 478 | goto nexttry; 479 | } else if (i == 0) 480 | break; 481 | else 482 | bytes += i; 483 | } 484 | } 485 | if (close(s)) { 486 | failed++; 487 | continue; 488 | } 489 | speed++; 490 | } 491 | } 492 | -------------------------------------------------------------------------------- /config.ini: -------------------------------------------------------------------------------- 1 | [Worker] 2 | thread_num=4 3 | port=8080 4 | daemon=1 5 | 6 | [Server] 7 | server_name=how2cs.cn 8 | root=/root/www/ 9 | -------------------------------------------------------------------------------- /pages/403.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 403 Forbidden 6 | 13 | 14 | 15 | 16 |
17 |

403 Forbidden

18 |
19 |
20 |
LCWebserver/0.3 (Ubuntu)
21 | 22 | 23 | -------------------------------------------------------------------------------- /pages/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 404 Not Found 6 | 13 | 14 | 15 | 16 |
17 |

404 Not Found

18 |
19 |
20 |
CSGuide WebServer/0.3 (Ubuntu)
21 | 22 | 23 | -------------------------------------------------------------------------------- /pages/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Welcome to CSGuide! 6 | 13 | 14 | 15 |

Welcome to CSGuide WebServer !

16 |

If you see this page, the CSGuide WebServer is successfully installed and 17 | working.

18 | 19 |

For online documentation and support please refer to 20 | CSGuide WebServer.
21 | 22 |

Thank you for using CSGuide WebServer.

23 |

By 编程指北

24 | 25 | -------------------------------------------------------------------------------- /version_0.1/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imarvinle/WebServer/e94c6af586082e773527deaf8cde75e05177ca4f/version_0.1/.DS_Store -------------------------------------------------------------------------------- /version_0.1/include/httpparse.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #ifndef WEBSERVER_HTTPPARSE_H 6 | #define WEBSERVER_HTTPPARSE_H 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #define CR '\r' 13 | #define LF '\n' 14 | #define LINE_END '\0' 15 | #define PASS 16 | 17 | namespace http { 18 | 19 | class HttpRequest; 20 | 21 | std::ostream &operator<<(std::ostream &, const HttpRequest &); 22 | 23 | class HttpRequestParser { 24 | public: 25 | enum LINE_STATE { LINE_OK = 0, LINE_BAD, LINE_MORE }; 26 | enum PARSE_STATE { PARSE_REQUESTLINE = 0, PARSE_HEADER, PARSE_BODY }; 27 | enum HTTP_CODE { NO_REQUEST, GET_REQUEST, BAD_REQUEST, FORBIDDEN_REQUEST, INTERNAL_ERROR, CLOSED_CONNECTION }; 28 | 29 | static LINE_STATE parse_line(char *buffer, int &checked_index, int &read_index); 30 | static HTTP_CODE parse_requestline(char *line, PARSE_STATE &parse_state, HttpRequest &request); 31 | static HTTP_CODE parse_headers(char *line, PARSE_STATE &parse_state, HttpRequest &request); 32 | static HTTP_CODE parse_body(char *body, HttpRequest &request); 33 | static HTTP_CODE parse_content(char *buffer, int &check_index, int &read_index, PARSE_STATE &parse_state, 34 | int &start_line, HttpRequest &request); 35 | }; 36 | 37 | struct HttpRequest { 38 | friend std::ostream &operator<<(std::ostream &, const HttpRequest &); 39 | 40 | enum HTTP_VERSION { HTTP_10 = 0, HTTP_11, VERSION_NOT_SUPPORT }; 41 | enum HTTP_METHOD { GET = 0, POST, PUT, DELETE, METHOD_NOT_SUPPORT }; 42 | enum HTTP_HEADER { 43 | Host = 0, 44 | User_Agent, 45 | Connection, 46 | Accept_Encoding, 47 | Accept_Language, 48 | Accept, 49 | Cache_Control, 50 | Upgrade_Insecure_Requests 51 | }; 52 | struct EnumClassHash { 53 | template 54 | std::size_t operator()(T t) const { 55 | return static_cast(t); 56 | } 57 | }; 58 | 59 | static std::unordered_map header_map; 60 | 61 | HttpRequest(std::string url = std::string(""), HTTP_METHOD method = METHOD_NOT_SUPPORT, 62 | HTTP_VERSION version = VERSION_NOT_SUPPORT) 63 | : mMethod(method), 64 | mVersion(version), 65 | mUri(url), 66 | mContent(nullptr), 67 | mHeaders(std::unordered_map()){}; 68 | 69 | HTTP_METHOD mMethod; 70 | HTTP_VERSION mVersion; 71 | std::string mUri; 72 | char *mContent; 73 | std::unordered_map mHeaders; 74 | }; 75 | 76 | } // namespace http 77 | 78 | #endif // WEBSERVER_HTTPPARSE_H 79 | -------------------------------------------------------------------------------- /version_0.1/include/httpresponse.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #ifndef WEBSERVER_HTTPRESPONSE_H 6 | #define WEBSERVER_HTTPRESPONSE_H 7 | 8 | #include 9 | #include 10 | 11 | #include "httpparse.h" 12 | 13 | #define BASEPATH 14 | 15 | namespace http { 16 | 17 | struct MimeType { 18 | MimeType(const std::string &str) : type(str){}; 19 | MimeType(const char *str) : type(str){}; 20 | 21 | std::string type; 22 | }; 23 | 24 | extern std::unordered_map Mime_map; 25 | 26 | class HttpResponse { 27 | public: 28 | enum HttpStatusCode { Unknow, k200Ok = 200, k403forbiden = 403, k404NotFound = 404 }; 29 | 30 | explicit HttpResponse(bool close) 31 | : mStatusCode(Unknow), 32 | mCloseConnection(close), 33 | mMime("text/html"), 34 | mBody(nullptr), 35 | mVersion(HttpRequest::HTTP_11) {} 36 | 37 | void setStatusCode(HttpStatusCode code) { mStatusCode = code; } 38 | void setBody(const char *buf) { mBody = buf; } 39 | void setContentLength(int len) { mContentLength = len; } 40 | void setVersion(const HttpRequest::HTTP_VERSION &version) { mVersion = version; } 41 | 42 | void setStatusMsg(const std::string &msg) { mStatusMsg = msg; } 43 | void setFilePath(const std::string &path) { mFilePath = path; } 44 | void setMime(const MimeType &mime) { mMime = mime; } 45 | 46 | void addHeader(const std::string &key, const std::string &value) { mHeaders[key] = value; } 47 | bool closeConnection() const { return mCloseConnection; } 48 | const HttpRequest::HTTP_VERSION version() const { return mVersion; } 49 | const std::string &filePath() const { return mFilePath; } 50 | HttpStatusCode statusCode() const { return mStatusCode; } 51 | const std::string &statusMsg() const { return mStatusMsg; } 52 | 53 | void appenBuffer(char *) const; 54 | 55 | ~HttpResponse() { 56 | if (mBody != nullptr) delete[] mBody; 57 | } 58 | 59 | private: 60 | HttpStatusCode mStatusCode; 61 | HttpRequest::HTTP_VERSION mVersion; 62 | std::string mStatusMsg; 63 | bool mCloseConnection; 64 | MimeType mMime; 65 | const char *mBody; 66 | int mContentLength; 67 | std::string mFilePath; 68 | std::unordered_map mHeaders; 69 | }; 70 | 71 | } // namespace http 72 | 73 | #endif // WEBSERVER_HTTPRESPONSE_H 74 | -------------------------------------------------------------------------------- /version_0.1/include/server.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_SERVER_H 7 | #define WEBSERVER_SERVER_H 8 | 9 | #include "httpparse.h" 10 | #include "httpresponse.h" 11 | #include "ssocket.h" 12 | 13 | #define BUFFERSIZE 1024 14 | 15 | namespace server { 16 | 17 | class HttpServer { 18 | public: 19 | explicit HttpServer(int port = 80, const char *ip = nullptr) : serverSocket(port, ip) { 20 | serverSocket.bind(); 21 | serverSocket.listen(); 22 | } 23 | 24 | void run(); 25 | 26 | private: 27 | void do_request(const nsocket::ClientSocket &); 28 | void header(const http::HttpRequest &, http::HttpResponse &); 29 | void static_file(http::HttpResponse &, const char *); 30 | void send(const http::HttpResponse &, const nsocket::ClientSocket &); 31 | void getMime(const http::HttpRequest &, http::HttpResponse &); 32 | 33 | nsocket::ServerSocket serverSocket; 34 | }; 35 | } // namespace server 36 | 37 | #endif // WEBSERVER_SERVER_H 38 | -------------------------------------------------------------------------------- /version_0.1/include/ssocket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_SOCKET_H 7 | #define WEBSERVER_SOCKET_H 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | 16 | namespace nsocket { 17 | class ClientSocket; 18 | 19 | void setReusePort(int fd); 20 | 21 | class ServerSocket { 22 | public: 23 | ServerSocket(int port = 8080, const char *ip = nullptr); 24 | ~ServerSocket(); 25 | void bind(); 26 | 27 | void listen(); 28 | 29 | int accept(ClientSocket &); 30 | 31 | public: 32 | sockaddr_in mAddr; 33 | int fd; 34 | int mPort; 35 | const char *mIp; 36 | }; 37 | 38 | class ClientSocket { 39 | public: 40 | ~ClientSocket(); 41 | 42 | socklen_t mLen; 43 | sockaddr_in mAddr; 44 | int fd; 45 | }; 46 | } // namespace nsocket 47 | #endif // WEBSERVER_SOCKET_H 48 | -------------------------------------------------------------------------------- /version_0.1/include/utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #ifndef WEBSERVER_UTILS_H 6 | #define WEBSERVER_UTILS_H 7 | 8 | #include 9 | 10 | namespace util { 11 | using namespace std; 12 | std::string& ltrim(string&); 13 | std::string& rtrim(string&); 14 | std::string& trim(string&); 15 | } // namespace util 16 | 17 | #endif // WEBSERVER_UTILS_H 18 | -------------------------------------------------------------------------------- /version_0.1/src/base/noncopyable.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_NONCOPYABLE_H 7 | #define WEBSERVER_NONCOPYABLE_H 8 | 9 | class noncopyable { 10 | public: 11 | noncopyable(const noncopyable&) = delete; 12 | void operator=(const noncopyable&) = delete; 13 | 14 | protected: 15 | noncopyable() = default; 16 | ~noncopyable() = default; 17 | }; 18 | #endif // WEBSERVER_NONCOPYABLE_H 19 | -------------------------------------------------------------------------------- /version_0.1/src/httpparse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/httpparse.h" 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #include "../include/utils.h" 13 | 14 | std::unordered_map http::HttpRequest::header_map = { 15 | {"HOST", http::HttpRequest::Host}, 16 | {"USER-AGENT", http::HttpRequest::User_Agent}, 17 | {"CONNECTION", http::HttpRequest::Connection}, 18 | {"ACCEPT-ENCODING", http::HttpRequest::Accept_Encoding}, 19 | {"ACCEPT-LANGUAGE", http::HttpRequest::Accept_Language}, 20 | {"ACCEPT", http::HttpRequest::Accept}, 21 | {"CACHE-CONTROL", http::HttpRequest::Cache_Control}, 22 | {"UPGRADE-INSECURE-REQUESTS", http::HttpRequest::Upgrade_Insecure_Requests}}; 23 | 24 | // 解析一行内容, buffer[checked_index, read_index) 25 | // check_index是需要分析的第一个字符, read_index已经读取数据末尾下一个字符 26 | http::HttpRequestParser::LINE_STATE http::HttpRequestParser::parse_line(char *buffer, int &checked_index, 27 | int &read_index) { 28 | char temp; 29 | for (; checked_index < read_index; checked_index++) { 30 | temp = buffer[checked_index]; 31 | if (temp == CR) { 32 | // 到末尾,需要读入 33 | if (checked_index + 1 == read_index) return LINE_MORE; 34 | // 完整 "\r\n" 35 | if (buffer[checked_index + 1] == LF) { 36 | buffer[checked_index++] = LINE_END; 37 | buffer[checked_index++] = LINE_END; 38 | return LINE_OK; 39 | } 40 | 41 | return LINE_BAD; 42 | } 43 | } 44 | // 需要读入更多 45 | return LINE_MORE; 46 | } 47 | 48 | // 解析请求行 49 | http::HttpRequestParser::HTTP_CODE http::HttpRequestParser::parse_requestline(char *line, PARSE_STATE &parse_state, 50 | HttpRequest &request) { 51 | char *url = strpbrk(line, " \t"); 52 | if (!url) { 53 | return BAD_REQUEST; 54 | } 55 | 56 | // 分割 method 和 url 57 | *url++ = '\0'; 58 | 59 | char *method = line; 60 | 61 | if (strcasecmp(method, "GET") == 0) { 62 | request.mMethod = HttpRequest::GET; 63 | } else if (strcasecmp(method, "POST") == 0) { 64 | request.mMethod = HttpRequest::POST; 65 | } else if (strcasecmp(method, "PUT") == 0) { 66 | request.mMethod = HttpRequest::PUT; 67 | } else { 68 | return BAD_REQUEST; 69 | } 70 | 71 | url += strspn(url, " \t"); 72 | char *version = strpbrk(url, " \t"); 73 | if (!version) { 74 | return BAD_REQUEST; 75 | } 76 | *version++ = '\0'; 77 | version += strspn(version, " \t"); 78 | 79 | // HTTP/1.1 后面可能还存在空白字符 80 | if (strncasecmp("HTTP/1.1", version, 8) == 0) { 81 | request.mVersion = HttpRequest::HTTP_11; 82 | } else if (strncasecmp("HTTP/1.0", version, 8) == 0) { 83 | request.mVersion = HttpRequest::HTTP_10; 84 | } else { 85 | return BAD_REQUEST; 86 | } 87 | 88 | if (strncasecmp(url, "http://", 7) == 0) { 89 | url += 7; 90 | url = strchr(url, '/'); 91 | } else if (strncasecmp(url, "/", 1) == 0) { 92 | PASS; 93 | } else { 94 | return BAD_REQUEST; 95 | } 96 | 97 | if (!url || *url != '/') { 98 | return BAD_REQUEST; 99 | } 100 | request.mUri = std::string(url); 101 | // 分析头部字段 102 | parse_state = PARSE_HEADER; 103 | return NO_REQUEST; 104 | } 105 | 106 | // 分析头部字段 107 | http::HttpRequestParser::HTTP_CODE http::HttpRequestParser::parse_headers(char *line, PARSE_STATE &parse_state, 108 | HttpRequest &request) { 109 | if (*line == '\0') { 110 | if (request.mMethod == HttpRequest::GET) { 111 | return GET_REQUEST; 112 | } 113 | parse_state = PARSE_BODY; 114 | return NO_REQUEST; 115 | } 116 | 117 | // char key[20]曾被缓冲区溢出 118 | char key[100], value[100]; 119 | 120 | // 需要修改有些value里也包含了':'符号 121 | sscanf(line, "%[^:]:%[^:]", key, value); 122 | 123 | decltype(HttpRequest::header_map)::iterator it; 124 | std::string key_s(key); 125 | std::transform(key_s.begin(), key_s.end(), key_s.begin(), ::toupper); 126 | std::string value_s(value); 127 | if (key_s == std::string("UPGRADE-INSECURE-REQUESTS")) { 128 | return NO_REQUEST; 129 | } 130 | 131 | if ((it = HttpRequest::header_map.find(util::trim(key_s))) != (HttpRequest::header_map.end())) { 132 | request.mHeaders.insert(std::make_pair(it->second, util::trim(value_s))); 133 | } else { 134 | std::cout << "Header no support: " << key << " : " << value << std::endl; 135 | } 136 | 137 | return NO_REQUEST; 138 | } 139 | 140 | // 解析body 141 | http::HttpRequestParser::HTTP_CODE http::HttpRequestParser::parse_body(char *body, http::HttpRequest &request) { 142 | request.mContent = body; 143 | return GET_REQUEST; 144 | } 145 | 146 | // http 请求入口 147 | http::HttpRequestParser::HTTP_CODE http::HttpRequestParser::parse_content( 148 | char *buffer, int &check_index, int &read_index, http::HttpRequestParser::PARSE_STATE &parse_state, int &start_line, 149 | HttpRequest &request) { 150 | LINE_STATE line_state = LINE_OK; 151 | HTTP_CODE retcode = NO_REQUEST; 152 | while ((line_state = parse_line(buffer, check_index, read_index)) == LINE_OK) { 153 | char *temp = buffer + start_line; // 这一行在buffer中的起始位置 154 | start_line = check_index; // 下一行起始位置 155 | 156 | switch (parse_state) { 157 | case PARSE_REQUESTLINE: { 158 | retcode = parse_requestline(temp, parse_state, request); 159 | if (retcode == BAD_REQUEST) return BAD_REQUEST; 160 | 161 | break; 162 | } 163 | 164 | case PARSE_HEADER: { 165 | retcode = parse_headers(temp, parse_state, request); 166 | if (retcode == BAD_REQUEST) { 167 | return BAD_REQUEST; 168 | } else if (retcode == GET_REQUEST) { 169 | return GET_REQUEST; 170 | } 171 | break; 172 | } 173 | 174 | case PARSE_BODY: { 175 | retcode = parse_body(temp, request); 176 | if (retcode == GET_REQUEST) { 177 | return GET_REQUEST; 178 | } 179 | return BAD_REQUEST; 180 | } 181 | default: 182 | return INTERNAL_ERROR; 183 | } 184 | } 185 | if (line_state == LINE_MORE) { 186 | return NO_REQUEST; 187 | } else { 188 | return BAD_REQUEST; 189 | } 190 | } 191 | // 重载HttpRequest << 192 | 193 | std::ostream &http::operator<<(std::ostream &os, const http::HttpRequest &request) { 194 | os << "method:" << request.mMethod << std::endl; 195 | os << "uri:" << request.mUri << std::endl; 196 | os << "version:" << request.mVersion << std::endl; 197 | // os << "content:" << request.mContent << std::endl; 198 | for (auto it = request.mHeaders.begin(); it != request.mHeaders.end(); it++) { 199 | os << it->first << ":" << it->second << std::endl; 200 | } 201 | return os; 202 | } 203 | -------------------------------------------------------------------------------- /version_0.1/src/httpresponse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/httpresponse.h" 7 | 8 | #include 9 | 10 | std::unordered_map http::Mime_map = {{".html", "text/html"}, 11 | {".xml", "text/xml"}, 12 | {".xhtml", "application/xhtml+xml"}, 13 | {".txt", "text/plain"}, 14 | {".rtf", "application/rtf"}, 15 | {".pdf", "application/pdf"}, 16 | {".word", "application/msword"}, 17 | {".png", "image/png"}, 18 | {".gif", "image/gif"}, 19 | {".jpg", "image/jpeg"}, 20 | {".jpeg", "image/jpeg"}, 21 | {".au", "audio/basic"}, 22 | {".mpeg", "video/mpeg"}, 23 | {".mpg", "video/mpeg"}, 24 | {".avi", "video/x-msvideo"}, 25 | {".gz", "application/x-gzip"}, 26 | {".tar", "application/x-tar"}, 27 | {".css", "text/css"}, 28 | {"", "text/plain"}, 29 | {"default", "text/plain"}}; 30 | 31 | void http::HttpResponse::appenBuffer(char *buffer) const { 32 | if (mVersion == HttpRequest::HTTP_11) { 33 | sprintf(buffer, "HTTP/1.1 %d %s\r\n", mStatusCode, mStatusMsg.c_str()); 34 | } else { 35 | sprintf(buffer, "HTTP/1.0 %d %s\r\n", mStatusCode, mStatusMsg.c_str()); 36 | } 37 | 38 | for (auto it = mHeaders.begin(); it != mHeaders.end(); it++) { 39 | sprintf(buffer, "%s%s: %s\r\n", buffer, it->first.c_str(), it->second.c_str()); 40 | } 41 | sprintf(buffer, "%sContent-type: %s\r\n", buffer, mMime.type.c_str()); 42 | if (mCloseConnection) { 43 | sprintf(buffer, "%sConnection: close\r\n", buffer); 44 | } else { 45 | sprintf(buffer, "%sConnection: keep-alive\r\n", buffer); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /version_0.1/src/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | #include "../include/server.h" 15 | 16 | int main(int argc, const char *argv[]) { 17 | char *buffer; 18 | //也可以将buffer作为输出参数 19 | if ((buffer = getcwd(NULL, 0)) == NULL) { 20 | perror("getcwd error"); 21 | } else { 22 | printf("%s\n", buffer); 23 | free(buffer); 24 | } 25 | 26 | server::HttpServer httpServer(80); 27 | httpServer.run(); 28 | } 29 | -------------------------------------------------------------------------------- /version_0.1/src/server.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/server.h" 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | #include 16 | 17 | #include "../include/httpparse.h" 18 | #include "../include/httpresponse.h" 19 | 20 | using namespace server; 21 | using namespace nsocket; 22 | using namespace http; 23 | 24 | const char *basePath = "/Users/lichunlin/CLionProjects/webserver/"; 25 | 26 | void HttpServer::run() { 27 | while (true) { 28 | ClientSocket clientSocket; 29 | serverSocket.accept(clientSocket); 30 | do_request(clientSocket); 31 | } 32 | } 33 | 34 | void HttpServer::do_request(const ClientSocket &clientSocket) { 35 | char buffer[BUFFERSIZE]; 36 | 37 | bzero(buffer, BUFFERSIZE); 38 | int check_index = 0, read_index = 0, start_line = 0; 39 | ssize_t recv_data; 40 | http::HttpRequestParser::PARSE_STATE parse_state = http::HttpRequestParser::PARSE_REQUESTLINE; 41 | 42 | while (true) { 43 | http::HttpRequest request; 44 | 45 | recv_data = recv(clientSocket.fd, buffer + read_index, BUFFERSIZE - read_index, 0); 46 | if (recv_data == -1) { 47 | std::cout << "reading faild" << std::endl; 48 | exit(0); 49 | } 50 | if (recv_data == 0) { 51 | std::cout << "connection closed by peer" << std::endl; 52 | break; 53 | } 54 | read_index += recv_data; 55 | 56 | http::HttpRequestParser::HTTP_CODE retcode = 57 | http::HttpRequestParser::parse_content(buffer, check_index, read_index, parse_state, start_line, request); 58 | 59 | if (retcode == http::HttpRequestParser::NO_REQUEST) { 60 | continue; 61 | } 62 | 63 | if (retcode == http::HttpRequestParser::GET_REQUEST) { 64 | HttpResponse response(true); 65 | header(request, response); 66 | getMime(request, response); 67 | static_file(response, "/Users/lichunlin/CLionProjects/webserver/version_0.1"); 68 | send(response, clientSocket); 69 | } else { 70 | std::cout << "Bad Request" << std::endl; 71 | } 72 | } 73 | } 74 | 75 | void HttpServer::header(const HttpRequest &request, HttpResponse &response) { 76 | if (request.mVersion == HttpRequest::HTTP_11) { 77 | response.setVersion(HttpRequest::HTTP_11); 78 | } else { 79 | response.setVersion(HttpRequest::HTTP_10); 80 | } 81 | response.addHeader("Server", "LC WebServer"); 82 | } 83 | 84 | // 获取Mime 同时设置path到response 85 | void HttpServer::getMime(const http::HttpRequest &request, http::HttpResponse &response) { 86 | std::string filepath = request.mUri; 87 | std::string mime; 88 | int pos; 89 | if ((pos = filepath.rfind('?')) != std::string::npos) { 90 | filepath.erase(filepath.rfind('?')); 91 | } 92 | 93 | if (filepath.rfind('.') != std::string::npos) { 94 | mime = filepath.substr(filepath.rfind('.')); 95 | } 96 | decltype(http::Mime_map)::iterator it; 97 | 98 | if ((it = http::Mime_map.find(mime)) != http::Mime_map.end()) { 99 | response.setMime(it->second); 100 | } else { 101 | response.setMime(http::Mime_map.find("default")->second); 102 | } 103 | response.setFilePath(filepath); 104 | } 105 | 106 | void HttpServer::static_file(HttpResponse &response, const char *basepath) { 107 | struct stat file_stat; 108 | char file[strlen(basepath) + strlen(response.filePath().c_str()) + 1]; 109 | strcpy(file, basepath); 110 | strcat(file, response.filePath().c_str()); 111 | 112 | if (stat(file, &file_stat) < 0) { 113 | response.setStatusCode(HttpResponse::k404NotFound); 114 | response.setStatusMsg("Not Found"); 115 | response.setFilePath(std::string(basepath) + "/404.html"); 116 | return; 117 | } 118 | 119 | if (!S_ISREG(file_stat.st_mode)) { 120 | response.setStatusCode(HttpResponse::k403forbiden); 121 | response.setStatusMsg("ForBidden"); 122 | response.setFilePath(std::string(basepath) + "/403.html"); 123 | return; 124 | } 125 | 126 | response.setStatusCode(HttpResponse::k200Ok); 127 | response.setStatusMsg("OK"); 128 | response.setFilePath(file); 129 | return; 130 | } 131 | 132 | void HttpServer::send(const http::HttpResponse &response, const nsocket::ClientSocket &clientSocket) { 133 | char header[BUFFERSIZE]; 134 | bzero(header, '\0'); 135 | const char *internal_error = "Internal Error"; 136 | struct stat file_stat; 137 | response.appenBuffer(header); 138 | if (stat(response.filePath().c_str(), &file_stat) < 0) { 139 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 140 | sprintf(header, "%s%s", header, internal_error); 141 | ::send(clientSocket.fd, header, strlen(header), 0); 142 | return; 143 | } 144 | 145 | int filefd = ::open(response.filePath().c_str(), O_RDONLY); 146 | if (filefd < 0) { 147 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 148 | sprintf(header, "%s%s", header, internal_error); 149 | ::send(clientSocket.fd, header, strlen(header), 0); 150 | return; 151 | } 152 | 153 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, file_stat.st_size); 154 | ::send(clientSocket.fd, header, strlen(header), 0); 155 | void *mapbuf = mmap(NULL, file_stat.st_size, PROT_READ, MAP_PRIVATE, filefd, 0); 156 | ::send(clientSocket.fd, mapbuf, file_stat.st_size, 0); 157 | munmap(mapbuf, file_stat.st_size); 158 | close(filefd); 159 | return; 160 | err: 161 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 162 | sprintf(header, "%s%s", header, internal_error); 163 | ::send(clientSocket.fd, header, strlen(header), 0); 164 | return; 165 | } -------------------------------------------------------------------------------- /version_0.1/src/ssocket.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/ssocket.h" 7 | 8 | void nsocket::setReusePort(int fd) { 9 | int opt = 1; 10 | setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt)); 11 | } 12 | 13 | nsocket::ServerSocket::ServerSocket(int port, const char *ip) : mPort(port), mIp(ip) { 14 | bzero(&mAddr, sizeof(mAddr)); 15 | mAddr.sin_family = AF_INET; 16 | mAddr.sin_port = htons(port); 17 | if (ip != nullptr) { 18 | ::inet_pton(AF_INET, ip, &mAddr.sin_addr); 19 | } else { 20 | mAddr.sin_addr.s_addr = htonl(INADDR_ANY); 21 | } 22 | fd = socket(AF_INET, SOCK_STREAM, 0); 23 | if (fd == -1) { 24 | std::cout << "creat socket error in file <" << __FILE__ << "> " 25 | << "at " << __LINE__ << std::endl; 26 | exit(0); 27 | } 28 | setReusePort(fd); 29 | } 30 | 31 | void nsocket::ServerSocket::bind() { 32 | int ret = ::bind(fd, (struct sockaddr *)&mAddr, sizeof(mAddr)); 33 | if (ret == -1) { 34 | std::cout << "bind error in file <" << __FILE__ << "> " 35 | << "at " << __LINE__ << std::endl; 36 | exit(0); 37 | } 38 | } 39 | 40 | void nsocket::ServerSocket::listen() { 41 | int ret = ::listen(fd, 5); 42 | if (ret == -1) { 43 | std::cout << "listen error in file <" << __FILE__ << "> " 44 | << "at " << __LINE__ << std::endl; 45 | exit(0); 46 | } 47 | } 48 | 49 | int nsocket::ServerSocket::accept(ClientSocket &clientSocket) { 50 | int clientfd = ::accept(fd, (struct sockaddr *)&clientSocket.mAddr, &clientSocket.mLen); 51 | if (clientfd < 0) { 52 | std::cout << "accept error in file <" << __FILE__ << "> " 53 | << "at " << __LINE__ << std::endl; 54 | exit(0); 55 | } 56 | clientSocket.fd = clientfd; 57 | std::cout << "accept a client" << std::endl; 58 | return clientfd; 59 | } 60 | 61 | nsocket::ServerSocket::~ServerSocket() { ::close(fd); } 62 | 63 | nsocket::ClientSocket::~ClientSocket() { ::close(fd); } 64 | -------------------------------------------------------------------------------- /version_0.1/src/utils.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/utils.h" 7 | 8 | #include 9 | 10 | std::string& util::ltrim(std::string& str) { 11 | if (str.empty()) { 12 | return str; 13 | } 14 | 15 | str.erase(0, str.find_first_not_of(" \t")); 16 | return str; 17 | } 18 | 19 | std::string& util::rtrim(std::string& str) { 20 | if (str.empty()) { 21 | return str; 22 | } 23 | str.erase(str.find_last_not_of(" \t") + 1); 24 | return str; 25 | } 26 | 27 | std::string& util::trim(std::string& str) { 28 | if (str.empty()) { 29 | return str; 30 | } 31 | 32 | util::ltrim(str); 33 | util::rtrim(str); 34 | return str; 35 | } 36 | -------------------------------------------------------------------------------- /version_0.1/test/test.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by marvinle on 2019/2/3 9:13 AM. 3 | // 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | int main() { 16 | // string s = "/helo/world/index?word=12"; 17 | // s.erase(s.rfind('?')); 18 | // string filetype; 19 | // if (s.rfind('.') != string::npos){ 20 | // filetype = s.substr(s.rfind('.')); 21 | // } 22 | // 23 | // 24 | // cout << s << endl; 25 | // if (filetype != "") { 26 | // cout << filetype << endl; 27 | // } else { 28 | // cout << " no file type" << endl; 29 | // } 30 | char *buffer; 31 | //也可以将buffer作为输出参数 32 | if ((buffer = getcwd(NULL, 0)) == NULL) { 33 | perror("getcwd error"); 34 | } else { 35 | printf("%s\n", buffer); 36 | free(buffer); 37 | } 38 | 39 | enum Code { ok = 201, notfound = 404 }; 40 | 41 | Code code = ok; 42 | printf("%d\n", code); 43 | } -------------------------------------------------------------------------------- /version_0.1/test/test_utils.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by marvinle on 2019/2/1 12:11 PM. 3 | // 4 | 5 | #include 6 | #include 7 | 8 | #include "../include/utils.h" 9 | 10 | using namespace std; 11 | 12 | void test_ltrim() { 13 | std::string s = " \thelloworld\t "; 14 | util::ltrim(s); 15 | if (s == "helloworld\t ") { 16 | cout << "ltrim ok" << endl; 17 | } else { 18 | cout << "test ltrim faild" << endl; 19 | } 20 | } 21 | void test_rtrim() { 22 | std::string s = " \thelloworld\t "; 23 | util::rtrim(s); 24 | if (s == " \thelloworld") { 25 | cout << "rtrim ok" << endl; 26 | } else { 27 | cout << "test rtrim faild" << endl; 28 | } 29 | } 30 | 31 | void test_trim() { 32 | std::string s = " 1"; 33 | util::trim(s); 34 | if (s == "1") { 35 | cout << "trim ok" << endl; 36 | } else { 37 | cout << "test trim faild" << endl; 38 | } 39 | } 40 | 41 | int main() { 42 | test_ltrim(); 43 | test_rtrim(); 44 | test_trim(); 45 | } 46 | -------------------------------------------------------------------------------- /version_0.2/403.html: -------------------------------------------------------------------------------- 1 | 2 | 403 Forbidden 3 | 4 |

403 Forbidden

5 |
nginx/1.10.3 (Ubuntu)
6 | 7 | -------------------------------------------------------------------------------- /version_0.2/404.html: -------------------------------------------------------------------------------- 1 | 2 | 404 Not Found 3 | 4 |

404 Not Found

5 |
nginx/1.10.3 (Ubuntu)
6 | 7 | -------------------------------------------------------------------------------- /version_0.2/include/Condition.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_CONDITION_H 7 | #define WEBSERVER_CONDITION_H 8 | 9 | #include 10 | 11 | #include "MutexLock.h" 12 | #include "noncopyable.h" 13 | 14 | class Condition : public noncopyable { 15 | public: 16 | explicit Condition(MutexLock &mutex) : mutex_(mutex) { pthread_cond_init(&cond_, NULL); } 17 | ~Condition() { pthread_cond_destroy(&cond_); } 18 | 19 | void wait() { pthread_cond_wait(&cond_, mutex_.getMutex()); } 20 | 21 | void notify() { pthread_cond_signal(&cond_); } 22 | 23 | void notifyAll() { pthread_cond_broadcast(&cond_); } 24 | 25 | private: 26 | MutexLock &mutex_; 27 | pthread_cond_t cond_; 28 | }; 29 | 30 | #endif // WEBSERVER_CONDITION_H 31 | -------------------------------------------------------------------------------- /version_0.2/include/HttpResponse.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #ifndef WEBSERVER_HTTPRESPONSE_H 6 | #define WEBSERVER_HTTPRESPONSE_H 7 | 8 | #include 9 | #include 10 | 11 | #include "httpparse.h" 12 | 13 | #define BASEPATH 14 | 15 | namespace http { 16 | 17 | struct MimeType { 18 | MimeType(const std::string &str) : type(str){}; 19 | MimeType(const char *str) : type(str){}; 20 | 21 | std::string type; 22 | }; 23 | 24 | extern std::unordered_map Mime_map; 25 | 26 | class HttpResponse { 27 | public: 28 | enum HttpStatusCode { Unknow, k200Ok = 200, k403forbiden = 403, k404NotFound = 404 }; 29 | 30 | explicit HttpResponse(bool close) 31 | : mStatusCode(Unknow), 32 | mCloseConnection(close), 33 | mMime("text/html"), 34 | mBody(nullptr), 35 | mVersion(HttpRequest::HTTP_11) {} 36 | 37 | void setStatusCode(HttpStatusCode code) { mStatusCode = code; } 38 | void setBody(const char *buf) { mBody = buf; } 39 | void setContentLength(int len) { mContentLength = len; } 40 | void setVersion(const HttpRequest::HTTP_VERSION &version) { mVersion = version; } 41 | 42 | void setStatusMsg(const std::string &msg) { mStatusMsg = msg; } 43 | void setFilePath(const std::string &path) { mFilePath = path; } 44 | void setMime(const MimeType &mime) { mMime = mime; } 45 | 46 | void addHeader(const std::string &key, const std::string &value) { mHeaders[key] = value; } 47 | bool closeConnection() const { return mCloseConnection; } 48 | const HttpRequest::HTTP_VERSION version() const { return mVersion; } 49 | const std::string &filePath() const { return mFilePath; } 50 | HttpStatusCode statusCode() const { return mStatusCode; } 51 | const std::string &statusMsg() const { return mStatusMsg; } 52 | 53 | void appenBuffer(char *) const; 54 | 55 | ~HttpResponse() { 56 | if (mBody != nullptr) delete[] mBody; 57 | } 58 | 59 | private: 60 | HttpStatusCode mStatusCode; 61 | HttpRequest::HTTP_VERSION mVersion; 62 | std::string mStatusMsg; 63 | bool mCloseConnection; 64 | MimeType mMime; 65 | const char *mBody; 66 | int mContentLength; 67 | std::string mFilePath; 68 | std::unordered_map mHeaders; 69 | }; 70 | 71 | } // namespace http 72 | 73 | #endif // WEBSERVER_HTTPRESPONSE_H 74 | -------------------------------------------------------------------------------- /version_0.2/include/MutexLock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_MUTEXLOCK_H 7 | #define WEBSERVER_MUTEXLOCK_H 8 | #include 9 | 10 | #include "noncopyable.h" 11 | 12 | class MutexLock : public noncopyable { 13 | public: 14 | MutexLock() { pthread_mutex_init(&mutex_, NULL); } 15 | ~MutexLock() { pthread_mutex_destroy(&mutex_); } 16 | void lock() { pthread_mutex_lock(&mutex_); } 17 | void unlock() { pthread_mutex_unlock(&mutex_); } 18 | pthread_mutex_t *getMutex() { return &mutex_; } 19 | 20 | private: 21 | pthread_mutex_t mutex_; 22 | }; 23 | 24 | class MutexLockGuard : public noncopyable { 25 | public: 26 | explicit MutexLockGuard(MutexLock &mutex) : mutex_(mutex) { mutex_.lock(); } 27 | 28 | ~MutexLockGuard() { mutex_.unlock(); } 29 | 30 | private: 31 | MutexLock &mutex_; 32 | }; 33 | 34 | #endif // WEBSERVER_MUTEXLOCK_H 35 | -------------------------------------------------------------------------------- /version_0.2/include/ThreadPool.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_THREADPOLL_H 7 | #define WEBSERVER_THREADPOLL_H 8 | 9 | #include 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include "Condition.h" 16 | #include "MutexLock.h" 17 | #include "noncopyable.h" 18 | 19 | namespace thread { 20 | const int MAX_THREAD_SIZE = 1024; 21 | const int MAX_QUEUE_SIZE = 10000; 22 | 23 | typedef enum { immediate_mode = 1, graceful_mode = 2 } ShutdownMode; 24 | 25 | struct ThreadTask { 26 | std::function process; 27 | void* arg; 28 | }; 29 | 30 | class ThreadPool { 31 | public: 32 | ThreadPool(int thread_s, int max_queue_s); 33 | ~ThreadPool(); 34 | bool append(thread::ThreadTask* request); 35 | void shutdown(bool graceful); 36 | 37 | private: 38 | static void* worker(void* args); 39 | void run(); 40 | 41 | private: 42 | // 线程同步互斥, mutex_ 在 condition_前面 43 | MutexLock mutex_; 44 | Condition condition_; 45 | 46 | // 线程池属性 47 | int thread_size; 48 | int max_queue_size; 49 | int started; 50 | int shutdown_; 51 | std::vector threads; 52 | std::list request_queue; 53 | }; 54 | 55 | } // namespace thread 56 | 57 | #endif // WEBSERVER_THREADPOLL_H 58 | -------------------------------------------------------------------------------- /version_0.2/include/Util.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_UTILS_H 7 | #define WEBSERVER_UTILS_H 8 | 9 | #include 10 | 11 | namespace util { 12 | using namespace std; 13 | std::string& ltrim(string&); 14 | std::string& rtrim(string&); 15 | std::string& trim(string&); 16 | } // namespace util 17 | 18 | #endif // WEBSERVER_UTILS_H 19 | -------------------------------------------------------------------------------- /version_0.2/include/httpparse.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #ifndef WEBSERVER_HTTPPARSE_H 6 | #define WEBSERVER_HTTPPARSE_H 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #define CR '\r' 13 | #define LF '\n' 14 | #define LINE_END '\0' 15 | #define PASS 16 | 17 | namespace http { 18 | 19 | class HttpRequest; 20 | 21 | std::ostream &operator<<(std::ostream &, const HttpRequest &); 22 | 23 | class HttpRequestParser { 24 | public: 25 | enum LINE_STATE { LINE_OK = 0, LINE_BAD, LINE_MORE }; 26 | enum PARSE_STATE { PARSE_REQUESTLINE = 0, PARSE_HEADER, PARSE_BODY }; 27 | enum HTTP_CODE { NO_REQUEST, GET_REQUEST, BAD_REQUEST, FORBIDDEN_REQUEST, INTERNAL_ERROR, CLOSED_CONNECTION }; 28 | 29 | static LINE_STATE parse_line(char *buffer, int &checked_index, int &read_index); 30 | static HTTP_CODE parse_requestline(char *line, PARSE_STATE &parse_state, HttpRequest &request); 31 | static HTTP_CODE parse_headers(char *line, PARSE_STATE &parse_state, HttpRequest &request); 32 | static HTTP_CODE parse_body(char *body, HttpRequest &request); 33 | static HTTP_CODE parse_content(char *buffer, int &check_index, int &read_index, PARSE_STATE &parse_state, 34 | int &start_line, HttpRequest &request); 35 | }; 36 | 37 | struct HttpRequest { 38 | friend std::ostream &operator<<(std::ostream &, const HttpRequest &); 39 | 40 | enum HTTP_VERSION { HTTP_10 = 0, HTTP_11, VERSION_NOT_SUPPORT }; 41 | enum HTTP_METHOD { GET = 0, POST, PUT, DELETE, METHOD_NOT_SUPPORT }; 42 | enum HTTP_HEADER { 43 | Host = 0, 44 | User_Agent, 45 | Connection, 46 | Accept_Encoding, 47 | Accept_Language, 48 | Accept, 49 | Cache_Control, 50 | Upgrade_Insecure_Requests 51 | }; 52 | struct EnumClassHash { 53 | template 54 | std::size_t operator()(T t) const { 55 | return static_cast(t); 56 | } 57 | }; 58 | 59 | static std::unordered_map header_map; 60 | 61 | HttpRequest(std::string url = std::string(""), HTTP_METHOD method = METHOD_NOT_SUPPORT, 62 | HTTP_VERSION version = VERSION_NOT_SUPPORT) 63 | : mMethod(method), 64 | mVersion(version), 65 | mUri(url), 66 | mContent(nullptr), 67 | mHeaders(std::unordered_map()){}; 68 | 69 | HTTP_METHOD mMethod; 70 | HTTP_VERSION mVersion; 71 | std::string mUri; 72 | char *mContent; 73 | std::unordered_map mHeaders; 74 | }; 75 | 76 | } // namespace http 77 | 78 | #endif // WEBSERVER_HTTPPARSE_H 79 | -------------------------------------------------------------------------------- /version_0.2/include/noncopyable.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #ifndef WEBSERVER_NONCOPYABLE_H 6 | #define WEBSERVER_NONCOPYABLE_H 7 | 8 | class noncopyable { 9 | public: 10 | noncopyable(const noncopyable&) = delete; 11 | noncopyable& operator=(const noncopyable&) = delete; 12 | 13 | protected: 14 | noncopyable() = default; 15 | ~noncopyable() = default; 16 | }; 17 | #endif // WEBSERVER_NONCOPYABLE_H 18 | -------------------------------------------------------------------------------- /version_0.2/include/server.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_SERVER_H 7 | #define WEBSERVER_SERVER_H 8 | 9 | #include "HttpResponse.h" 10 | #include "httpparse.h" 11 | #include "ssocket.h" 12 | 13 | #define BUFFERSIZE 1024 14 | 15 | namespace server { 16 | 17 | class HttpServer { 18 | public: 19 | explicit HttpServer(int port = 80, const char *ip = nullptr) : serverSocket(port, ip) { 20 | serverSocket.bind(); 21 | serverSocket.listen(); 22 | } 23 | 24 | void run(); 25 | void do_request(void *args); 26 | 27 | private: 28 | void header(const http::HttpRequest &, http::HttpResponse &); 29 | void static_file(http::HttpResponse &, const char *); 30 | void send(const http::HttpResponse &, const nsocket::ClientSocket &); 31 | void getMime(const http::HttpRequest &, http::HttpResponse &); 32 | 33 | nsocket::ServerSocket serverSocket; 34 | }; 35 | } // namespace server 36 | 37 | #endif // WEBSERVER_SERVER_H 38 | -------------------------------------------------------------------------------- /version_0.2/include/ssocket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #ifndef WEBSERVER_SOCKET_H 7 | #define WEBSERVER_SOCKET_H 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | 16 | namespace nsocket { 17 | class ClientSocket; 18 | 19 | void setReusePort(int fd); 20 | 21 | class ServerSocket { 22 | public: 23 | ServerSocket(int port = 8080, const char *ip = nullptr); 24 | ~ServerSocket(); 25 | void bind(); 26 | 27 | void listen(); 28 | 29 | int accept(ClientSocket &); 30 | 31 | public: 32 | sockaddr_in mAddr; 33 | int fd; 34 | int mPort; 35 | const char *mIp; 36 | }; 37 | 38 | class ClientSocket { 39 | public: 40 | ~ClientSocket(); 41 | 42 | socklen_t mLen; 43 | sockaddr_in mAddr; 44 | int fd; 45 | }; 46 | } // namespace nsocket 47 | #endif // WEBSERVER_SOCKET_H 48 | -------------------------------------------------------------------------------- /version_0.2/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Welcome to LC! 5 | 12 | 13 | 14 |

Welcome to LC !

15 |

If you see this page, the lc webserver is successfully installed and 16 | working.

17 | 18 |

For online documentation and support please refer to 19 | LC WebServer.
20 | 21 |

Thank you for using LC WebServer.

22 | 23 | -------------------------------------------------------------------------------- /version_0.2/src/ThreadPool.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/ThreadPool.h" 7 | 8 | #include 9 | 10 | #include 11 | 12 | using namespace thread; 13 | 14 | ThreadPool::ThreadPool(int thread_s, int max_queue_s) 15 | : max_queue_size(max_queue_s), thread_size(thread_s), condition_(mutex_), started(0), shutdown_(0) { 16 | if (thread_s <= 0 || thread_s > MAX_THREAD_SIZE) { 17 | thread_size = 4; 18 | } 19 | 20 | if (max_queue_s <= 0 || max_queue_s > MAX_QUEUE_SIZE) { 21 | max_queue_size = MAX_QUEUE_SIZE; 22 | } 23 | // 分配空间 24 | threads.resize(thread_size); 25 | 26 | for (int i = 0; i < thread_size; i++) { 27 | // 后期可扩展出单独的Thread类,只需要该类拥有run方法即可 28 | 29 | if (pthread_create(&threads[i], NULL, worker, this) != 0) { 30 | std::cout << "ThreadPool init error" << std::endl; 31 | throw std::exception(); 32 | } 33 | started++; 34 | } 35 | } 36 | 37 | ThreadPool::~ThreadPool() {} 38 | 39 | bool ThreadPool::append(ThreadTask *request) { 40 | if (request == nullptr) return false; 41 | 42 | if (shutdown_) { 43 | std::cout << "ThreadPool has shutdown" << std::endl; 44 | return false; 45 | } 46 | 47 | MutexLockGuard guard(this->mutex_); 48 | if (request_queue.size() > max_queue_size) { 49 | std::cout << max_queue_size; 50 | std::cout << "ThreadPool too many requests" << std::endl; 51 | return false; 52 | } 53 | request_queue.push_back(request); 54 | if (request_queue.size() == 1) { 55 | condition_.notify(); 56 | } 57 | return true; 58 | } 59 | 60 | void ThreadPool::shutdown(bool graceful) { 61 | { 62 | MutexLockGuard guard(this->mutex_); 63 | if (shutdown_) { 64 | std::cout << "has shutdown" << std::endl; 65 | } 66 | shutdown_ = graceful ? graceful_mode : immediate_mode; 67 | condition_.notifyAll(); 68 | } 69 | for (int i = 0; i < thread_size; i++) { 70 | if (pthread_join(threads[i], NULL) != 0) { 71 | std::cout << "pthread_join error" << std::endl; 72 | } 73 | } 74 | } 75 | 76 | void *ThreadPool::worker(void *args) { 77 | ThreadPool *pool = static_cast(args); 78 | // 退出线程 79 | if (pool == nullptr) return NULL; 80 | // 执行线程主方法 81 | pool->run(); 82 | return NULL; 83 | } 84 | 85 | void ThreadPool::run() { 86 | while (true) { 87 | ThreadTask *request = nullptr; 88 | { 89 | MutexLockGuard guard(this->mutex_); 90 | // 无任务 且未shutdown 则条件等待, 注意此处应使用while而非if 91 | while (request_queue.empty() && !shutdown_) { 92 | condition_.wait(); 93 | } 94 | 95 | if ((shutdown_ == immediate_mode) || (shutdown_ == graceful_mode && request_queue.empty())) { 96 | break; 97 | } 98 | // FIFO 99 | request = request_queue.front(); 100 | request_queue.pop_front(); 101 | } 102 | if (request == nullptr) continue; 103 | 104 | request->process(request->arg); 105 | delete request; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /version_0.2/src/Util.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #include "../include/Util.h" 6 | 7 | #include 8 | 9 | std::string& util::ltrim(std::string& str) { 10 | if (str.empty()) { 11 | return str; 12 | } 13 | 14 | str.erase(0, str.find_first_not_of(" \t")); 15 | return str; 16 | } 17 | 18 | std::string& util::rtrim(std::string& str) { 19 | if (str.empty()) { 20 | return str; 21 | } 22 | str.erase(str.find_last_not_of(" \t") + 1); 23 | return str; 24 | } 25 | 26 | std::string& util::trim(std::string& str) { 27 | if (str.empty()) { 28 | return str; 29 | } 30 | 31 | util::ltrim(str); 32 | util::rtrim(str); 33 | return str; 34 | } 35 | -------------------------------------------------------------------------------- /version_0.2/src/httpparse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #include "../include/httpparse.h" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include "../include/Util.h" 12 | 13 | using namespace http; 14 | 15 | std::unordered_map http::HttpRequest::header_map = { 16 | {"HOST", http::HttpRequest::Host}, 17 | {"USER-AGENT", http::HttpRequest::User_Agent}, 18 | {"CONNECTION", http::HttpRequest::Connection}, 19 | {"ACCEPT-ENCODING", http::HttpRequest::Accept_Encoding}, 20 | {"ACCEPT-LANGUAGE", http::HttpRequest::Accept_Language}, 21 | {"ACCEPT", http::HttpRequest::Accept}, 22 | {"CACHE-CONTROL", http::HttpRequest::Cache_Control}, 23 | {"UPGRADE-INSECURE-REQUESTS", http::HttpRequest::Upgrade_Insecure_Requests}}; 24 | 25 | // 解析一行内容, buffer[checked_index, read_index) 26 | // check_index是需要分析的第一个字符, read_index已经读取数据末尾下一个字符 27 | HttpRequestParser::LINE_STATE HttpRequestParser::parse_line(char *buffer, int &checked_index, int &read_index) { 28 | char temp; 29 | for (; checked_index < read_index; checked_index++) { 30 | temp = buffer[checked_index]; 31 | if (temp == CR) { 32 | // 到末尾,需要读入 33 | if (checked_index + 1 == read_index) return LINE_MORE; 34 | // 完整 "\r\n" 35 | if (buffer[checked_index + 1] == LF) { 36 | buffer[checked_index++] = LINE_END; 37 | buffer[checked_index++] = LINE_END; 38 | return LINE_OK; 39 | } 40 | 41 | return LINE_BAD; 42 | } 43 | } 44 | // 需要读入更多 45 | return LINE_MORE; 46 | } 47 | 48 | // 解析请求行 49 | HttpRequestParser::HTTP_CODE HttpRequestParser::parse_requestline(char *line, PARSE_STATE &parse_state, 50 | HttpRequest &request) { 51 | char *url = strpbrk(line, " \t"); 52 | if (!url) { 53 | return BAD_REQUEST; 54 | } 55 | 56 | // 分割 method 和 url 57 | *url++ = '\0'; 58 | 59 | char *method = line; 60 | 61 | if (strcasecmp(method, "GET") == 0) { 62 | request.mMethod = HttpRequest::GET; 63 | } else if (strcasecmp(method, "POST") == 0) { 64 | request.mMethod = HttpRequest::POST; 65 | } else if (strcasecmp(method, "PUT") == 0) { 66 | request.mMethod = HttpRequest::PUT; 67 | } else { 68 | return BAD_REQUEST; 69 | } 70 | 71 | url += strspn(url, " \t"); 72 | char *version = strpbrk(url, " \t"); 73 | if (!version) { 74 | return BAD_REQUEST; 75 | } 76 | *version++ = '\0'; 77 | version += strspn(version, " \t"); 78 | 79 | // HTTP/1.1 后面可能还存在空白字符 80 | if (strncasecmp("HTTP/1.1", version, 8) == 0) { 81 | request.mVersion = HttpRequest::HTTP_11; 82 | } else if (strncasecmp("HTTP/1.0", version, 8) == 0) { 83 | request.mVersion = HttpRequest::HTTP_10; 84 | } else { 85 | return BAD_REQUEST; 86 | } 87 | 88 | if (strncasecmp(url, "http://", 7) == 0) { 89 | url += 7; 90 | url = strchr(url, '/'); 91 | } else if (strncasecmp(url, "/", 1) == 0) { 92 | PASS; 93 | } else { 94 | return BAD_REQUEST; 95 | } 96 | 97 | if (!url || *url != '/') { 98 | return BAD_REQUEST; 99 | } 100 | request.mUri = std::string(url); 101 | // 分析头部字段 102 | parse_state = PARSE_HEADER; 103 | return NO_REQUEST; 104 | } 105 | 106 | // 分析头部字段 107 | HttpRequestParser::HTTP_CODE HttpRequestParser::parse_headers(char *line, PARSE_STATE &parse_state, 108 | HttpRequest &request) { 109 | if (*line == '\0') { 110 | if (request.mMethod == HttpRequest::GET) { 111 | return GET_REQUEST; 112 | } 113 | parse_state = PARSE_BODY; 114 | return NO_REQUEST; 115 | } 116 | 117 | // char key[20]曾被缓冲区溢出 118 | char key[100], value[100]; 119 | 120 | // 需要修改有些value里也包含了':'符号 121 | sscanf(line, "%[^:]:%[^:]", key, value); 122 | 123 | decltype(HttpRequest::header_map)::iterator it; 124 | std::string key_s(key); 125 | std::transform(key_s.begin(), key_s.end(), key_s.begin(), ::toupper); 126 | std::string value_s(value); 127 | if (key_s == std::string("UPGRADE-INSECURE-REQUESTS")) { 128 | return NO_REQUEST; 129 | } 130 | 131 | if ((it = HttpRequest::header_map.find(util::trim(key_s))) != (HttpRequest::header_map.end())) { 132 | request.mHeaders.insert(std::make_pair(it->second, util::trim(value_s))); 133 | } else { 134 | std::cout << "Header no support: " << key << " : " << value << std::endl; 135 | } 136 | 137 | return NO_REQUEST; 138 | } 139 | 140 | // 解析body 141 | HttpRequestParser::HTTP_CODE HttpRequestParser::parse_body(char *body, http::HttpRequest &request) { 142 | request.mContent = body; 143 | return GET_REQUEST; 144 | } 145 | 146 | // http 请求入口 147 | HttpRequestParser::HTTP_CODE HttpRequestParser::parse_content(char *buffer, int &check_index, int &read_index, 148 | http::HttpRequestParser::PARSE_STATE &parse_state, 149 | int &start_line, HttpRequest &request) { 150 | LINE_STATE line_state = LINE_OK; 151 | HTTP_CODE retcode = NO_REQUEST; 152 | while ((line_state = parse_line(buffer, check_index, read_index)) == LINE_OK) { 153 | char *temp = buffer + start_line; // 这一行在buffer中的起始位置 154 | start_line = check_index; // 下一行起始位置 155 | 156 | switch (parse_state) { 157 | case PARSE_REQUESTLINE: { 158 | retcode = parse_requestline(temp, parse_state, request); 159 | if (retcode == BAD_REQUEST) return BAD_REQUEST; 160 | 161 | break; 162 | } 163 | 164 | case PARSE_HEADER: { 165 | retcode = parse_headers(temp, parse_state, request); 166 | if (retcode == BAD_REQUEST) { 167 | return BAD_REQUEST; 168 | } else if (retcode == GET_REQUEST) { 169 | return GET_REQUEST; 170 | } 171 | break; 172 | } 173 | 174 | case PARSE_BODY: { 175 | retcode = parse_body(temp, request); 176 | if (retcode == GET_REQUEST) { 177 | return GET_REQUEST; 178 | } 179 | return BAD_REQUEST; 180 | } 181 | default: 182 | return INTERNAL_ERROR; 183 | } 184 | } 185 | if (line_state == LINE_MORE) { 186 | return NO_REQUEST; 187 | } else { 188 | return BAD_REQUEST; 189 | } 190 | } 191 | 192 | // 重载HttpRequest << 193 | std::ostream &http::operator<<(std::ostream &os, const HttpRequest &request) { 194 | os << "method:" << request.mMethod << std::endl; 195 | os << "uri:" << request.mUri << std::endl; 196 | os << "version:" << request.mVersion << std::endl; 197 | // os << "content:" << request.mContent << std::endl; 198 | for (auto it = request.mHeaders.begin(); it != request.mHeaders.end(); it++) { 199 | os << it->first << ":" << it->second << std::endl; 200 | } 201 | return os; 202 | } 203 | -------------------------------------------------------------------------------- /version_0.2/src/httpresponse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/HttpResponse.h" 7 | 8 | #include 9 | 10 | std::unordered_map http::Mime_map = {{".html", "text/html"}, 11 | {".xml", "text/xml"}, 12 | {".xhtml", "application/xhtml+xml"}, 13 | {".txt", "text/plain"}, 14 | {".rtf", "application/rtf"}, 15 | {".pdf", "application/pdf"}, 16 | {".word", "application/msword"}, 17 | {".png", "image/png"}, 18 | {".gif", "image/gif"}, 19 | {".jpg", "image/jpeg"}, 20 | {".jpeg", "image/jpeg"}, 21 | {".au", "audio/basic"}, 22 | {".mpeg", "video/mpeg"}, 23 | {".mpg", "video/mpeg"}, 24 | {".avi", "video/x-msvideo"}, 25 | {".gz", "application/x-gzip"}, 26 | {".tar", "application/x-tar"}, 27 | {".css", "text/css"}, 28 | {"", "text/plain"}, 29 | {"default", "text/plain"}}; 30 | 31 | void http::HttpResponse::appenBuffer(char *buffer) const { 32 | if (mVersion == HttpRequest::HTTP_11) { 33 | sprintf(buffer, "HTTP/1.1 %d %s\r\n", mStatusCode, mStatusMsg.c_str()); 34 | } else { 35 | sprintf(buffer, "HTTP/1.0 %d %s\r\n", mStatusCode, mStatusMsg.c_str()); 36 | } 37 | 38 | for (auto it = mHeaders.begin(); it != mHeaders.end(); it++) { 39 | sprintf(buffer, "%s%s: %s\r\n", buffer, it->first.c_str(), it->second.c_str()); 40 | } 41 | sprintf(buffer, "%sContent-type: %s\r\n", buffer, mMime.type.c_str()); 42 | if (mCloseConnection) { 43 | sprintf(buffer, "%sConnection: close\r\n", buffer); 44 | } else { 45 | sprintf(buffer, "%sConnection: keep-alive\r\n", buffer); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /version_0.2/src/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | #include "../include/server.h" 15 | 16 | char basePath[300] = "/Users/lichunlin/CLionProjects/webserver/"; 17 | 18 | int main(int argc, const char *argv[]) { 19 | //也可以将buffer作为输出参数 20 | if ((getcwd(basePath, 300)) == NULL) { 21 | perror("getcwd error"); 22 | } else { 23 | printf("%s\n", basePath); 24 | } 25 | 26 | server::HttpServer httpServer(80); 27 | httpServer.run(); 28 | } 29 | -------------------------------------------------------------------------------- /version_0.2/src/server.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/server.h" 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | #include "../include/HttpResponse.h" 19 | #include "../include/ThreadPool.h" 20 | #include "../include/httpparse.h" 21 | 22 | using namespace server; 23 | using namespace nsocket; 24 | using namespace http; 25 | 26 | extern char basePath[300]; 27 | 28 | void HttpServer::run() { 29 | thread::ThreadPool threadPool(4, 1000); 30 | while (true) { 31 | ClientSocket *clientSocket = new ClientSocket; 32 | serverSocket.accept(*clientSocket); 33 | thread::ThreadTask *threadTask = new thread::ThreadTask; 34 | threadTask->process = std::bind(&HttpServer::do_request, this, std::placeholders::_1); 35 | threadTask->arg = static_cast(clientSocket); 36 | threadPool.append(threadTask); 37 | } 38 | } 39 | 40 | void HttpServer::do_request(void *arg) { 41 | ClientSocket clientSocket = *static_cast(arg); 42 | 43 | char buffer[BUFFERSIZE]; 44 | 45 | bzero(buffer, BUFFERSIZE); 46 | int check_index = 0, read_index = 0, start_line = 0; 47 | ssize_t recv_data; 48 | http::HttpRequestParser::PARSE_STATE parse_state = http::HttpRequestParser::PARSE_REQUESTLINE; 49 | 50 | while (true) { 51 | http::HttpRequest request; 52 | 53 | recv_data = recv(clientSocket.fd, buffer + read_index, BUFFERSIZE - read_index, 0); 54 | if (recv_data == -1) { 55 | std::cout << "reading faild" << std::endl; 56 | return; 57 | } 58 | if (recv_data == 0) { 59 | std::cout << "connection closed by peer" << std::endl; 60 | break; 61 | } 62 | read_index += recv_data; 63 | 64 | http::HttpRequestParser::HTTP_CODE retcode = 65 | http::HttpRequestParser::parse_content(buffer, check_index, read_index, parse_state, start_line, request); 66 | 67 | if (retcode == http::HttpRequestParser::NO_REQUEST) { 68 | continue; 69 | } 70 | std::cout << request << std::endl; 71 | 72 | if (retcode == http::HttpRequestParser::GET_REQUEST) { 73 | HttpResponse response(true); 74 | header(request, response); 75 | getMime(request, response); 76 | static_file(response, basePath); 77 | send(response, clientSocket); 78 | } else { 79 | std::cout << "Bad Request" << std::endl; 80 | } 81 | } 82 | } 83 | 84 | void HttpServer::header(const HttpRequest &request, HttpResponse &response) { 85 | if (request.mVersion == HttpRequest::HTTP_11) { 86 | response.setVersion(HttpRequest::HTTP_11); 87 | } else { 88 | response.setVersion(HttpRequest::HTTP_10); 89 | } 90 | response.addHeader("Server", "LC WebServer"); 91 | } 92 | 93 | // 获取Mime 同时设置path到response 94 | void HttpServer::getMime(const http::HttpRequest &request, http::HttpResponse &response) { 95 | std::string filepath = request.mUri; 96 | std::string mime; 97 | int pos; 98 | if ((pos = filepath.rfind('?')) != std::string::npos) { 99 | filepath.erase(filepath.rfind('?')); 100 | } 101 | 102 | if (filepath.rfind('.') != std::string::npos) { 103 | mime = filepath.substr(filepath.rfind('.')); 104 | } 105 | decltype(http::Mime_map)::iterator it; 106 | 107 | if ((it = http::Mime_map.find(mime)) != http::Mime_map.end()) { 108 | response.setMime(it->second); 109 | } else { 110 | response.setMime(http::Mime_map.find("default")->second); 111 | } 112 | response.setFilePath(filepath); 113 | } 114 | 115 | void HttpServer::static_file(HttpResponse &response, const char *basepath) { 116 | struct stat file_stat; 117 | char file[strlen(basepath) + strlen(response.filePath().c_str()) + 1]; 118 | strcpy(file, basepath); 119 | strcat(file, response.filePath().c_str()); 120 | 121 | if (stat(file, &file_stat) < 0) { 122 | response.setStatusCode(HttpResponse::k404NotFound); 123 | response.setStatusMsg("Not Found"); 124 | response.setFilePath(std::string(basepath) + "/404.html"); 125 | return; 126 | } 127 | 128 | if (!S_ISREG(file_stat.st_mode)) { 129 | response.setStatusCode(HttpResponse::k403forbiden); 130 | response.setStatusMsg("ForBidden"); 131 | response.setFilePath(std::string(basepath) + "/403.html"); 132 | return; 133 | } 134 | 135 | response.setStatusCode(HttpResponse::k200Ok); 136 | response.setStatusMsg("OK"); 137 | response.setFilePath(file); 138 | return; 139 | } 140 | 141 | void HttpServer::send(const http::HttpResponse &response, const nsocket::ClientSocket &clientSocket) { 142 | char header[BUFFERSIZE]; 143 | bzero(header, '\0'); 144 | const char *internal_error = "Internal Error"; 145 | struct stat file_stat; 146 | response.appenBuffer(header); 147 | if (stat(response.filePath().c_str(), &file_stat) < 0) { 148 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 149 | sprintf(header, "%s%s", header, internal_error); 150 | ::send(clientSocket.fd, header, strlen(header), 0); 151 | return; 152 | } 153 | 154 | int filefd = ::open(response.filePath().c_str(), O_RDONLY); 155 | if (filefd < 0) { 156 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 157 | sprintf(header, "%s%s", header, internal_error); 158 | ::send(clientSocket.fd, header, strlen(header), 0); 159 | return; 160 | } 161 | 162 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, file_stat.st_size); 163 | ::send(clientSocket.fd, header, strlen(header), 0); 164 | void *mapbuf = mmap(NULL, file_stat.st_size, PROT_READ, MAP_PRIVATE, filefd, 0); 165 | ::send(clientSocket.fd, mapbuf, file_stat.st_size, 0); 166 | munmap(mapbuf, file_stat.st_size); 167 | close(filefd); 168 | return; 169 | err: 170 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 171 | sprintf(header, "%s%s", header, internal_error); 172 | ::send(clientSocket.fd, header, strlen(header), 0); 173 | return; 174 | } -------------------------------------------------------------------------------- /version_0.2/src/ssocket.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | #include "../include/ssocket.h" 6 | 7 | void nsocket::setReusePort(int fd) { 8 | int opt = 1; 9 | setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt)); 10 | } 11 | 12 | nsocket::ServerSocket::ServerSocket(int port, const char *ip) : mPort(port), mIp(ip) { 13 | bzero(&mAddr, sizeof(mAddr)); 14 | mAddr.sin_family = AF_INET; 15 | mAddr.sin_port = htons(port); 16 | if (ip != nullptr) { 17 | ::inet_pton(AF_INET, ip, &mAddr.sin_addr); 18 | } else { 19 | mAddr.sin_addr.s_addr = htonl(INADDR_ANY); 20 | } 21 | fd = socket(AF_INET, SOCK_STREAM, 0); 22 | if (fd == -1) { 23 | std::cout << "creat socket error in file <" << __FILE__ << "> " 24 | << "at " << __LINE__ << std::endl; 25 | exit(0); 26 | } 27 | setReusePort(fd); 28 | } 29 | 30 | void nsocket::ServerSocket::bind() { 31 | int ret = ::bind(fd, (struct sockaddr *)&mAddr, sizeof(mAddr)); 32 | if (ret == -1) { 33 | std::cout << "bind error in file <" << __FILE__ << "> " 34 | << "at " << __LINE__ << std::endl; 35 | exit(0); 36 | } 37 | } 38 | 39 | void nsocket::ServerSocket::listen() { 40 | int ret = ::listen(fd, 5); 41 | if (ret == -1) { 42 | std::cout << "listen error in file <" << __FILE__ << "> " 43 | << "at " << __LINE__ << std::endl; 44 | exit(0); 45 | } 46 | } 47 | 48 | int nsocket::ServerSocket::accept(ClientSocket &clientSocket) { 49 | int clientfd = ::accept(fd, (struct sockaddr *)&clientSocket.mAddr, &clientSocket.mLen); 50 | if (clientfd < 0) { 51 | std::cout << "accept error in file <" << __FILE__ << "> " 52 | << "at " << __LINE__ << std::endl; 53 | exit(0); 54 | } 55 | clientSocket.fd = clientfd; 56 | std::cout << "accept a client" << std::endl; 57 | return clientfd; 58 | } 59 | 60 | nsocket::ServerSocket::~ServerSocket() { ::close(fd); } 61 | 62 | nsocket::ClientSocket::~ClientSocket() { ::close(fd); } 63 | -------------------------------------------------------------------------------- /version_0.2/test/test.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | int main() { 17 | // string s = "/helo/world/index?word=12"; 18 | // s.erase(s.rfind('?')); 19 | // string filetype; 20 | // if (s.rfind('.') != string::npos){ 21 | // filetype = s.substr(s.rfind('.')); 22 | // } 23 | // 24 | // 25 | // cout << s << endl; 26 | // if (filetype != "") { 27 | // cout << filetype << endl; 28 | // } else { 29 | // cout << " no file type" << endl; 30 | // } 31 | char *buffer; 32 | //也可以将buffer作为输出参数 33 | if ((buffer = getcwd(NULL, 0)) == NULL) { 34 | perror("getcwd error"); 35 | } else { 36 | printf("%s\n", buffer); 37 | free(buffer); 38 | } 39 | 40 | enum Code { ok = 201, notfound = 404 }; 41 | 42 | Code code = ok; 43 | printf("%d\n", code); 44 | } -------------------------------------------------------------------------------- /version_0.2/test/test_utils.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | #include "../include/Util.h" 10 | 11 | using namespace std; 12 | 13 | void test_ltrim() { 14 | std::string s = " \thelloworld\t "; 15 | util::ltrim(s); 16 | if (s == "helloworld\t ") { 17 | cout << "ltrim ok" << endl; 18 | } else { 19 | cout << "test ltrim faild" << endl; 20 | } 21 | } 22 | void test_rtrim() { 23 | std::string s = " \thelloworld\t "; 24 | util::rtrim(s); 25 | if (s == " \thelloworld") { 26 | cout << "rtrim ok" << endl; 27 | } else { 28 | cout << "test rtrim faild" << endl; 29 | } 30 | } 31 | 32 | void test_trim() { 33 | std::string s = " 1"; 34 | util::trim(s); 35 | if (s == "1") { 36 | cout << "trim ok" << endl; 37 | } else { 38 | cout << "test trim faild" << endl; 39 | } 40 | } 41 | 42 | int main() { 43 | test_ltrim(); 44 | test_rtrim(); 45 | test_trim(); 46 | } 47 | -------------------------------------------------------------------------------- /version_0.3/include/condition.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include "mutex_lock.h" 11 | #include "noncopyable.h" 12 | 13 | namespace csguide_webserver { 14 | 15 | class Condition : public Noncopyable { 16 | public: 17 | explicit Condition(MutexLock &mutex) : mutex_(mutex) { pthread_cond_init(&cond_, NULL); } 18 | 19 | ~Condition() { pthread_cond_destroy(&cond_); } 20 | 21 | void inline Wait() { pthread_cond_wait(&cond_, mutex_.GetMutex()); } 22 | 23 | void inline Notify() { pthread_cond_signal(&cond_); } 24 | 25 | void inline NotifyAll() { pthread_cond_broadcast(&cond_); } 26 | 27 | private: 28 | MutexLock &mutex_; 29 | pthread_cond_t cond_; 30 | }; 31 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/epoll.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "http_data.h" 16 | #include "socket.h" 17 | #include "timer.h" 18 | 19 | namespace csguide_webserver { 20 | 21 | class Epoll { 22 | 23 | public: 24 | static int Init(int max_events); 25 | 26 | static int Addfd(int epoll_fd, int fd, __uint32_t events, std::shared_ptr http_data); 27 | 28 | static int Modfd(int epoll_fd, int fd, __uint32_t events, std::shared_ptr http_data); 29 | 30 | static int Delfd(int epoll_fd, int fd, __uint32_t events); 31 | 32 | static std::vector> Poll(const ServerSocket &server_socket, int max_event, int timeout); 33 | 34 | static void HandleConnection(const ServerSocket &server_socket); 35 | 36 | public: 37 | static std::unordered_map> http_data_map_; 38 | static const int MAX_EVENTS; 39 | static epoll_event *events_; 40 | static TimerManager timer_manager_; 41 | const static __uint32_t DEFAULT_EVENTS; 42 | }; 43 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/http_data.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include "http_parse.h" 11 | #include "http_response.h" 12 | #include "socket.h" 13 | #include "timer.h" 14 | 15 | namespace csguide_webserver { 16 | 17 | class TimerNode; 18 | 19 | class HttpData : public std::enable_shared_from_this { 20 | public: 21 | HttpData() : epoll_fd(-1) {} 22 | 23 | public: 24 | std::shared_ptr request_; 25 | std::shared_ptr response_; 26 | std::shared_ptr client_socket_; 27 | int epoll_fd; 28 | 29 | public: 30 | 31 | void CloseTimer(); 32 | 33 | void SetTimer(std::shared_ptr); 34 | 35 | private: 36 | std::weak_ptr timer_; 37 | }; 38 | 39 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/http_parse.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | namespace csguide_webserver { 13 | 14 | #define CR '\r' 15 | #define LF '\n' 16 | #define LINE_END '\0' 17 | #define PASS 18 | 19 | class HttpRequest; 20 | 21 | std::ostream &operator<<(std::ostream &, const HttpRequest &); 22 | 23 | class HttpRequestParser { 24 | public: 25 | enum LINE_STATE { LINE_OK = 0, LINE_BAD, LINE_MORE }; 26 | enum PARSE_STATE { PARSE_REQUESTLINE = 0, PARSE_HEADER, PARSE_BODY }; 27 | enum HTTP_CODE { NO_REQUEST, GET_REQUEST, BAD_REQUEST, FORBIDDEN_REQUEST, INTERNAL_ERROR, CLOSED_CONNECTION }; 28 | 29 | static LINE_STATE ParseLine(char *buffer, int &checked_index, int &read_index); 30 | 31 | static HTTP_CODE ParseRequestline(char *line, PARSE_STATE &parse_state, HttpRequest &request); 32 | 33 | static HTTP_CODE ParseHeaders(char *line, PARSE_STATE &parse_state, HttpRequest &request); 34 | 35 | static HTTP_CODE ParseBody(char *body, HttpRequest &request); 36 | 37 | static HTTP_CODE ParseContent(char *buffer, int &check_index, int &read_index, PARSE_STATE &parse_state, 38 | int &start_line, HttpRequest &request); 39 | }; 40 | } // namespace csguide_webserver 41 | -------------------------------------------------------------------------------- /version_0.3/include/http_request.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | #include 10 | 11 | namespace csguide_webserver { 12 | 13 | class HttpRequest; 14 | 15 | std::ostream &operator<<(std::ostream &, const HttpRequest &); 16 | 17 | struct HttpRequest { 18 | friend std::ostream &operator<<(std::ostream &, const HttpRequest &); 19 | 20 | enum HTTP_VERSION { HTTP_10 = 0, HTTP_11, VERSION_NOT_SUPPORT }; 21 | enum HTTP_METHOD { GET = 0, POST, PUT, DELETE, METHOD_NOT_SUPPORT }; 22 | enum HTTP_HEADER { 23 | Host = 0, 24 | User_Agent, 25 | Connection, 26 | Accept_Encoding, 27 | Accept_Language, 28 | Accept, 29 | Cache_Control, 30 | Upgrade_Insecure_Requests 31 | }; 32 | 33 | struct EnumClassHash { 34 | template 35 | std::size_t operator()(T t) const { 36 | return static_cast(t); 37 | } 38 | }; 39 | 40 | static std::unordered_map header_map; 41 | 42 | HttpRequest(std::string url = std::string(""), HTTP_METHOD method = METHOD_NOT_SUPPORT, 43 | HTTP_VERSION version = VERSION_NOT_SUPPORT) 44 | : mMethod(method), 45 | mVersion(version), 46 | mUri(url), 47 | mContent(nullptr), 48 | mHeaders(std::unordered_map()){}; 49 | 50 | HTTP_METHOD mMethod; 51 | HTTP_VERSION mVersion; 52 | std::string mUri; 53 | char *mContent; 54 | std::unordered_map mHeaders; 55 | }; 56 | 57 | } // namespace csguide_webserver 58 | -------------------------------------------------------------------------------- /version_0.3/include/http_response.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #include "http_request.h" 13 | 14 | namespace csguide_webserver { 15 | 16 | struct MimeType { 17 | MimeType(const std::string &str) : type(str){}; 18 | 19 | MimeType(const char *str) : type(str){}; 20 | 21 | std::string type; 22 | }; 23 | 24 | extern std::unordered_map MimeMap; 25 | 26 | class HttpResponse { 27 | public: 28 | enum HttpStatusCode { Unknow, k200Ok = 200, k403forbiden = 403, k404NotFound = 404 }; 29 | 30 | explicit HttpResponse(bool mkeep = true) 31 | : status_code_(Unknow), keep_alive_(mkeep), mime_("text/html"), body_buufer(nullptr), version_(HttpRequest::HTTP_11) {} 32 | 33 | void SetStatusCode(HttpStatusCode code) { status_code_ = code; } 34 | 35 | void SetBody(const char *buf) { body_buufer = buf; } 36 | 37 | void SetContentLength(int len) { content_length_ = len; } 38 | 39 | void SetVersion(const HttpRequest::HTTP_VERSION &version) { version_ = version; } 40 | 41 | void SetStatusMsg(const std::string &msg) { status_msg_ = msg; } 42 | 43 | void SetFilePath(const std::string &path) { file_path_ = path; } 44 | 45 | void SetMime(const MimeType &mime) { mime_ = mime; } 46 | 47 | void SetKeepAlive(bool isalive) { keep_alive_ = isalive; } 48 | 49 | void AddHeader(const std::string &key, const std::string &value) { headers_[key] = value; } 50 | 51 | bool KeepAlive() const { return keep_alive_; } 52 | 53 | const HttpRequest::HTTP_VERSION Version() const { return version_; } 54 | 55 | const std::string &FilePath() const { return file_path_; } 56 | 57 | HttpStatusCode StatusCode() const { return status_code_; } 58 | 59 | const std::string &StatusMsg() const { return status_msg_; } 60 | 61 | void AppenBuffer(char *) const; 62 | 63 | ~HttpResponse() { 64 | if (body_buufer != nullptr) delete[] body_buufer; 65 | } 66 | 67 | private: 68 | HttpStatusCode status_code_; 69 | HttpRequest::HTTP_VERSION version_; 70 | std::string status_msg_; 71 | bool keep_alive_; 72 | MimeType mime_; 73 | const char *body_buufer; 74 | int content_length_; 75 | std::string file_path_; 76 | std::unordered_map headers_; 77 | }; 78 | 79 | } // namespace csguide_webserver 80 | -------------------------------------------------------------------------------- /version_0.3/include/ini_file.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | * Brief: INI 格式的配置文件解析器 5 | */ 6 | 7 | #pragma once 8 | 9 | #include 10 | 11 | #include "ini_section.h" 12 | 13 | namespace csguide_webserver { 14 | 15 | class INIFile { 16 | public: 17 | bool Load(const std::string& file_path); 18 | bool Save(const std::string& file_path) const; 19 | 20 | const INISection* GetSection(const std::string& name) const; 21 | void AddSection(const INISection& section); 22 | 23 | private: 24 | std::vector sections_; 25 | }; 26 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/ini_section.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | * Brief: INI 格式的配置文件解析器 5 | */ 6 | 7 | #pragma once 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | namespace csguide_webserver { 15 | 16 | class INISection { 17 | public: 18 | INISection(const std::string& name = "") : name_(name) {} 19 | 20 | bool Parse(const std::string& input_line); 21 | 22 | bool ParseKV(const std::string& line); 23 | 24 | friend std::ostream& operator<<(std::ostream& os, const INISection& section); 25 | 26 | const std::string& GetName() const { return name_; } 27 | const std::string& GetValue(const std::string& key) const; 28 | void SetValue(const std::string& key, const std::string& value); 29 | 30 | private: 31 | std::string name_; 32 | bool section_start_ = false; // 已经读到这一节开始 33 | std::map key_value_pairs_; 34 | }; 35 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/logger.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | * Brief: 简单的日志类 5 | */ 6 | 7 | #pragma once 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | namespace csguide_webserver { 16 | #pragma once 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | enum LogLevel { RUN, ERROR, DEBUG }; 25 | 26 | class Logger { 27 | public: 28 | static Logger& GetInstance() { 29 | static Logger instance; 30 | return instance; 31 | } 32 | 33 | Logger(const Logger&) = delete; 34 | void operator=(const Logger&) = delete; 35 | 36 | void SetLogFile(const std::string& log_file_path); 37 | 38 | template 39 | void Log(LogLevel level, const std::string& fmt_str, Args... args); 40 | 41 | template 42 | void LogRun(const std::string& fmt_str, Args... args) { 43 | Log(RUN, fmt_str, args...); 44 | } 45 | 46 | template 47 | void LogErr(const std::string& fmt_str, Args... args) { 48 | Log(ERROR, fmt_str, args...); 49 | } 50 | 51 | template 52 | void LogDebug(const std::string& fmt_str, Args... args) { 53 | Log(DEBUG, fmt_str, args...); 54 | } 55 | 56 | private: 57 | Logger(); 58 | ~Logger(); 59 | 60 | const char* LogLevelToString(LogLevel level); 61 | std::string FormatMessage(const std::string& fmt_str, ...); 62 | 63 | std::ofstream log_file_; 64 | bool use_file_; 65 | }; 66 | 67 | // 在头文件中提供模板的定义以避免链接错误 68 | template 69 | void Logger::Log(LogLevel level, const std::string& fmt_str, Args... args) { 70 | std::string message = FormatMessage(fmt_str.c_str(), args...); 71 | std::string formatted_msg = LogLevelToString(level) + std::string(": ") + message; 72 | 73 | if (use_file_) { 74 | log_file_ << formatted_msg << std::endl; 75 | } else { 76 | std::cout << formatted_msg << std::endl; 77 | } 78 | } 79 | 80 | 81 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/mutex_lock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include "noncopyable.h" 11 | 12 | namespace csguide_webserver { 13 | 14 | class MutexLock : public Noncopyable { 15 | public: 16 | MutexLock() { pthread_mutex_init(&mutex_, NULL); } 17 | 18 | ~MutexLock() { pthread_mutex_destroy(&mutex_); } 19 | 20 | void inline Lock() { pthread_mutex_lock(&mutex_); } 21 | 22 | void inline Unlock() { pthread_mutex_unlock(&mutex_); } 23 | 24 | pthread_mutex_t *GetMutex() { return &mutex_; } 25 | 26 | private: 27 | pthread_mutex_t mutex_; 28 | }; 29 | 30 | class MutexLockGuard : public Noncopyable { 31 | public: 32 | explicit MutexLockGuard(MutexLock &mutex) : mutex_(mutex) { mutex_.Lock(); } 33 | 34 | ~MutexLockGuard() { mutex_.Unlock(); } 35 | 36 | private: 37 | MutexLock &mutex_; 38 | }; 39 | } // namespace csguide_webserver 40 | -------------------------------------------------------------------------------- /version_0.3/include/noncopyable.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | * Brief: 定义不可复制(Non-copyable)类,禁用了拷贝构造函数和拷贝赋值运算符 5 | * 通过将构造和析构函数声明为protected,允许子类继承并实例化。 6 | */ 7 | 8 | #pragma once 9 | 10 | namespace csguide_webserver { 11 | class Noncopyable { 12 | public: 13 | // 禁用拷贝构造函数 14 | Noncopyable(const Noncopyable&) = delete; 15 | 16 | // 禁用拷贝赋值运算符 17 | Noncopyable& operator=(const Noncopyable&) = delete; 18 | 19 | protected: 20 | // 默认构造函数,子类可以实例化 21 | Noncopyable() = default; 22 | 23 | // 默认析构函数 24 | ~Noncopyable() = default; 25 | }; 26 | } // namespace csguide_webserver 27 | -------------------------------------------------------------------------------- /version_0.3/include/server.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include "http_data.h" 11 | #include "http_parse.h" 12 | #include "http_response.h" 13 | #include "socket.h" 14 | 15 | namespace csguide_webserver { 16 | 17 | #define BUFFERSIZE 2048 18 | 19 | struct ServerConf { 20 | int thread_num = 4; 21 | int port = 8080; 22 | bool daemon = true; 23 | std::string root = "./pages/"; // 这是默认目录,也就是当前项目的 pages 子目录 24 | }; 25 | 26 | class HttpServer { 27 | public: 28 | enum FileState { FILE_OK, FIlE_NOT_FOUND, FILE_FORBIDDEN }; 29 | 30 | public: 31 | HttpServer(const ServerConf& server_conf, const char* ip = nullptr) 32 | : server_conf_(server_conf), serverSocket(server_conf.port, ip) { 33 | serverSocket.Bind(); 34 | serverSocket.Listen(); 35 | } 36 | 37 | void Run(int max_queue_size = 10000); 38 | 39 | void DoRequest(std::shared_ptr arg); 40 | 41 | private: 42 | void Header(std::shared_ptr http_data); 43 | 44 | FileState StaticFile(std::shared_ptr http_data); 45 | 46 | void Send(std::shared_ptr http_data, FileState file_state); 47 | 48 | void GetMime(std::shared_ptr http_data); 49 | 50 | private: 51 | const ServerConf& server_conf_; 52 | ServerSocket serverSocket; 53 | }; 54 | 55 | } // namespace csguide_webserver 56 | -------------------------------------------------------------------------------- /version_0.3/include/socket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | 16 | namespace csguide_webserver { 17 | 18 | class ClientSocket; 19 | 20 | void setReusePort(int fd); 21 | 22 | class ServerSocket { 23 | public: 24 | ServerSocket(int port = 8080, const char *ip = nullptr); 25 | 26 | ~ServerSocket(); 27 | 28 | void Bind(); 29 | 30 | void Listen(); 31 | 32 | void Close(); 33 | 34 | int Accept(ClientSocket &) const; 35 | 36 | public: 37 | sockaddr_in sockaddr_in_; 38 | int listen_fd_; 39 | int epoll_fd_; 40 | int port_; 41 | const char *ip_; 42 | }; 43 | 44 | class ClientSocket { 45 | public: 46 | ClientSocket() { fd_ = -1; }; 47 | 48 | void close(); 49 | 50 | ~ClientSocket(); 51 | 52 | socklen_t socklen_; 53 | sockaddr_in sockaddr_in_; 54 | int fd_; 55 | }; 56 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/include/thread_pool.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "condition.h" 16 | #include "mutex_lock.h" 17 | #include "noncopyable.h" 18 | 19 | namespace csguide_webserver { 20 | 21 | const int MAX_THREAD_SIZE = 1024; 22 | const int MAX_QUEUE_SIZE = 10000; 23 | 24 | typedef enum { immediate_mode = 1, graceful_mode = 2 } ShutdownMode; 25 | 26 | struct ThreadTask { 27 | std::function)> process; // 实际传入的是Server::do_request; 28 | std::shared_ptr arg; // 实际应该是HttpData对象 29 | }; 30 | 31 | class ThreadPool { 32 | public: 33 | ThreadPool(int thread_s, int max_queue_s); 34 | 35 | ~ThreadPool(); 36 | 37 | bool Append(std::shared_ptr arg, std::function)> fun); 38 | 39 | void Shutdown(bool graceful); 40 | 41 | private: 42 | static void *worker(void *args); 43 | 44 | void run(); 45 | 46 | private: 47 | // 线程同步互斥, mutex_ 在 condition_前面 48 | MutexLock mutex_; 49 | Condition condition_; 50 | 51 | // 线程池属性 52 | int thread_size_; 53 | int max_queue_size_; 54 | int started_; 55 | int shutdown_; 56 | std::vector threads_; 57 | std::list request_queue_; 58 | }; 59 | 60 | } // namespace csguide_webserver 61 | -------------------------------------------------------------------------------- /version_0.3/include/timer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #include "http_data.h" 13 | #include "mutex_lock.h" 14 | 15 | namespace csguide_webserver { 16 | 17 | class HttpData; 18 | 19 | class TimerNode { 20 | public: 21 | TimerNode(std::shared_ptr httpData, size_t timeout); 22 | ~TimerNode(); 23 | 24 | public: 25 | bool IsDeleted() const { return deleted_; } 26 | 27 | size_t GetExpireTime() { return expired_time_; } 28 | 29 | bool isExpire() { 30 | // 平凡调用系统调用不好 31 | // current_time(); 32 | return expired_time_ < current_msec_; 33 | } 34 | 35 | void Deleted(); 36 | 37 | std::shared_ptr GetHttpData() { return http_data_; } 38 | 39 | static void CurrentTime(); 40 | private: 41 | static size_t current_msec_; // 当前时间 42 | bool deleted_; 43 | size_t expired_time_; // 毫秒 44 | std::shared_ptr http_data_; 45 | }; 46 | 47 | struct TimerCmp { 48 | bool operator()(std::shared_ptr &a, std::shared_ptr &b) const { 49 | return a->GetExpireTime() > b->GetExpireTime(); 50 | } 51 | }; 52 | 53 | class TimerManager { 54 | public: 55 | typedef std::shared_ptr Shared_TimerNode; 56 | 57 | public: 58 | void addTimer(std::shared_ptr httpData, size_t timeout); 59 | 60 | void handle_expired_event(); 61 | 62 | const static size_t DEFAULT_TIME_OUT; 63 | 64 | private: 65 | std::priority_queue, TimerCmp> timer_queue_; 66 | MutexLock lock_; 67 | }; 68 | 69 | } // namespace csguide_webserver 70 | -------------------------------------------------------------------------------- /version_0.3/include/util.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | #include "server.h" 11 | 12 | using namespace std; 13 | 14 | namespace csguide_webserver { 15 | 16 | std::string &Ltrim(string &); 17 | 18 | std::string &Rtrim(string &); 19 | 20 | std::string &Trim(string &); 21 | 22 | int SetNonBlocking(int fd); 23 | 24 | void HandleForSigPipe(); 25 | 26 | int CheckBasePath(const std::string &base_path); 27 | 28 | bool EndsWith(std::string const &str, std::string const &suffix); 29 | 30 | int StrToInt(const std::string &str, int &result); 31 | 32 | int ParseConfig(const std::string config_file, ServerConf &server_conf); 33 | 34 | std::string ExtractSubstring(const std::string &input, char start_char, char end_char); 35 | 36 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/epoll.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/epoll.h" 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | #include "../include/util.h" 15 | 16 | namespace csguide_webserver { 17 | 18 | // 全局静态变量初始化 19 | std::unordered_map> Epoll::http_data_map_; 20 | 21 | const int Epoll::MAX_EVENTS = 10000; 22 | 23 | epoll_event *Epoll::events_; 24 | 25 | // 可读 | ET模 | 保证一个socket连接在任一时刻只被一个线程处理 26 | const __uint32_t Epoll::DEFAULT_EVENTS = (EPOLLIN | EPOLLET | EPOLLONESHOT); 27 | 28 | TimerManager Epoll::timer_manager_; 29 | 30 | int Epoll::Init(int max_events) { 31 | int epoll_fd = ::epoll_create(max_events); 32 | if (epoll_fd == -1) { 33 | std::cout << "epoll create error" << std::endl; 34 | exit(-1); 35 | } 36 | events_ = new epoll_event[max_events]; 37 | return epoll_fd; 38 | } 39 | 40 | int Epoll::Addfd(int epoll_fd, int fd, __uint32_t events, std::shared_ptr http_data) { 41 | epoll_event event; 42 | event.events = (EPOLLIN | EPOLLET); 43 | event.data.fd = fd; 44 | // 增加httpDataMap 45 | http_data_map_[fd] = http_data; 46 | int ret = ::epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event); 47 | if (ret < 0) { 48 | std::cout << "epoll add error" << endl; 49 | // 释放httpData 50 | http_data_map_[fd].reset(); 51 | return -1; 52 | } 53 | return 0; 54 | } 55 | 56 | int Epoll::Modfd(int epoll_fd, int fd, __uint32_t events, std::shared_ptr http_data) { 57 | epoll_event event; 58 | event.events = events; 59 | event.data.fd = fd; 60 | // 每次更改的时候也更新 httpDataMap 61 | http_data_map_[fd] = http_data; 62 | int ret = ::epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &event); 63 | if (ret < 0) { 64 | std::cout << "epoll mod error" << endl; 65 | // 释放httpData 66 | http_data_map_[fd].reset(); 67 | return -1; 68 | } 69 | return 0; 70 | } 71 | 72 | int Epoll::Delfd(int epoll_fd, int fd, __uint32_t events) { 73 | epoll_event event; 74 | event.events = events; 75 | event.data.fd = fd; 76 | int ret = epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &event); 77 | if (ret < 0) { 78 | std::cout << "epoll del error" << endl; 79 | return -1; 80 | } 81 | auto it = http_data_map_.find(fd); 82 | if (it != http_data_map_.end()) { 83 | http_data_map_.erase(it); 84 | } 85 | return 0; 86 | } 87 | 88 | void Epoll::HandleConnection(const ServerSocket &server_socket) { 89 | std::shared_ptr tempClient(new ClientSocket); 90 | // epoll 是ET模式,循环接收连接 91 | // 需要将listen_fd设置为non-blocking 92 | 93 | while (server_socket.Accept(*tempClient) > 0) { 94 | // 设置非阻塞 95 | int ret = SetNonBlocking(tempClient->fd_); 96 | if (ret < 0) { 97 | std::cout << "setnonblocking error" << std::endl; 98 | tempClient->close(); 99 | continue; 100 | } 101 | 102 | // FIXME 接受新客户端 构造HttpData并添加定时器 103 | 104 | // 在这里做限制并发, 暂时未完成 105 | 106 | std::shared_ptr sharedHttpData(new HttpData); 107 | sharedHttpData->request_ = std::shared_ptr(new HttpRequest()); 108 | sharedHttpData->response_ = std::shared_ptr(new HttpResponse()); 109 | 110 | std::shared_ptr sharedClientSocket(new ClientSocket()); 111 | sharedClientSocket.swap(tempClient); 112 | sharedHttpData->client_socket_ = sharedClientSocket; 113 | sharedHttpData->epoll_fd = server_socket.epoll_fd_; 114 | Addfd(server_socket.epoll_fd_, sharedClientSocket->fd_, DEFAULT_EVENTS, sharedHttpData); 115 | // FIXME 默认超时时间5 秒测试添加定时器 116 | timer_manager_.addTimer(sharedHttpData, TimerManager::DEFAULT_TIME_OUT); 117 | } 118 | } 119 | 120 | std::vector> Epoll::Poll(const ServerSocket &server_socket, int max_event, int timeout) { 121 | int event_num = epoll_wait(server_socket.epoll_fd_, events_, max_event, timeout); 122 | if (event_num < 0) { 123 | std::cout << "epoll_num=" << event_num << std::endl; 124 | std::cout << "epoll_wait error" << std::endl; 125 | std::cout << errno << std::endl; 126 | exit(-1); 127 | } 128 | 129 | std::vector> httpDatas; 130 | // 遍历events集合 131 | for (int i = 0; i < event_num; i++) { 132 | int fd = events_[i].data.fd; 133 | 134 | // 监听描述符 135 | if (fd == server_socket.listen_fd_) { 136 | HandleConnection(server_socket); 137 | } else { 138 | // 出错的描述符,移除定时器, 关闭文件描述符 139 | if ((events_[i].events & EPOLLERR) || (events_[i].events & EPOLLRDHUP) || (events_[i].events & EPOLLHUP)) { 140 | auto it = http_data_map_.find(fd); 141 | if (it != http_data_map_.end()) { 142 | // 将HttpData节点和TimerNode的关联分开,这样HttpData会立即析构,在析构函数内关闭文件描述符等资源 143 | it->second->CloseTimer(); 144 | // httpDataMap.erase(it); 145 | } 146 | continue; 147 | } 148 | 149 | auto it = http_data_map_.find(fd); 150 | if (it != http_data_map_.end()) { 151 | if ((events_[i].events & EPOLLIN) || (events_[i].events & EPOLLPRI)) { 152 | httpDatas.push_back(it->second); 153 | // std::cout << "定时器中找到:" << fd << std::endl; 154 | // 清除定时器 HttpData.closeTimer() 155 | it->second->CloseTimer(); 156 | http_data_map_.erase(it); 157 | } 158 | } else { 159 | std::cout << "长连接第二次连接未找到" << std::endl; 160 | ::close(fd); 161 | continue; 162 | } 163 | // 这里有个问题是 TimerNode正常超时释放时 164 | } 165 | } 166 | return httpDatas; 167 | } 168 | 169 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/http/http_data.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../../include/http_data.h" 7 | 8 | namespace csguide_webserver { 9 | 10 | void HttpData::CloseTimer() { 11 | // 首先判断Timer是否还在, 有可能已经超时释放 12 | if (timer_.lock()) { 13 | std::shared_ptr tempTimer(timer_.lock()); 14 | tempTimer->Deleted(); 15 | // 断开weak_ptr 16 | timer_.reset(); 17 | } 18 | } 19 | 20 | void HttpData::SetTimer(std::shared_ptr timer) { timer_ = timer; } 21 | 22 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/http/http_parse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../../include/http_parse.h" 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include "../../include/http_request.h" 14 | #include "../../include/util.h" 15 | 16 | namespace csguide_webserver { 17 | 18 | std::unordered_map HttpRequest::header_map = { 19 | {"HOST", HttpRequest::Host}, 20 | {"USER-AGENT", HttpRequest::User_Agent}, 21 | {"CONNECTION", HttpRequest::Connection}, 22 | {"ACCEPT-ENCODING", HttpRequest::Accept_Encoding}, 23 | {"ACCEPT-LANGUAGE", HttpRequest::Accept_Language}, 24 | {"ACCEPT", HttpRequest::Accept}, 25 | {"CACHE-CONTROL", HttpRequest::Cache_Control}, 26 | {"UPGRADE-INSECURE-REQUESTS", HttpRequest::Upgrade_Insecure_Requests}}; 27 | 28 | // 解析一行内容, buffer[checked_index, read_index) 29 | // check_index是需要分析的第一个字符, read_index已经读取数据末尾下一个字符 30 | HttpRequestParser::LINE_STATE HttpRequestParser::ParseLine(char *buffer, int &checked_index, int &read_index) { 31 | char temp; 32 | for (; checked_index < read_index; checked_index++) { 33 | temp = buffer[checked_index]; 34 | if (temp == CR) { 35 | // 到末尾,需要读入 36 | if (checked_index + 1 == read_index) return LINE_MORE; 37 | // 完整 "\r\n" 38 | if (buffer[checked_index + 1] == LF) { 39 | buffer[checked_index++] = LINE_END; 40 | buffer[checked_index++] = LINE_END; 41 | return LINE_OK; 42 | } 43 | 44 | return LINE_BAD; 45 | } 46 | } 47 | // 需要读入更多 48 | return LINE_MORE; 49 | } 50 | 51 | // 解析请求行 52 | HttpRequestParser::HTTP_CODE HttpRequestParser::ParseRequestline(char *line, PARSE_STATE &parse_state, 53 | HttpRequest &request) { 54 | char *url = strpbrk(line, " \t"); 55 | if (!url) { 56 | return BAD_REQUEST; 57 | } 58 | 59 | // 分割 method 和 url 60 | *url++ = '\0'; 61 | 62 | char *method = line; 63 | 64 | if (strcasecmp(method, "GET") == 0) { 65 | request.mMethod = HttpRequest::GET; 66 | } else if (strcasecmp(method, "POST") == 0) { 67 | request.mMethod = HttpRequest::POST; 68 | } else if (strcasecmp(method, "PUT") == 0) { 69 | request.mMethod = HttpRequest::PUT; 70 | } else { 71 | return BAD_REQUEST; 72 | } 73 | 74 | url += strspn(url, " \t"); 75 | char *version = strpbrk(url, " \t"); 76 | if (!version) { 77 | return BAD_REQUEST; 78 | } 79 | *version++ = '\0'; 80 | version += strspn(version, " \t"); 81 | 82 | // HTTP/1.1 后面可能还存在空白字符 83 | if (strncasecmp("HTTP/1.1", version, 8) == 0) { 84 | request.mVersion = HttpRequest::HTTP_11; 85 | } else if (strncasecmp("HTTP/1.0", version, 8) == 0) { 86 | request.mVersion = HttpRequest::HTTP_10; 87 | } else { 88 | return BAD_REQUEST; 89 | } 90 | 91 | if (strncasecmp(url, "http://", 7) == 0) { 92 | url += 7; 93 | url = strchr(url, '/'); 94 | } else if (strncasecmp(url, "/", 1) == 0) { 95 | PASS; 96 | } else { 97 | return BAD_REQUEST; 98 | } 99 | 100 | if (!url || *url != '/') { 101 | return BAD_REQUEST; 102 | } 103 | request.mUri = std::string(url); 104 | // 分析头部字段 105 | parse_state = PARSE_HEADER; 106 | return NO_REQUEST; 107 | } 108 | 109 | // 分析头部字段 110 | HttpRequestParser::HTTP_CODE HttpRequestParser::ParseHeaders(char *line, PARSE_STATE &parse_state, 111 | HttpRequest &request) { 112 | if (*line == '\0') { 113 | if (request.mMethod == HttpRequest::GET) { 114 | return GET_REQUEST; 115 | } 116 | parse_state = PARSE_BODY; 117 | return NO_REQUEST; 118 | } 119 | 120 | // FIXME char key[20]曾被缓冲区溢出, value[100]也被 chrome的user-agent 溢出 121 | char key[100], value[300]; 122 | 123 | // FIXME 需要修改有些value里也包含了':'符号 124 | sscanf(line, "%[^:]:%[^:]", key, value); 125 | 126 | decltype(HttpRequest::header_map)::iterator it; 127 | std::string key_s(key); 128 | std::transform(key_s.begin(), key_s.end(), key_s.begin(), ::toupper); 129 | std::string value_s(value); 130 | // if (key_s == std::string("UPGRADE-INSECURE-REQUESTS")) { 131 | // return NO_REQUEST; 132 | // } 133 | 134 | if ((it = HttpRequest::header_map.find(Trim(key_s))) != (HttpRequest::header_map.end())) { 135 | request.mHeaders.insert(std::make_pair(it->second, Trim(value_s))); 136 | } else { 137 | // std::cout << "Header no support: " << key << " : " << value << std::endl; 138 | } 139 | 140 | return NO_REQUEST; 141 | } 142 | 143 | // 解析body 144 | HttpRequestParser::HTTP_CODE HttpRequestParser::ParseBody(char *body, HttpRequest &request) { 145 | request.mContent = body; 146 | return GET_REQUEST; 147 | } 148 | 149 | // http 请求入口 150 | HttpRequestParser::HTTP_CODE HttpRequestParser::ParseContent(char *buffer, int &check_index, int &read_index, 151 | HttpRequestParser::PARSE_STATE &parse_state, 152 | int &start_line, HttpRequest &request) { 153 | LINE_STATE line_state = LINE_OK; 154 | HTTP_CODE retcode = NO_REQUEST; 155 | while ((line_state = ParseLine(buffer, check_index, read_index)) == LINE_OK) { 156 | char *temp = buffer + start_line; // 这一行在buffer中的起始位置 157 | start_line = check_index; // 下一行起始位置 158 | 159 | switch (parse_state) { 160 | case PARSE_REQUESTLINE: { 161 | retcode = ParseRequestline(temp, parse_state, request); 162 | if (retcode == BAD_REQUEST) return BAD_REQUEST; 163 | 164 | break; 165 | } 166 | 167 | case PARSE_HEADER: { 168 | retcode = ParseHeaders(temp, parse_state, request); 169 | if (retcode == BAD_REQUEST) { 170 | return BAD_REQUEST; 171 | } else if (retcode == GET_REQUEST) { 172 | return GET_REQUEST; 173 | } 174 | break; 175 | } 176 | 177 | case PARSE_BODY: { 178 | retcode = ParseBody(temp, request); 179 | if (retcode == GET_REQUEST) { 180 | return GET_REQUEST; 181 | } 182 | return BAD_REQUEST; 183 | } 184 | default: 185 | return INTERNAL_ERROR; 186 | } 187 | } 188 | if (line_state == LINE_MORE) { 189 | return NO_REQUEST; 190 | } else { 191 | return BAD_REQUEST; 192 | } 193 | } 194 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/http/http_request.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../../include/http_request.h" 7 | 8 | namespace csguide_webserver { 9 | 10 | // 重载HttpRequest << 11 | std::ostream &operator<<(std::ostream &os, const HttpRequest &request) { 12 | os << "method:" << request.mMethod << std::endl; 13 | os << "uri:" << request.mUri << std::endl; 14 | os << "version:" << request.mVersion << std::endl; 15 | // os << "content:" << request.mContent << std::endl; 16 | for (auto it = request.mHeaders.begin(); it != request.mHeaders.end(); it++) { 17 | os << it->first << ":" << it->second << std::endl; 18 | } 19 | return os; 20 | } 21 | 22 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/http/http_response.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../../include/http_response.h" 7 | 8 | #include 9 | 10 | namespace csguide_webserver { 11 | 12 | std::unordered_map MimeMap = {{".html", "text/html"}, 13 | {".xml", "text/xml"}, 14 | {".xhtml", "application/xhtml+xml"}, 15 | {".txt", "text/plain"}, 16 | {".rtf", "application/rtf"}, 17 | {".pdf", "application/pdf"}, 18 | {".word", "application/msword"}, 19 | {".png", "image/png"}, 20 | {".gif", "image/gif"}, 21 | {".jpg", "image/jpeg"}, 22 | {".jpeg", "image/jpeg"}, 23 | {".au", "audio/basic"}, 24 | {".mpeg", "video/mpeg"}, 25 | {".mpg", "video/mpeg"}, 26 | {".avi", "video/x-msvideo"}, 27 | {".gz", "application/x-gzip"}, 28 | {".tar", "application/x-tar"}, 29 | {".svg", "image/svg+xml"}, 30 | {".css", "text/css"}, 31 | {"", "text/plain"}, 32 | {"default", "text/plain"}}; 33 | 34 | void HttpResponse::AppenBuffer(char *buffer) const { 35 | // 版本 36 | if (version_ == HttpRequest::HTTP_11) { 37 | sprintf(buffer, "HTTP/1.1 %d %s\r\n", status_code_, status_msg_.c_str()); 38 | } else { 39 | sprintf(buffer, "HTTP/1.0 %d %s\r\n", status_code_, status_msg_.c_str()); 40 | } 41 | // 头部字段 42 | for (auto it = headers_.begin(); it != headers_.end(); it++) { 43 | sprintf(buffer, "%s%s: %s\r\n", buffer, it->first.c_str(), it->second.c_str()); 44 | } 45 | sprintf(buffer, "%sContent-type: %s\r\n", buffer, mime_.type.c_str()); 46 | // keep_alive 47 | if (keep_alive_) { 48 | sprintf(buffer, "%sConnection: keep-alive\r\n", buffer); 49 | } else { 50 | sprintf(buffer, "%sConnection: close\r\n", buffer); 51 | } 52 | } 53 | 54 | } // namespace csguide_webserver 55 | -------------------------------------------------------------------------------- /version_0.3/src/http/server.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../../include/server.h" 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #include "../../include/epoll.h" 22 | #include "../../include/http_data.h" 23 | #include "../../include/http_parse.h" 24 | #include "../../include/http_response.h" 25 | #include "../../include/thread_pool.h" 26 | #include "../../include/util.h" 27 | 28 | namespace csguide_webserver { 29 | 30 | char NOT_FOUND_PAGE[] = 31 | "\n" 32 | "404 Not Found\n" 33 | "\n" 34 | "

404 Not Found

\n" 35 | "
LC WebServer/0.3 (Linux)
\n" 36 | "\n" 37 | ""; 38 | 39 | char FORBIDDEN_PAGE[] = 40 | "\n" 41 | "403 Forbidden\n" 42 | "\n" 43 | "

403 Forbidden

\n" 44 | "
LC WebServer/0.3 (Linux)
\n" 45 | "\n" 46 | ""; 47 | 48 | char INDEX_PAGE[] = 49 | "\n" 50 | "\n" 51 | "\n" 52 | " Welcome to LC WebServer!\n" 53 | " \n" 60 | "\n" 61 | "\n" 62 | "

Welcome to LC WebServer!

\n" 63 | "

If you see this page, the lc webserver is successfully installed and\n" 64 | " working.

\n" 65 | "\n" 66 | "

For online documentation and support please refer to\n" 67 | " LC " 68 | "WebServer.
\n" 69 | "\n" 70 | "

Thank you for using LC WebServer.

\n" 71 | "\n" 72 | ""; 73 | 74 | char TEST[] = "HELLO WORLD"; 75 | 76 | void HttpServer::Run(int max_queue_size) { 77 | ThreadPool threadPool(server_conf_.thread_num, max_queue_size); 78 | int epoll_fd = Epoll::Init(1024); 79 | std::shared_ptr httpData(new HttpData()); 80 | httpData->epoll_fd = epoll_fd; 81 | serverSocket.epoll_fd_ = epoll_fd; // 之前就是这里忘了添加,导致穿进去的serverSocket具有不正确的epoll_fd 82 | 83 | __uint32_t event = (EPOLLIN | EPOLLET); 84 | Epoll::Addfd(epoll_fd, serverSocket.listen_fd_, event, httpData); 85 | 86 | while (true) { 87 | std::vector> events = Epoll::Poll(serverSocket, 1024, -1); 88 | // FIXME 将事件传递给 线程池 89 | for (auto& req : events) { 90 | threadPool.Append(req, std::bind(&HttpServer::DoRequest, this, std::placeholders::_1)); 91 | } 92 | // 处理定时器超时事件 93 | Epoll::timer_manager_.handle_expired_event(); 94 | } 95 | } 96 | 97 | void HttpServer::DoRequest(std::shared_ptr arg) { 98 | std::shared_ptr sharedHttpData = std::static_pointer_cast(arg); 99 | 100 | char buffer[BUFFERSIZE]; 101 | 102 | bzero(buffer, BUFFERSIZE); 103 | int check_index = 0, read_index = 0, start_line = 0; 104 | ssize_t recv_data; 105 | HttpRequestParser::PARSE_STATE parse_state = HttpRequestParser::PARSE_REQUESTLINE; 106 | 107 | while (true) { 108 | // FIXME 这里也是同样的,由于是非阻塞IO,所以返回-1 109 | // 也不一定是错误,还需判断error 110 | recv_data = recv(sharedHttpData->client_socket_->fd_, buffer + read_index, BUFFERSIZE - read_index, 0); 111 | if (recv_data == -1) { 112 | if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { 113 | return; // FIXME 请求不完整该怎么办,继续加定时器吗?还是直接关闭 114 | } 115 | std::cout << "reading faild" << std::endl; 116 | return; 117 | } 118 | // todo 返回值为 0对端关闭, 这边也应该关闭定时器 119 | 120 | if (recv_data == 0) { 121 | std::cout << "connection closed by peer" << std::endl; 122 | break; 123 | } 124 | read_index += recv_data; 125 | 126 | HttpRequestParser::HTTP_CODE retcode = HttpRequestParser::ParseContent( 127 | buffer, check_index, read_index, parse_state, start_line, *sharedHttpData->request_); 128 | 129 | if (retcode == HttpRequestParser::NO_REQUEST) { 130 | continue; 131 | } 132 | 133 | if (retcode == HttpRequestParser::GET_REQUEST) { 134 | // FIXME 检查 keep_alive选项 135 | auto it = sharedHttpData->request_->mHeaders.find(HttpRequest::Connection); 136 | if (it != sharedHttpData->request_->mHeaders.end()) { 137 | if (it->second == "keep-alive") { 138 | sharedHttpData->response_->SetKeepAlive(true); 139 | // timeout=20s 140 | sharedHttpData->response_->AddHeader("Keep-Alive", std::string("timeout=20")); 141 | } else { 142 | sharedHttpData->response_->SetKeepAlive(false); 143 | } 144 | } 145 | Header(sharedHttpData); 146 | GetMime(sharedHttpData); 147 | // FIXME 之前测试时写死的了文件路径导致上服务器出错 148 | // static_file(sharedHttpData, 149 | // "/Users/lichunlin/CLionProjects/webserver/version_0.1"); 150 | FileState fileState = StaticFile(sharedHttpData); 151 | Send(sharedHttpData, fileState); 152 | // 如果是keep_alive else 153 | // sharedHttpData将会自动析构释放clientSocket,从而关闭资源 154 | if (sharedHttpData->response_->KeepAlive()) { 155 | // FIXME std::cout << "再次添加定时器 keep_alive: " << 156 | // sharedHttpData->clientSocket_->fd << std::endl; 157 | Epoll::Modfd(sharedHttpData->epoll_fd, sharedHttpData->client_socket_->fd_, Epoll::DEFAULT_EVENTS, 158 | sharedHttpData); 159 | Epoll::timer_manager_.addTimer(sharedHttpData, TimerManager::DEFAULT_TIME_OUT); 160 | } 161 | 162 | } else { 163 | // todo Bad Request 164 | // 应该关闭定时器,(其实定时器已经关闭,在每接到一个新的数据时) 165 | std::cout << "Bad Request" << std::endl; 166 | } 167 | } 168 | } 169 | 170 | void HttpServer::Header(std::shared_ptr http_data) { 171 | if (http_data->request_->mVersion == HttpRequest::HTTP_11) { 172 | http_data->response_->SetVersion(HttpRequest::HTTP_11); 173 | } else { 174 | http_data->response_->SetVersion(HttpRequest::HTTP_10); 175 | } 176 | http_data->response_->AddHeader("Server", "LC WebServer"); 177 | } 178 | 179 | // 获取Mime 同时设置path到response 180 | void HttpServer::GetMime(std::shared_ptr http_data) { 181 | std::string filepath = http_data->request_->mUri; 182 | std::string mime; 183 | int pos; 184 | // std::cout << "uri: " << filepath << std::endl; 185 | // FIXME 直接将参数丢掉了,后续可以开发 186 | if ((pos = filepath.rfind('?')) != std::string::npos) { 187 | filepath.erase(filepath.rfind('?')); 188 | } 189 | 190 | if (filepath.rfind('.') != std::string::npos) { 191 | mime = filepath.substr(filepath.rfind('.')); 192 | } 193 | decltype(MimeMap)::iterator it; 194 | 195 | if ((it = MimeMap.find(mime)) != MimeMap.end()) { 196 | http_data->response_->SetMime(it->second); 197 | } else { 198 | http_data->response_->SetMime(MimeMap.find("default")->second); 199 | } 200 | http_data->response_->SetFilePath(filepath); 201 | } 202 | 203 | HttpServer::FileState HttpServer::StaticFile(std::shared_ptr http_data) { 204 | struct stat file_stat; 205 | std::string file = server_conf_.root + http_data->response_->FilePath(); 206 | // 如果是 / 结尾,则默认读取 /index.html 207 | // 扩展,比如访问,csguide.cn/,则默认读取 csguide.cn/index.html 208 | if (EndsWith(file, "/")) { 209 | file = file + "index.html"; 210 | // 并且重新设置 mime 为 html 211 | http_data->response_->SetMime(MimeType("text/html")); 212 | } 213 | 214 | // 文件不存在 215 | if (stat(file.c_str(), &file_stat) < 0) { 216 | // FIXME 设置Mime 为 html 217 | http_data->response_->SetMime(MimeType("text/html")); 218 | http_data->response_->SetStatusCode(HttpResponse::k404NotFound); 219 | http_data->response_->SetStatusMsg("Not Found"); 220 | // 废弃, 404就不需要设置filepath 221 | // httpData->response_->setFilePath(std::string(base_path_)+"/404.html"); 222 | // std::cout << "File Not Found: " << file << std::endl; 223 | return FIlE_NOT_FOUND; 224 | } 225 | 226 | // 不是普通文件或无访问权限 227 | if (!S_ISREG(file_stat.st_mode)) { 228 | // FIXME 设置Mime 为 html 229 | http_data->response_->SetMime(MimeType("text/html")); 230 | http_data->response_->SetStatusCode(HttpResponse::k403forbiden); 231 | http_data->response_->SetStatusMsg("ForBidden"); 232 | // 废弃, 403就不需要设置filepath 233 | // httpData->response_->setFilePath(std::string(base_path_)+"/403.html"); 234 | std::cout << "not normal file" << std::endl; 235 | return FILE_FORBIDDEN; 236 | } 237 | 238 | http_data->response_->SetStatusCode(HttpResponse::k200Ok); 239 | http_data->response_->SetStatusMsg("OK"); 240 | http_data->response_->SetFilePath(file); 241 | // std::cout << "文件存在 - ok" << std::endl; 242 | return FILE_OK; 243 | } 244 | 245 | void HttpServer::Send(std::shared_ptr http_data, FileState file_state) { 246 | char header[BUFFERSIZE]; 247 | bzero(header, '\0'); 248 | const char* internal_error = "Internal Error"; 249 | struct stat file_stat; 250 | http_data->response_->AppenBuffer(header); 251 | // 404 252 | if (file_state == FIlE_NOT_FOUND) { 253 | // 如果是 '/'开头就发送默认页 254 | if (http_data->response_->FilePath() == std::string("/")) { 255 | // 现在使用测试页面 256 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(INDEX_PAGE)); 257 | sprintf(header, "%s%s", header, INDEX_PAGE); 258 | } else { 259 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(NOT_FOUND_PAGE)); 260 | sprintf(header, "%s%s", header, NOT_FOUND_PAGE); 261 | } 262 | ::send(http_data->client_socket_->fd_, header, strlen(header), 0); 263 | return; 264 | } 265 | 266 | if (file_state == FILE_FORBIDDEN) { 267 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(FORBIDDEN_PAGE)); 268 | sprintf(header, "%s%s", header, FORBIDDEN_PAGE); 269 | ::send(http_data->client_socket_->fd_, header, strlen(header), 0); 270 | return; 271 | } 272 | // 获取文件状态 273 | if (stat(http_data->response_->FilePath().c_str(), &file_stat) < 0) { 274 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 275 | sprintf(header, "%s%s", header, internal_error); 276 | ::send(http_data->client_socket_->fd_, header, strlen(header), 0); 277 | return; 278 | } 279 | 280 | int filefd = ::open(http_data->response_->FilePath().c_str(), O_RDONLY); 281 | // 内部错误 282 | if (filefd < 0) { 283 | std::cout << "打开文件失败" << std::endl; 284 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 285 | sprintf(header, "%s%s", header, internal_error); 286 | ::send(http_data->client_socket_->fd_, header, strlen(header), 0); 287 | close(filefd); 288 | return; 289 | } 290 | 291 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, file_stat.st_size); 292 | ::send(http_data->client_socket_->fd_, header, strlen(header), 0); 293 | void* mapbuf = mmap(NULL, file_stat.st_size, PROT_READ, MAP_PRIVATE, filefd, 0); 294 | ::send(http_data->client_socket_->fd_, mapbuf, file_stat.st_size, 0); 295 | munmap(mapbuf, file_stat.st_size); 296 | close(filefd); 297 | return; 298 | err: 299 | sprintf(header, "%sContent-length: %d\r\n\r\n", header, strlen(internal_error)); 300 | sprintf(header, "%s%s", header, internal_error); 301 | ::send(http_data->client_socket_->fd_, header, strlen(header), 0); 302 | return; 303 | } 304 | 305 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include //for signal 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | #include "../include/logger.h" 20 | #include "../include/server.h" 21 | #include "../include/util.h" 22 | 23 | using namespace csguide_webserver; 24 | 25 | 26 | void daemon_run() { 27 | int pid; 28 | signal(SIGCHLD, SIG_IGN); 29 | // 1)在父进程中,fork返回新创建子进程的进程ID; 30 | // 2)在子进程中,fork返回0; 31 | // 3)如果出现错误,fork返回一个负值; 32 | pid = fork(); 33 | if (pid < 0) { 34 | std::cout << "fork error" << std::endl; 35 | exit(-1); 36 | } 37 | //父进程退出,子进程独立运行 38 | else if (pid > 0) { 39 | exit(0); 40 | } 41 | //之前parent和child运行在同一个session里,parent是会话(session)的领头进程, 42 | // parent进程作为会话的领头进程,如果exit结束执行的话,那么子进程会成为孤儿进程,并被init收养。 43 | //执行setsid()之后,child将重新获得一个新的会话(session)id。 44 | //这时parent退出之后,将不会影响到child了。 45 | setsid(); 46 | int fd; 47 | fd = open("/dev/null", O_RDWR, 0); 48 | if (fd != -1) { 49 | dup2(fd, STDIN_FILENO); 50 | dup2(fd, STDOUT_FILENO); 51 | dup2(fd, STDERR_FILENO); 52 | } 53 | if (fd > 2) close(fd); 54 | } 55 | 56 | void CheckConf(ServerConf &server_conf) { 57 | int ret = CheckBasePath(server_conf.root); 58 | if (ret != 0) { 59 | Logger::GetInstance().LogRun("Warning: \"%s\" 不存在或不可访问, 将使用当前目录作为网站根目录", optarg); 60 | char CurrenctPath[256]; 61 | // 获取当前目录出错,使用 . 代替 62 | if (getcwd(CurrenctPath, 300) == NULL) { 63 | Logger::GetInstance().LogErr("getcwd err"); 64 | server_conf.root = "."; 65 | } else { 66 | server_conf.root = CurrenctPath; 67 | } 68 | } 69 | // 去除最后的 / ,因为 basepath + url,url部分有 / 70 | if (server_conf.root[server_conf.root.size() - 1] == '/') { 71 | server_conf.root.pop_back(); 72 | } 73 | } 74 | 75 | int main(int argc, char **argv) { 76 | int opt; 77 | const char *str = "f:"; 78 | 79 | ServerConf server_conf; 80 | 81 | while ((opt = getopt(argc, argv, str)) != -1) { 82 | switch (opt) { 83 | case 'f': { 84 | if (optarg != NULL) { 85 | int ret = ParseConfig(optarg, server_conf); 86 | if (0 != ret) { 87 | Logger::GetInstance().LogErr("ParseConfig Err, exit"); 88 | exit(ret); 89 | } 90 | } else { 91 | Logger::GetInstance().LogErr("empty opt: f"); 92 | } 93 | break; 94 | } 95 | } 96 | } 97 | 98 | CheckConf(server_conf); 99 | 100 | // 输出配置信息 101 | { 102 | Logger::GetInstance().LogRun("*******CSGuide WebServer 配置信息*******"); 103 | Logger::GetInstance().LogRun("端口:\t%d", server_conf.port); 104 | Logger::GetInstance().LogRun("线程数:\t%d", server_conf.thread_num); 105 | Logger::GetInstance().LogRun("根目录:\t%s", server_conf.root.c_str()); 106 | Logger::GetInstance().LogRun("守护模式:\t%s", server_conf.daemon ? "true" : "false"); 107 | } 108 | 109 | if (server_conf.daemon) daemon_run(); 110 | 111 | HandleForSigPipe(); 112 | 113 | HttpServer httpServer(server_conf); 114 | httpServer.Run(); 115 | } 116 | -------------------------------------------------------------------------------- /version_0.3/src/socket.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/socket.h" 7 | 8 | #include 9 | #include 10 | 11 | #include "../include/util.h" 12 | 13 | namespace csguide_webserver { 14 | 15 | void SetReusePort(int fd) { 16 | int opt = 1; 17 | setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt)); 18 | } 19 | 20 | ServerSocket::ServerSocket(int port, const char *ip) : port_(port), ip_(ip) { 21 | bzero(&sockaddr_in_, sizeof(sockaddr_in_)); 22 | sockaddr_in_.sin_family = AF_INET; 23 | sockaddr_in_.sin_port = htons(port); 24 | if (ip != nullptr) { 25 | ::inet_pton(AF_INET, ip, &sockaddr_in_.sin_addr); 26 | } else { 27 | sockaddr_in_.sin_addr.s_addr = htonl(INADDR_ANY); 28 | } 29 | listen_fd_ = socket(AF_INET, SOCK_STREAM, 0); 30 | if (listen_fd_ == -1) { 31 | std::cout << "creat socket error in file <" << __FILE__ << "> " 32 | << "at " << __LINE__ << std::endl; 33 | exit(0); 34 | } 35 | SetReusePort(listen_fd_); 36 | SetNonBlocking(listen_fd_); // FIXME 之前没加,导致循环接受阻塞了 37 | } 38 | 39 | void ServerSocket::Bind() { 40 | int ret = ::bind(listen_fd_, (struct sockaddr *)&sockaddr_in_, sizeof(sockaddr_in_)); 41 | if (ret == -1) { 42 | std::cout << "bind error in file <" << __FILE__ << "> " 43 | << "at " << __LINE__ << std::endl; 44 | exit(0); 45 | } 46 | } 47 | 48 | void ServerSocket::Listen() { 49 | int ret = ::listen(listen_fd_, 1024); 50 | if (ret == -1) { 51 | std::cout << "listen error in file <" << __FILE__ << "> " 52 | << "at " << __LINE__ << std::endl; 53 | exit(0); 54 | } 55 | } 56 | 57 | int ServerSocket::Accept(ClientSocket & client_socket) const { 58 | // std::cout << "listen_fd" << listen_fd << std::endl; 59 | // FIXME 之前这里出报 Invalid arg 60 | // int clientfd = ::accept(listen_fd, (struct sockaddr*)&clientSocket.mAddr, 61 | // &clientSocket.mLen); 62 | int clientfd = ::accept(listen_fd_, NULL, NULL); 63 | 64 | // FIXME 由于之前listen_fd是阻塞的逻辑正确,但是对于非阻塞listen_fd不正确 65 | // if (clientfd < 0) { 66 | // std::cout << "accept error in file <" << __FILE__ << "> "<< "at " << 67 | // __LINE__ << std::endl; exit(0); 68 | // } 69 | if (clientfd < 0) { 70 | if ((errno == EWOULDBLOCK) || (errno == EAGAIN)) return clientfd; 71 | std::cout << "accept error in file <" << __FILE__ << "> " 72 | << "at " << __LINE__ << std::endl; 73 | std::cout << "clientfd:" << clientfd << std::endl; 74 | perror("accpet error"); 75 | // exit(0); 76 | } 77 | // std::cout << "accept a client: " << clientfd << std::endl; 78 | client_socket.fd_ = clientfd; 79 | return clientfd; 80 | } 81 | 82 | void ServerSocket::Close() { 83 | if (listen_fd_ >= 0) { 84 | ::close(listen_fd_); 85 | // std::cout << "定时器超时关闭, 文件描述符:" << listen_fd << std::endl; 86 | listen_fd_ = -1; 87 | } 88 | } 89 | ServerSocket::~ServerSocket() { Close(); } 90 | 91 | void ClientSocket::close() { 92 | if (fd_ >= 0) { 93 | // std::cout << "文件描述符关闭: " << fd < 9 | #include 10 | 11 | #include 12 | 13 | namespace csguide_webserver { 14 | 15 | ThreadPool::ThreadPool(int thread_s, int max_queue_s) 16 | : max_queue_size_(max_queue_s), thread_size_(thread_s), condition_(mutex_), started_(0), shutdown_(0) { 17 | if (thread_s <= 0 || thread_s > MAX_THREAD_SIZE) { 18 | thread_size_ = 4; 19 | } 20 | 21 | if (max_queue_s <= 0 || max_queue_s > MAX_QUEUE_SIZE) { 22 | max_queue_size_ = MAX_QUEUE_SIZE; 23 | } 24 | // 分配空间 25 | threads_.resize(thread_size_); 26 | 27 | for (int i = 0; i < thread_size_; i++) { 28 | // 后期可扩展出单独的Thread类,只需要该类拥有run方法即可 29 | if (pthread_create(&threads_[i], NULL, worker, this) != 0) { 30 | std::cout << "ThreadPool Init error" << std::endl; 31 | throw std::exception(); 32 | } 33 | started_++; 34 | } 35 | } 36 | 37 | ThreadPool::~ThreadPool() {} 38 | 39 | bool ThreadPool::Append(std::shared_ptr arg, std::function)> fun) { 40 | if (shutdown_) { 41 | std::cout << "ThreadPool has shutdown" << std::endl; 42 | return false; 43 | } 44 | 45 | MutexLockGuard guard(this->mutex_); 46 | if (request_queue_.size() > max_queue_size_) { 47 | std::cout << max_queue_size_; 48 | std::cout << "ThreadPool too many requests" << std::endl; 49 | return false; 50 | } 51 | ThreadTask threadTask; 52 | threadTask.arg = arg; 53 | threadTask.process = fun; 54 | 55 | request_queue_.push_back(threadTask); 56 | // if (request_queue.size() == 1) { 57 | // condition_.notify(); 58 | // } 59 | // 之前是先判断当前队列是否为空,为空才有线程等待在上面,才需要signal 60 | // 而后发现其实直接signal也没事,因为signal信号就算没有等待在信号上的也没事 61 | condition_.Notify(); 62 | return true; 63 | } 64 | 65 | void ThreadPool::Shutdown(bool graceful) { 66 | { 67 | MutexLockGuard guard(this->mutex_); 68 | if (shutdown_) { 69 | std::cout << "has shutdown" << std::endl; 70 | } 71 | shutdown_ = graceful ? graceful_mode : immediate_mode; 72 | condition_.NotifyAll(); 73 | } 74 | for (int i = 0; i < thread_size_; i++) { 75 | if (pthread_join(threads_[i], NULL) != 0) { 76 | std::cout << "pthread_join error" << std::endl; 77 | } 78 | } 79 | } 80 | 81 | void *ThreadPool::worker(void *args) { 82 | ThreadPool *pool = static_cast(args); 83 | // 退出线程 84 | if (pool == nullptr) return NULL; 85 | prctl(PR_SET_NAME, "EventLoopThread"); 86 | 87 | // 执行线程主方法 88 | pool->run(); 89 | return NULL; 90 | } 91 | 92 | void ThreadPool::run() { 93 | while (true) { 94 | ThreadTask requestTask; 95 | { 96 | MutexLockGuard guard(this->mutex_); 97 | // 无任务 且未shutdown 则条件等待, 注意此处应使用while而非if 98 | while (request_queue_.empty() && !shutdown_) { 99 | condition_.Wait(); 100 | } 101 | 102 | if ((shutdown_ == immediate_mode) || (shutdown_ == graceful_mode && request_queue_.empty())) { 103 | break; 104 | } 105 | // FIFO 106 | requestTask = request_queue_.front(); 107 | request_queue_.pop_front(); 108 | } 109 | requestTask.process(requestTask.arg); 110 | } 111 | } 112 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/timer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include "../include/timer.h" 7 | 8 | #include 9 | #include 10 | 11 | #include "../include/epoll.h" 12 | 13 | namespace csguide_webserver { 14 | 15 | size_t TimerNode::current_msec_ = 0; // 当前时间 16 | 17 | const size_t TimerManager::DEFAULT_TIME_OUT = 20 * 1000; // 20s 18 | 19 | TimerNode::TimerNode(std::shared_ptr httpData, size_t timeout) : deleted_(false), http_data_(httpData) { 20 | CurrentTime(); 21 | expired_time_ = current_msec_ + timeout; 22 | } 23 | 24 | TimerNode::~TimerNode() { 25 | // FIXME 26 | // 析构关闭资源的时候,要讲httpDataMap中的引用,否则资源无法关闭,后期可改进为httpDataMap存储 27 | // weak_ptr std::cout << "TimerNode析构" << std::endl; 28 | // 析构时如果是被deleted 则httpData为NULL, 29 | // 不用处理,而如果是超时,则需要删除Epoll中的httpDataMap中 30 | if (http_data_) { 31 | auto it = Epoll::http_data_map_.find(http_data_->client_socket_->fd_); 32 | if (it != Epoll::http_data_map_.end()) { 33 | Epoll::http_data_map_.erase(it); 34 | } 35 | } 36 | } 37 | 38 | void inline TimerNode::CurrentTime() { 39 | struct timeval cur; 40 | gettimeofday(&cur, NULL); 41 | current_msec_ = (cur.tv_sec * 1000) + (cur.tv_usec / 1000); 42 | } 43 | 44 | void TimerNode::Deleted() { 45 | // 删除采用标记删除, 并及时析构HttpData,以关闭描述符 46 | // 关闭定时器时应该把 httpDataMap 里的HttpData 一起erase 47 | http_data_.reset(); 48 | deleted_ = true; 49 | } 50 | 51 | void TimerManager::addTimer(std::shared_ptr httpData, size_t timeout) { 52 | Shared_TimerNode timerNode(new TimerNode(httpData, timeout)); 53 | { 54 | MutexLockGuard guard(lock_); 55 | timer_queue_.push(timerNode); 56 | // 将TimerNode和HttpData关联起来 57 | httpData->SetTimer(timerNode); 58 | } 59 | } 60 | 61 | void TimerManager::handle_expired_event() { 62 | MutexLockGuard guard(lock_); 63 | // 更新当前时间 64 | // std::cout << "开始处理超时事件" << std::endl; 65 | TimerNode::CurrentTime(); 66 | while (!timer_queue_.empty()) { 67 | Shared_TimerNode timerNode = timer_queue_.top(); 68 | if (timerNode->IsDeleted()) { 69 | // 删除节点 70 | timer_queue_.pop(); 71 | } else if (timerNode->isExpire()) { 72 | // 过期 删除 73 | timer_queue_.pop(); 74 | } else { 75 | break; 76 | } 77 | } 78 | } 79 | 80 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/util/ini_file.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 4 | * Author: xiaobei (https://github.com/imarvinle) 5 | * Brief: INI 格式的配置文件解析器 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | #include "../../include/ini_file.h" 12 | 13 | namespace csguide_webserver { 14 | 15 | bool INIFile::Load(const std::string& file_path) { 16 | std::ifstream ifs(file_path); 17 | if (!ifs.is_open()) { 18 | return false; 19 | } 20 | 21 | INISection section; 22 | std::string line; 23 | while (std::getline(ifs, line)) { 24 | if (section.Parse(line)) { 25 | continue; 26 | } else { 27 | // 解析完一个 Section,新构造一个 28 | AddSection(section); 29 | section = INISection(); 30 | section.Parse(line); 31 | } 32 | } 33 | // 最后这个 Section 要加入 34 | AddSection(section); 35 | return true; 36 | } 37 | 38 | bool INIFile::Save(const std::string& file_path) const { 39 | std::ofstream ofs(file_path); 40 | if (!ofs.is_open()) { 41 | return false; 42 | } 43 | 44 | for (const auto& section : sections_) { 45 | ofs << section << '\n'; 46 | } 47 | 48 | return true; 49 | } 50 | 51 | const INISection* INIFile::GetSection(const std::string& name) const { 52 | for (const auto& section : sections_) { 53 | if (section.GetName() == name) { 54 | return §ion; 55 | } else { 56 | std::cout << "sectionname: " << section.GetName() << std::endl; 57 | } 58 | } 59 | return nullptr; 60 | } 61 | 62 | void INIFile::AddSection(const INISection& section) { sections_.push_back(section); } 63 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/util/ini_section.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 4 | * Author: xiaobei (https://github.com/imarvinle) 5 | * Brief: INI 格式的配置文件解析器 6 | */ 7 | 8 | #include "../../include/ini_section.h" 9 | #include "../../include/logger.h" 10 | #include "../../include/util.h" 11 | 12 | namespace csguide_webserver { 13 | 14 | bool INISection::ParseKV(const std::string& line) { 15 | auto equal_pos = line.find('='); 16 | if (equal_pos == std::string::npos) { 17 | return false; 18 | } 19 | 20 | std::string key = line.substr(0, equal_pos); 21 | std::string value = line.substr(equal_pos + 1); 22 | 23 | // 去除首尾空白字符 24 | Trim(key); 25 | Trim(value); 26 | Logger::GetInstance().LogRun("get key value, section=%s, key=%s, value=%s", name_.c_str(), key.c_str(), 27 | value.c_str()); 28 | SetValue(key, value); 29 | return true; 30 | } 31 | 32 | bool INISection::Parse(const std::string& input_line) { 33 | std::string line = input_line; 34 | 35 | // 去除行首和行尾空格 36 | Trim(line); 37 | 38 | // 空行或者 # 注释行 跳过 39 | if (line.empty() || line[0] == '#') { 40 | Logger::GetInstance().LogRun("empty line: %s", line.c_str()); 41 | return true; 42 | } 43 | 44 | // 首次读到起始行 类似:[Worker], 取出其中的 KEY 45 | if (line[0] == '[' && !section_start_) { 46 | // 如果不是 ] 结尾,则报错 47 | if (line[line.size() - 1] != ']') { 48 | Logger::GetInstance().LogErr("section not end with ], line: %s", line.c_str()); 49 | // 继续读下一行 50 | return true; 51 | } 52 | 53 | // 提取这一节的 Section Name 54 | name_ = ExtractSubstring(line, '[', ']'); 55 | section_start_ = true; 56 | return true; 57 | } 58 | 59 | // 非首次读到 [ 开头,说明是下一个 Section开始了,直接返回 60 | if (line[0] == '[') { 61 | Logger::GetInstance().LogRun("[%s] section end, this line is next section, line: %s", name_.c_str(), line.c_str()); 62 | return false; 63 | } 64 | 65 | // 正常情况解析这一行的 key和 value 66 | ParseKV(line); 67 | return true; 68 | } 69 | 70 | std::istream& operator>>(std::istream& is, INISection& section) { 71 | std::string line; 72 | while (std::getline(is, line)) { 73 | // 去除行首和行尾空格 74 | } 75 | 76 | return is; 77 | } 78 | 79 | std::ostream& operator<<(std::ostream& os, const INISection& section) { 80 | os << '[' << section.GetName() << "]\n"; 81 | for (const auto& kv : section.key_value_pairs_) { 82 | os << kv.first << '=' << kv.second << '\n'; 83 | } 84 | return os; 85 | } 86 | 87 | const std::string& INISection::GetValue(const std::string& key) const { 88 | auto it = key_value_pairs_.find(key); 89 | if (it == key_value_pairs_.end()) { 90 | static const std::string empty; 91 | return empty; 92 | } 93 | 94 | return it->second; 95 | } 96 | 97 | void INISection::SetValue(const std::string& key, const std::string& value) { key_value_pairs_[key] = value; } 98 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/util/logger.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | * Brief: 简单的日志类 5 | */ 6 | 7 | #include "../../include/logger.h" 8 | 9 | namespace csguide_webserver { 10 | 11 | Logger::Logger() : use_file_(false) {} 12 | 13 | Logger::~Logger() { 14 | if (use_file_) { 15 | log_file_.close(); 16 | } 17 | } 18 | 19 | void Logger::SetLogFile(const std::string& log_file_path) { 20 | log_file_.open(log_file_path, std::ofstream::out | std::ofstream::app); 21 | use_file_ = log_file_.is_open(); 22 | if (!use_file_) { 23 | std::cerr << "Failed to open log file: " << log_file_path << std::endl; 24 | } 25 | } 26 | 27 | const char* Logger::LogLevelToString(LogLevel level) { 28 | switch (level) { 29 | case LogLevel::RUN: 30 | return "RUN"; 31 | case LogLevel::ERROR: 32 | return "ERROR"; 33 | case LogLevel::DEBUG: 34 | return "DEBUG"; 35 | default: 36 | break; 37 | } 38 | return ""; 39 | } 40 | 41 | 42 | std::string Logger::FormatMessage(const std::string& fmt_str, ...) { 43 | va_list args; 44 | 45 | va_start(args, fmt_str); 46 | int buffer_size = std::vsnprintf(NULL, 0, fmt_str.c_str(), args) + 1; 47 | va_end(args); 48 | 49 | // 使用new和delete 替换 std::make_unique 50 | char* buffer = new char[buffer_size]; 51 | 52 | va_start(args, fmt_str); 53 | std::vsnprintf(buffer, buffer_size, fmt_str.c_str(), args); 54 | va_end(args); 55 | 56 | std::string formatted_message(buffer, buffer + buffer_size - 1); 57 | 58 | delete[] buffer; 59 | 60 | return formatted_message; 61 | } 62 | 63 | 64 | 65 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/src/util/util.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #include "../../include/ini_file.h" 18 | #include "../../include/logger.h" 19 | #include "../../include/server.h" 20 | #include "../../include/util.h" 21 | 22 | namespace csguide_webserver { 23 | 24 | std::string &Ltrim(std::string &str) { 25 | if (str.empty()) { 26 | return str; 27 | } 28 | 29 | str.erase(0, str.find_first_not_of(" \t")); 30 | return str; 31 | } 32 | 33 | std::string &Rtrim(std::string &str) { 34 | if (str.empty()) { 35 | return str; 36 | } 37 | str.erase(str.find_last_not_of(" \t") + 1); 38 | return str; 39 | } 40 | 41 | std::string &Trim(std::string &str) { 42 | if (str.empty()) { 43 | return str; 44 | } 45 | 46 | Ltrim(str); 47 | Rtrim(str); 48 | return str; 49 | } 50 | 51 | int SetNonBlocking(int fd) { 52 | int old_option = fcntl(fd, F_GETFL); 53 | int new_option = old_option | O_NONBLOCK; 54 | fcntl(fd, F_SETFL, new_option); 55 | return old_option; 56 | } 57 | 58 | void HandleForSigPipe() { 59 | struct sigaction sa; 60 | memset(&sa, '\0', sizeof(sa)); 61 | sa.sa_handler = SIG_IGN; 62 | sa.sa_flags = 0; 63 | if (sigaction(SIGPIPE, &sa, NULL)) return; 64 | } 65 | 66 | int CheckBasePath(const std::string &base_path) { 67 | struct stat file; 68 | if (stat(base_path.c_str(), &file) == -1) { 69 | Logger::GetInstance().LogErr("path not exist: %s", base_path.c_str()); 70 | return -1; 71 | } 72 | // 不是目录 或者不可访问 73 | if (!S_ISDIR(file.st_mode) || access(base_path.c_str(), R_OK) == -1) { 74 | Logger::GetInstance().LogErr("path not directory or can't access: %s", base_path.c_str()); 75 | return -1; 76 | } 77 | return 0; 78 | } 79 | 80 | bool EndsWith(std::string const &str, std::string const &suffix) { 81 | if (str.length() < suffix.length()) { 82 | return false; 83 | } 84 | return str.rfind(suffix) == str.size() - suffix.size(); 85 | } 86 | 87 | int ParseConfig(const std::string config_file, ServerConf &server_conf) { 88 | INIFile ini_file; 89 | int ret = 0; 90 | 91 | if (ini_file.Load(config_file)) { 92 | const INISection *worker_section = ini_file.GetSection("Worker"); 93 | if (worker_section) { 94 | ret = StrToInt(worker_section->GetValue("thread_num"), *(&server_conf.thread_num)); 95 | if (0 != ret) { 96 | return ret; 97 | } 98 | ret = StrToInt(worker_section->GetValue("port"), *(&server_conf.port)); 99 | if (0 != ret) { 100 | return ret; 101 | } 102 | int daemon = 0; 103 | ret = StrToInt(worker_section->GetValue("daemon"), *(&daemon)); 104 | if (0 != ret) { 105 | return ret; 106 | } 107 | server_conf.daemon = (daemon == 1); 108 | } else { 109 | Logger::GetInstance().LogErr("Worker Section not found, configfile=%s", config_file.c_str()); 110 | return -1; 111 | } 112 | 113 | const INISection *server_section = ini_file.GetSection("Server"); 114 | if (server_section) { 115 | server_conf.root = server_section->GetValue("root"); 116 | } else { 117 | Logger::GetInstance().LogErr("Server Section not found, configfile=%s", config_file.c_str()); 118 | return -1; 119 | } 120 | } else { 121 | // 配置读取失败,返回失败 122 | Logger::GetInstance().LogErr("Failed to load configfile: %s", config_file.c_str()); 123 | return -1; 124 | } 125 | return 0; 126 | } 127 | 128 | int StrToInt(const std::string &str, int &result) { 129 | try { 130 | result = std::stoi(str); 131 | return 0; 132 | } catch (const std::invalid_argument &) { 133 | std::cerr << "非法的参数: " << str << '\n'; 134 | } catch (const std::out_of_range &) { 135 | std::cerr << "超出范围: " << str << '\n'; 136 | } catch (...) { 137 | std::cerr << "未知错误" << '\n'; 138 | } 139 | return -1; // 转换失败返回-1 140 | } 141 | 142 | std::string ExtractSubstring(const std::string &input, char start_char, char end_char) { 143 | size_t start = input.find(start_char); 144 | size_t end = input.rfind(end_char); 145 | 146 | if (start != std::string::npos && end != std::string::npos && end > start) { 147 | return input.substr(start + 1, end - start - 1); 148 | } else { 149 | return ""; // 返回空字符串,表示未找到子字符串 150 | } 151 | } 152 | 153 | } // namespace csguide_webserver -------------------------------------------------------------------------------- /version_0.3/test/test.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | 16 | int main() { 17 | // string s = "/helo/world/index?word=12"; 18 | // s.erase(s.rfind('?')); 19 | // string filetype; 20 | // if (s.rfind('.') != string::npos){ 21 | // filetype = s.substr(s.rfind('.')); 22 | // } 23 | // 24 | // 25 | // cout << s << endl; 26 | // if (filetype != "") { 27 | // cout << filetype << endl; 28 | // } else { 29 | // cout << " no file type" << endl; 30 | // } 31 | char *buffer; 32 | //也可以将buffer作为输出参数 33 | if ((buffer = getcwd(NULL, 0)) == NULL) { 34 | perror("getcwd error"); 35 | } else { 36 | printf("%s\n", buffer); 37 | free(buffer); 38 | } 39 | 40 | enum Code { ok = 201, notfound = 404 }; 41 | 42 | Code code = ok; 43 | printf("%d\n", code); 44 | } -------------------------------------------------------------------------------- /version_0.3/test/test_utils.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2019 CSGuide(https://csguide.cn) 3 | * Author: xiaobei (https://github.com/imarvinle) 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | #include "../include/Util.h" 10 | 11 | using namespace std; 12 | 13 | using namespace 14 | 15 | void test_ltrim() { 16 | std::string s = " \thelloworld\t "; 17 | util::ltrim(s); 18 | if (s == "helloworld\t ") { 19 | cout << "ltrim ok" << endl; 20 | } else { 21 | cout << "test ltrim faild" << endl; 22 | } 23 | } 24 | void test_rtrim() { 25 | std::string s = " \thelloworld\t "; 26 | util::rtrim(s); 27 | if (s == " \thelloworld") { 28 | cout << "rtrim ok" << endl; 29 | } else { 30 | cout << "test rtrim faild" << endl; 31 | } 32 | } 33 | 34 | void test_trim() { 35 | std::string s = " 1"; 36 | util::trim(s); 37 | if (s == "1") { 38 | cout << "trim ok" << endl; 39 | } else { 40 | cout << "test trim faild" << endl; 41 | } 42 | } 43 | 44 | int main() { 45 | test_ltrim(); 46 | test_rtrim(); 47 | test_trim(); 48 | } 49 | -------------------------------------------------------------------------------- /version_0.3/开发问题记录.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | * http://xxx.xxx/ 路径结束会发生段错误,检查HTTP parse过程 // 解决 4 | 5 | * 有空添加 favicon.ico 6 | 7 | * 会有connection close by peer 错误,还未fix -------------------------------------------------------------------------------- /性能测试分析.md: -------------------------------------------------------------------------------- 1 | # 性能测试分析 2 | 3 | ## 测试机环境 4 | 5 | * OS: Unbuntu 18.04 (虚拟机,宿主机为Win10) 6 | 7 | * 宿主机硬件: 8 | 1. CPU: i5-6500T 9 | 2. 内存: 8GB 10 | 11 | * 虚拟机分配资源 12 | 1. CPU资源: 4核 13 | 2. 内存: 4GB 14 | 15 | 16 | ## 测试工具 17 | 18 | * [webbench](https://github.com/EZLippi/WebBench) 19 | 20 | 21 | ## 测试用例 22 | 23 | 24 | 25 | 26 | ### case-01 27 | 28 | * 关闭系统所有调试信息以及输出,**4** 个工作线程并以守护进程运行(./webserver -d -t 4 -p 8080) 29 | 30 | 31 | * 页面大小: **575** bytes/page 32 | 33 | * wenbench设置: **1000**客户端、连接60s、短连接 34 | 35 | * 空闲时线程CPU占用情况: 36 | 37 | ![](https://ws2.sinaimg.cn/large/006tKfTcgy1g10x31osjvj31bq0huh41.jpg) 38 | 39 | **测试结果:** 40 | 41 | QPS: 37665 42 | 传输速度: 24.5 MB/S 43 | 44 | 45 | * 测试结果: 46 | 47 | ![4thread_1000client_60s](https://ws2.sinaimg.cn/large/006tKfTcgy1g0oopho0lqj30w60eaq4c.jpg) 48 | 49 | * 测试时线程CPU占用: 50 | 51 | ![](https://ws4.sinaimg.cn/large/006tKfTcgy1g10x457kyqj31ca0f6qm9.jpg) 52 | 53 | 54 | 55 | ### case-02 56 | 57 | * 关闭系统所有调试信息以及输出,**8** 个工作线程并以守护进程运行(./webserver -d -t 8 -p 8080) 58 | 59 | 60 | * 页面大小: **575** bytes/page 61 | 62 | * wenbench设置: **1000**客户端、连接60s、短连接 63 | 64 | * 空闲时8线程CPU占用情况: 65 | ![](https://ws4.sinaimg.cn/large/006tKfTcgy1g10x6fa5ptj31d20jmqs1.jpg) 66 | 67 | **测试结果:** 68 | 69 | QPS: 34263 70 | 传输速度: 22.5 MB/S 71 | 72 | * 测试结果: 73 | 74 | ![8thread_1000client_60s](https://ws2.sinaimg.cn/large/006tKfTcgy1g0op8am8isj30ww0eiq4c.jpg) 75 | 76 | * 测试时线程CPU占用: 77 | 78 | ![](https://ws1.sinaimg.cn/large/006tKfTcgy1g10x89u7ssj31f20kk1kx.jpg) 79 | 80 | 81 | ## 分析 82 | 83 | * 我的给虚拟机配置的是四个核心,所以其实从结果可以看出开8个线程的反而比开四个线程的QPS略低,应该是线程之间切换开销增大造成的, 84 | 而四个线程正好匹配核心,性能达到最高。并且可以看到8线程CPU占用截图,其实同一时刻只有一半的线程处于运行状态(R),其它处于S(sleep), 85 | 所以线程个数的选择应该是与CPU核心相关的。 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /整体设计.md: -------------------------------------------------------------------------------- 1 | # 并发模型 2 | 3 | 程序使用Reactor模型,主线程使用epoll作为IO多路复用的实现方式,只负责监听文件描述符上是否有事件发生,有的话就将对应的文件描述符交给工作线程来处理, 4 | 工作线程是在程序开始时便创建的固定数量线程池,避免了频繁创建线程带来的开销。 5 | 6 | 7 | ## 项目采用的Reactor模型 8 | 9 | ![并发模型](https://ws4.sinaimg.cn/large/006tKfTcgy1g10f7fac2wj31560g044n.jpg) 10 | 11 | 在项目中有一个主线程和四个工作线程,主线程将任务添加到线程池,任务即就绪待处理的文件描述符,epoll使用EPOLLONESHOT保证一个socket连接在任意时刻都只被一个线程处理 12 | 13 | 14 | 15 | 16 | ## epoll工作模式的选择 17 | 18 | epoll的触发模式选择了ET模式,ET模式要比高效很多,不会被同一事件触发多次,每次读都必须循环读取直到EAGIN错误,确保处理完。 19 | 20 | --------------------------------------------------------------------------------