├── .gitignore ├── .gitmodules ├── .travis.yml ├── Changes ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── ext └── rhebok │ ├── extconf.rb │ └── rhebok.c ├── lib ├── rack │ └── handler │ │ └── rhebok.rb ├── rhebok.rb └── rhebok │ ├── buffered.rb │ ├── config.rb │ └── version.rb ├── rhebok.gemspec └── test ├── spec_01_basic.rb ├── spec_02_server.rb ├── spec_03_unix.rb ├── spec_04_hook.rb ├── spec_05_config.rb ├── spec_06_curl.rb ├── testconfig.rb └── testrequest.rb /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /Gemfile.lock 4 | /_yardoc/ 5 | /coverage/ 6 | /doc/ 7 | /pkg/ 8 | /spec/reports/ 9 | /tmp/ 10 | *.bundle 11 | *.so 12 | *.o 13 | *.a 14 | mkmf.log 15 | *~ 16 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ext/rhebok/picohttpparser"] 2 | path = ext/rhebok/picohttpparser 3 | url = https://github.com/h2o/picohttpparser.git 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | install: 3 | - git submodule update --init --recursive 4 | - gem install bacon 5 | - gem install bundler 6 | - bundle install --jobs=3 --retry=3 7 | rvm: 8 | - 2.2.3 9 | - 2.3.1 10 | -------------------------------------------------------------------------------- /Changes: -------------------------------------------------------------------------------- 1 | 0.9.3 2016-09-13T11:05:00 2 | 3 | - bugfix about timeout by wrong Operator Precedence #7 4 | - Optimize by avoiding function call #8 5 | - fix rack deps 6 | 7 | 0.9.2 2015-12-24T00:31:23 8 | 9 | - optimize a bit 10 | 11 | 0.9.1 2015-12-07T10:37:51 12 | 13 | - disable chunked transfer by default 14 | 15 | 0.9.0 2015-11-13T23:44:13 16 | 17 | - safe graceful shutdown 18 | - fix iovcnt calculation 19 | 20 | 0.8.6 2015-01-26T14:53:06Z 21 | 22 | - add some chunked transfer test. refactor around sending chunk 23 | 24 | 0.8.5 2015-01-26T02:23:08Z 25 | 26 | - fix bug. send 0byte mark when using a non raw Array body 27 | 28 | 0.8.3 2015-01-23T00:33:02Z 29 | 30 | - change default backlog to SOMAXCONN 31 | 32 | 0.8.2 2015-01-22T19:42:49Z 33 | 34 | - tune around Expect 35 | 36 | 0.8.1 2015-01-22T16:42:28Z 37 | 38 | - stringfy body and header values 39 | - check 0 byte body 40 | 41 | 0.8.0 2015-01-22T10:18:30Z 42 | 43 | - support HTTP/1.1 44 | 45 | 0.2.3 2015-01-08T11:21:01Z 46 | 47 | - check ENV["SERVER_STARTER_PORT"] has "=" 48 | 49 | 0.2.2 2015-01-07T22:41:52Z 50 | 51 | - support SO_REUSEPORT 52 | 53 | 0.2.1 2014-12-27T01:26:47Z 54 | 55 | - fix segfault. header includes "\n" 56 | 57 | 0.2.0 2014-12-26T11:40:23Z 58 | 59 | - support ConfigFile 60 | - changed default MaxWorkers to 5 61 | 62 | 0.1.2 2014-12-25T17:33:59Z 63 | 64 | - oops. status_code.to_i is required 65 | 66 | 0.1.1 2014-12-25T17:19:31Z 67 | 68 | - added close for body 69 | 70 | 0.1.0 2014-12-25T16:23:00Z 71 | 72 | - remove specific rack version 73 | 74 | 0.0.8 2014-12-25T15:23:41Z 75 | 76 | - tweek Header order 77 | - require ruby >= 2.0 78 | 79 | 0.0.7 2014-12-24T16:25:22Z 80 | 81 | - support unix domain socket directly 82 | 83 | 0.0.6 2014-12-24T13:19:50Z 84 | 85 | - support OobGC 86 | 87 | 0.0.5 2014-12-19T11:06:28Z 88 | 89 | - support MaxRequestPerChild=0. worker never exit. 90 | - refactor around res header 91 | 92 | 0.0.4 2014-12-19-T01:50:11Z 93 | 94 | - support multiple line header 95 | 96 | 0.0.3 2014-12-18T17:22:53Z 97 | 98 | - fixed segfault. iovec shortage 99 | 100 | 0.0.2 2014-12-18T12:50:11Z 101 | 102 | - fixed install issue 103 | 104 | 0.0.1 2014-12-18T12:15:52Z 105 | 106 | - first release 107 | 108 | 109 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Specify your gem's dependencies in rhebok.gemspec 4 | gemspec 5 | gem "rake-compiler" 6 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | This software is copyright (c) 2014 by Masahiro Nagano . 2 | 3 | This is free software; you can redistribute it and/or modify it under 4 | the same terms as the Perl 5 programming language system itself. 5 | 6 | Terms of the Perl programming language system itself 7 | 8 | a) the GNU General Public License as published by the Free 9 | Software Foundation; either version 1, or (at your option) any 10 | later version, or 11 | b) the "Artistic License" 12 | 13 | --- The GNU General Public License, Version 1, February 1989 --- 14 | 15 | This software is Copyright (c) 2014 by Masahiro Nagano . 16 | 17 | This is free software, licensed under: 18 | 19 | The GNU General Public License, Version 1, February 1989 20 | 21 | GNU GENERAL PUBLIC LICENSE 22 | Version 1, February 1989 23 | 24 | Copyright (C) 1989 Free Software Foundation, Inc. 25 | 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA 26 | 27 | Everyone is permitted to copy and distribute verbatim copies 28 | of this license document, but changing it is not allowed. 29 | 30 | Preamble 31 | 32 | The license agreements of most software companies try to keep users 33 | at the mercy of those companies. By contrast, our General Public 34 | License is intended to guarantee your freedom to share and change free 35 | software--to make sure the software is free for all its users. The 36 | General Public License applies to the Free Software Foundation's 37 | software and to any other program whose authors commit to using it. 38 | You can use it for your programs, too. 39 | 40 | When we speak of free software, we are referring to freedom, not 41 | price. Specifically, the General Public License is designed to make 42 | sure that you have the freedom to give away or sell copies of free 43 | software, that you receive source code or can get it if you want it, 44 | that you can change the software or use pieces of it in new free 45 | programs; and that you know you can do these things. 46 | 47 | To protect your rights, we need to make restrictions that forbid 48 | anyone to deny you these rights or to ask you to surrender the rights. 49 | These restrictions translate to certain responsibilities for you if you 50 | distribute copies of the software, or if you modify it. 51 | 52 | For example, if you distribute copies of a such a program, whether 53 | gratis or for a fee, you must give the recipients all the rights that 54 | you have. You must make sure that they, too, receive or can get the 55 | source code. And you must tell them their rights. 56 | 57 | We protect your rights with two steps: (1) copyright the software, and 58 | (2) offer you this license which gives you legal permission to copy, 59 | distribute and/or modify the software. 60 | 61 | Also, for each author's protection and ours, we want to make certain 62 | that everyone understands that there is no warranty for this free 63 | software. If the software is modified by someone else and passed on, we 64 | want its recipients to know that what they have is not the original, so 65 | that any problems introduced by others will not reflect on the original 66 | authors' reputations. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | GNU GENERAL PUBLIC LICENSE 72 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 73 | 74 | 0. This License Agreement applies to any program or other work which 75 | contains a notice placed by the copyright holder saying it may be 76 | distributed under the terms of this General Public License. The 77 | "Program", below, refers to any such program or work, and a "work based 78 | on the Program" means either the Program or any work containing the 79 | Program or a portion of it, either verbatim or with modifications. Each 80 | licensee is addressed as "you". 81 | 82 | 1. You may copy and distribute verbatim copies of the Program's source 83 | code as you receive it, in any medium, provided that you conspicuously and 84 | appropriately publish on each copy an appropriate copyright notice and 85 | disclaimer of warranty; keep intact all the notices that refer to this 86 | General Public License and to the absence of any warranty; and give any 87 | other recipients of the Program a copy of this General Public License 88 | along with the Program. You may charge a fee for the physical act of 89 | transferring a copy. 90 | 91 | 2. You may modify your copy or copies of the Program or any portion of 92 | it, and copy and distribute such modifications under the terms of Paragraph 93 | 1 above, provided that you also do the following: 94 | 95 | a) cause the modified files to carry prominent notices stating that 96 | you changed the files and the date of any change; and 97 | 98 | b) cause the whole of any work that you distribute or publish, that 99 | in whole or in part contains the Program or any part thereof, either 100 | with or without modifications, to be licensed at no charge to all 101 | third parties under the terms of this General Public License (except 102 | that you may choose to grant warranty protection to some or all 103 | third parties, at your option). 104 | 105 | c) If the modified program normally reads commands interactively when 106 | run, you must cause it, when started running for such interactive use 107 | in the simplest and most usual way, to print or display an 108 | announcement including an appropriate copyright notice and a notice 109 | that there is no warranty (or else, saying that you provide a 110 | warranty) and that users may redistribute the program under these 111 | conditions, and telling the user how to view a copy of this General 112 | Public License. 113 | 114 | d) You may charge a fee for the physical act of transferring a 115 | copy, and you may at your option offer warranty protection in 116 | exchange for a fee. 117 | 118 | Mere aggregation of another independent work with the Program (or its 119 | derivative) on a volume of a storage or distribution medium does not bring 120 | the other work under the scope of these terms. 121 | 122 | 3. You may copy and distribute the Program (or a portion or derivative of 123 | it, under Paragraph 2) in object code or executable form under the terms of 124 | Paragraphs 1 and 2 above provided that you also do one of the following: 125 | 126 | a) accompany it with the complete corresponding machine-readable 127 | source code, which must be distributed under the terms of 128 | Paragraphs 1 and 2 above; or, 129 | 130 | b) accompany it with a written offer, valid for at least three 131 | years, to give any third party free (except for a nominal charge 132 | for the cost of distribution) a complete machine-readable copy of the 133 | corresponding source code, to be distributed under the terms of 134 | Paragraphs 1 and 2 above; or, 135 | 136 | c) accompany it with the information you received as to where the 137 | corresponding source code may be obtained. (This alternative is 138 | allowed only for noncommercial distribution and only if you 139 | received the program in object code or executable form alone.) 140 | 141 | Source code for a work means the preferred form of the work for making 142 | modifications to it. For an executable file, complete source code means 143 | all the source code for all modules it contains; but, as a special 144 | exception, it need not include source code for modules which are standard 145 | libraries that accompany the operating system on which the executable 146 | file runs, or for standard header files or definitions files that 147 | accompany that operating system. 148 | 149 | 4. You may not copy, modify, sublicense, distribute or transfer the 150 | Program except as expressly provided under this General Public License. 151 | Any attempt otherwise to copy, modify, sublicense, distribute or transfer 152 | the Program is void, and will automatically terminate your rights to use 153 | the Program under this License. However, parties who have received 154 | copies, or rights to use copies, from you under this General Public 155 | License will not have their licenses terminated so long as such parties 156 | remain in full compliance. 157 | 158 | 5. By copying, distributing or modifying the Program (or any work based 159 | on the Program) you indicate your acceptance of this license to do so, 160 | and all its terms and conditions. 161 | 162 | 6. Each time you redistribute the Program (or any work based on the 163 | Program), the recipient automatically receives a license from the original 164 | licensor to copy, distribute or modify the Program subject to these 165 | terms and conditions. You may not impose any further restrictions on the 166 | recipients' exercise of the rights granted herein. 167 | 168 | 7. The Free Software Foundation may publish revised and/or new versions 169 | of the General Public License from time to time. Such new versions will 170 | be similar in spirit to the present version, but may differ in detail to 171 | address new problems or concerns. 172 | 173 | Each version is given a distinguishing version number. If the Program 174 | specifies a version number of the license which applies to it and "any 175 | later version", you have the option of following the terms and conditions 176 | either of that version or of any later version published by the Free 177 | Software Foundation. If the Program does not specify a version number of 178 | the license, you may choose any version ever published by the Free Software 179 | Foundation. 180 | 181 | 8. If you wish to incorporate parts of the Program into other free 182 | programs whose distribution conditions are different, write to the author 183 | to ask for permission. For software which is copyrighted by the Free 184 | Software Foundation, write to the Free Software Foundation; we sometimes 185 | make exceptions for this. Our decision will be guided by the two goals 186 | of preserving the free status of all derivatives of our free software and 187 | of promoting the sharing and reuse of software generally. 188 | 189 | NO WARRANTY 190 | 191 | 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 192 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 193 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 194 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 195 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 196 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 197 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 198 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 199 | REPAIR OR CORRECTION. 200 | 201 | 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 202 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 203 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 204 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 205 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 206 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 207 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 208 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 209 | POSSIBILITY OF SUCH DAMAGES. 210 | 211 | END OF TERMS AND CONDITIONS 212 | 213 | Appendix: How to Apply These Terms to Your New Programs 214 | 215 | If you develop a new program, and you want it to be of the greatest 216 | possible use to humanity, the best way to achieve this is to make it 217 | free software which everyone can redistribute and change under these 218 | terms. 219 | 220 | To do so, attach the following notices to the program. It is safest to 221 | attach them to the start of each source file to most effectively convey 222 | the exclusion of warranty; and each file should have at least the 223 | "copyright" line and a pointer to where the full notice is found. 224 | 225 | 226 | Copyright (C) 19yy 227 | 228 | This program is free software; you can redistribute it and/or modify 229 | it under the terms of the GNU General Public License as published by 230 | the Free Software Foundation; either version 1, or (at your option) 231 | any later version. 232 | 233 | This program is distributed in the hope that it will be useful, 234 | but WITHOUT ANY WARRANTY; without even the implied warranty of 235 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 236 | GNU General Public License for more details. 237 | 238 | You should have received a copy of the GNU General Public License 239 | along with this program; if not, write to the Free Software 240 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA 241 | 242 | 243 | Also add information on how to contact you by electronic and paper mail. 244 | 245 | If the program is interactive, make it output a short notice like this 246 | when it starts in an interactive mode: 247 | 248 | Gnomovision version 69, Copyright (C) 19xx name of author 249 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 250 | This is free software, and you are welcome to redistribute it 251 | under certain conditions; type `show c' for details. 252 | 253 | The hypothetical commands `show w' and `show c' should show the 254 | appropriate parts of the General Public License. Of course, the 255 | commands you use may be called something other than `show w' and `show 256 | c'; they could even be mouse-clicks or menu items--whatever suits your 257 | program. 258 | 259 | You should also get your employer (if you work as a programmer) or your 260 | school, if any, to sign a "copyright disclaimer" for the program, if 261 | necessary. Here a sample; alter the names: 262 | 263 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 264 | program `Gnomovision' (a program to direct compilers to make passes 265 | at assemblers) written by James Hacker. 266 | 267 | , 1 April 1989 268 | Ty Coon, President of Vice 269 | 270 | That's all there is to it! 271 | 272 | 273 | --- The Artistic License 1.0 --- 274 | 275 | This software is Copyright (c) 2014 by Masahiro Nagano . 276 | 277 | This is free software, licensed under: 278 | 279 | The Artistic License 1.0 280 | 281 | The Artistic License 282 | 283 | Preamble 284 | 285 | The intent of this document is to state the conditions under which a Package 286 | may be copied, such that the Copyright Holder maintains some semblance of 287 | artistic control over the development of the package, while giving the users of 288 | the package the right to use and distribute the Package in a more-or-less 289 | customary fashion, plus the right to make reasonable modifications. 290 | 291 | Definitions: 292 | 293 | - "Package" refers to the collection of files distributed by the Copyright 294 | Holder, and derivatives of that collection of files created through 295 | textual modification. 296 | - "Standard Version" refers to such a Package if it has not been modified, 297 | or has been modified in accordance with the wishes of the Copyright 298 | Holder. 299 | - "Copyright Holder" is whoever is named in the copyright or copyrights for 300 | the package. 301 | - "You" is you, if you're thinking about copying or distributing this Package. 302 | - "Reasonable copying fee" is whatever you can justify on the basis of media 303 | cost, duplication charges, time of people involved, and so on. (You will 304 | not be required to justify it to the Copyright Holder, but only to the 305 | computing community at large as a market that must bear the fee.) 306 | - "Freely Available" means that no fee is charged for the item itself, though 307 | there may be fees involved in handling the item. It also means that 308 | recipients of the item may redistribute it under the same conditions they 309 | received it. 310 | 311 | 1. You may make and give away verbatim copies of the source form of the 312 | Standard Version of this Package without restriction, provided that you 313 | duplicate all of the original copyright notices and associated disclaimers. 314 | 315 | 2. You may apply bug fixes, portability fixes and other modifications derived 316 | from the Public Domain or from the Copyright Holder. A Package modified in such 317 | a way shall still be considered the Standard Version. 318 | 319 | 3. You may otherwise modify your copy of this Package in any way, provided that 320 | you insert a prominent notice in each changed file stating how and when you 321 | changed that file, and provided that you do at least ONE of the following: 322 | 323 | a) place your modifications in the Public Domain or otherwise make them 324 | Freely Available, such as by posting said modifications to Usenet or an 325 | equivalent medium, or placing the modifications on a major archive site 326 | such as ftp.uu.net, or by allowing the Copyright Holder to include your 327 | modifications in the Standard Version of the Package. 328 | 329 | b) use the modified Package only within your corporation or organization. 330 | 331 | c) rename any non-standard executables so the names do not conflict with 332 | standard executables, which must also be provided, and provide a separate 333 | manual page for each non-standard executable that clearly documents how it 334 | differs from the Standard Version. 335 | 336 | d) make other distribution arrangements with the Copyright Holder. 337 | 338 | 4. You may distribute the programs of this Package in object code or executable 339 | form, provided that you do at least ONE of the following: 340 | 341 | a) distribute a Standard Version of the executables and library files, 342 | together with instructions (in the manual page or equivalent) on where to 343 | get the Standard Version. 344 | 345 | b) accompany the distribution with the machine-readable source of the Package 346 | with your modifications. 347 | 348 | c) accompany any non-standard executables with their corresponding Standard 349 | Version executables, giving the non-standard executables non-standard 350 | names, and clearly documenting the differences in manual pages (or 351 | equivalent), together with instructions on where to get the Standard 352 | Version. 353 | 354 | d) make other distribution arrangements with the Copyright Holder. 355 | 356 | 5. You may charge a reasonable copying fee for any distribution of this 357 | Package. You may charge any fee you choose for support of this Package. You 358 | may not charge a fee for this Package itself. However, you may distribute this 359 | Package in aggregate with other (possibly commercial) programs as part of a 360 | larger (possibly commercial) software distribution provided that you do not 361 | advertise this Package as a product of your own. 362 | 363 | 6. The scripts and library files supplied as input to or produced as output 364 | from the programs of this Package do not automatically fall under the copyright 365 | of this Package, but belong to whomever generated them, and may be sold 366 | commercially, and may be aggregated with this Package. 367 | 368 | 7. C or perl subroutines supplied by you and linked into this Package shall not 369 | be considered part of this Package. 370 | 371 | 8. The name of the Copyright Holder may not be used to endorse or promote 372 | products derived from this software without specific prior written permission. 373 | 374 | 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED 375 | WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF 376 | MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. 377 | 378 | The End 379 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rhebok 2 | 3 | ![rhebok logo](https://s3-ap-northeast-1.amazonaws.com/softwarearchives/rhebookfix-350.png) 4 | 5 | 6 | [![Build Status](https://travis-ci.org/kazeburo/rhebok.svg?branch=master)](https://travis-ci.org/kazeburo/rhebok) 7 | 8 | Rhebok is High Performance Rack Handler/Web Server. 2x performance when compared against Unicorn. 9 | 10 | Rhebok supports following features. 11 | 12 | - ultra fast HTTP processing using [picohttpparser](https://github.com/h2o/picohttpparser) 13 | - uses accept4(2) if OS support 14 | - uses writev(2) for output responses 15 | - prefork and graceful shutdown using [prefork_engine](https://rubygems.org/gems/prefork_engine) 16 | - hot deploy using [start_server](https://metacpan.org/release/Server-Starter) ([here](https://github.com/lestrrat/go-server-starter) is golang version by lestrrat-san) 17 | - supports HTTP/1.1 except for KeepAlive 18 | - supports OobGC 19 | 20 | This server is suitable for running HTTP application servers behind a reverse proxy like nginx. 21 | 22 | ## Installation 23 | 24 | Add this line to your application's Gemfile: 25 | 26 | ``` 27 | gem 'rhebok' 28 | ``` 29 | 30 | And then execute: 31 | 32 | $ bundle 33 | 34 | Or install it yourself as: 35 | 36 | $ gem install rhebok 37 | 38 | ## Usage 39 | 40 | $ rackup -s Rhebok --port 8080 -O MaxWorkers=5 -O MaxRequestPerChild=1000 -O OobGC=yes -E production config.ru 41 | 42 | ## Sample configuration with Nginx 43 | 44 | nginx.conf 45 | 46 | http { 47 | upstream app { 48 | server unix:/path/to/app.sock; 49 | } 50 | server { 51 | location / { 52 | proxy_pass http://app; 53 | } 54 | location ~ ^/(stylesheets|images)/ { 55 | root /path/to/webapp/public; 56 | } 57 | } 58 | } 59 | 60 | command line of running Rhebok 61 | 62 | $ rackup -s Rhebok -O Path=/path/to/app.sock \ 63 | -O MaxWorkers=5 -O MaxRequestPerChild=1000 -E production config.ru 64 | 65 | ## Options 66 | 67 | ### ConfigFile 68 | 69 | filename to load options. For details, please read `Config File` section 70 | 71 | ### Host 72 | 73 | hostname or ip address to bind (default: 0.0.0.0) 74 | 75 | ### Port 76 | 77 | port to bind (default: 9292) 78 | 79 | ### Path 80 | 81 | path to listen using unix socket 82 | 83 | ### BackLog 84 | 85 | specifies a listen backlog parameter (default: Socket::SOMAXCONN. usually 128 on Linux ) 86 | 87 | ### ReusePort 88 | 89 | enable SO_REUSEPORT for TCP socket 90 | 91 | ### MaxWorkers 92 | 93 | number of worker processes (default: 5) 94 | 95 | ### MaxRequestPerChild 96 | 97 | Max number of requests to be handled before a worker process exits (default: 1000) 98 | If set to `0`. worker never exists. This option looks like Apache's MaxRequestPerChild 99 | 100 | ### MinRequestPerChild 101 | 102 | if set, randomizes the number of requests handled by a single worker process between the value and that supplied by MaxRequestPerChlid (default: none) 103 | 104 | ### Timeout 105 | 106 | seconds until timeout (default: 300) 107 | 108 | ### OobGC 109 | 110 | Boolean like string. If true, Rhebok execute GC after close client socket. (defualt: false) 111 | 112 | ### MaxGCPerRequest 113 | 114 | If [gctools](https://github.com/tmm1/gctools) is available, this option is not used. invoke GC by `GC::OOB.run` after every requests. 115 | 116 | Max number of request before invoking GC (defualt: 5) 117 | 118 | ### MinGCPerRequest 119 | 120 | If set, randomizes the number of request before invoking GC between the number of MaxGCPerRequest (defualt: none) 121 | 122 | ### Chunked_Transfer 123 | 124 | If set, use chunked transfer for response (default: false) 125 | 126 | ### SpawnInterval 127 | 128 | if set, worker processes will not be spawned more than once than every given seconds. Also, when SIGUSR1 is being received, no more than one worker processes will be collected every given seconds. This feature is useful for doing a "slow-restart". See http://blog.kazuhooku.com/2011/04/web-serverstarter-parallelprefork.html for more information. (default: none) 129 | 130 | ## Config File 131 | 132 | load options from specified config file. If same options are exists in command line and the config file, options written in the config file will take precedence. 133 | 134 | ``` 135 | $ cat rhebok_config.rb 136 | host '127.0.0.1' 137 | port 9292 138 | max_workers ENV["WEB_CONCURRENCY"] || 3 139 | before_fork { 140 | defined?(ActiveRecord::Base) and 141 | ActiveRecord::Base.connection.disconnect! 142 | } 143 | after_fork { 144 | defined?(ActiveRecord::Base) and 145 | ActiveRecord::Base.establish_connection 146 | } 147 | $ rackup -s Rhebok -O ConfigFile=rhebok_config.rb -O port 8080 -O OobGC -E production 148 | Rhebok starts Listening on 127.0.0.1:9292 Pid:11892 149 | ``` 150 | 151 | Supported options in config file are below. 152 | 153 | ### host 154 | 155 | ### port 156 | 157 | ### path 158 | 159 | ### backlog 160 | 161 | ### reuseport 162 | 163 | ### max_workers 164 | 165 | ### timeout 166 | 167 | ### max_request_per_child 168 | 169 | ### min_request_per_child 170 | 171 | ### oobgc 172 | 173 | ### max_gc_per_request 174 | 175 | ### min_gc_per_request 176 | 177 | ### chunked_transfer 178 | 179 | ### spawn_interval 180 | 181 | ### before_fork 182 | 183 | proc object. This block will be called by a master process before forking each worker 184 | 185 | ### after_fork 186 | 187 | proc object. This block will be called by a worker process after forking 188 | 189 | ## Signal Handling 190 | 191 | ### Master process 192 | 193 | - TERM, HUP: If the master process received TERM or HUP signal, Rhebok will shutdown gracefully 194 | - USR1: If set SpawnInterval, Rhebok will collect workers every given seconds and exit 195 | 196 | ### worker process 197 | 198 | - TERM: If the worker process received TERM, exit after finishing current request 199 | 200 | 201 | ## Benchmark 202 | 203 | Rhebok and Unicorn "Hello World" Benchmark (behind nginx reverse proxy) 204 | 205 | ![image](https://s3-ap-northeast-1.amazonaws.com/softwarearchives/rhebok_unicorn_bench.png) 206 | 207 | *"nginx static file" represents req/sec when delivering 13 bytes static files from nginx* 208 | 209 | Application code is [here](https://github.com/kazeburo/rhebok_bench_app). 210 | 211 | ruby version 212 | 213 | $ ruby -v 214 | ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux] 215 | 216 | nginx.conf 217 | 218 | worker_processes 16; 219 | 220 | events { 221 | worker_connections 50000; 222 | } 223 | 224 | http { 225 | include mime.types; 226 | access_log off; 227 | sendfile on; 228 | tcp_nopush on; 229 | tcp_nodelay on; 230 | etag off; 231 | upstream app { 232 | server unix:/dev/shm/app.sock; 233 | } 234 | server { 235 | location / { 236 | proxy_pass http://app; 237 | } 238 | } 239 | } 240 | 241 | ### Rhebok 242 | 243 | command to run 244 | 245 | $ start_server --backlog=16384 --path /dev/shm/app.sock -- \ 246 | bundle exec --keep-file-descriptors rackup -s Rhebok \ 247 | -O MaxWorkers=8 -O MaxRequestPerChild=0 -E production config.ru 248 | 249 | #### Hello World/Rack Application 250 | 251 | $ ./wrk -t 4 -c 500 -d 30 http://localhost/ 252 | Running 30s test @ http://localhost/ 253 | 4 threads and 500 connections 254 | Thread Stats Avg Stdev Max +/- Stdev 255 | Latency 1.74ms 661.27us 38.69ms 91.19% 256 | Req/Sec 72.69k 9.42k 114.33k 79.43% 257 | 8206118 requests in 30.00s, 1.34GB read 258 | Requests/sec: 273544.70 259 | Transfer/sec: 45.90MB 260 | 261 | #### Sinatra 262 | 263 | $ ./wrk -t 4 -c 500 -d 30 http://localhost/ 264 | Running 30s test @ http://localhost/ 265 | 4 threads and 500 connections 266 | Thread Stats Avg Stdev Max +/- Stdev 267 | Latency 16.39ms 418.08us 22.25ms 78.25% 268 | Req/Sec 7.73k 230.81 8.38k 70.81% 269 | 912104 requests in 30.00s, 273.09MB read 270 | Requests/sec: 30404.28 271 | Transfer/sec: 9.10MB 272 | 273 | #### Rails 274 | 275 | $ ./wrk -t 4 -c 500 -d 30 http://localhost/ 276 | Running 30s test @ http://localhost/ 277 | 4 threads and 500 connections 278 | Thread Stats Avg Stdev Max +/- Stdev 279 | Latency 101.13ms 2.57ms 139.04ms 96.88% 280 | Req/Sec 1.24k 27.11 1.29k 82.98% 281 | 148169 requests in 30.00s, 178.18MB read 282 | Requests/sec: 4938.93 283 | Transfer/sec: 5.94MB 284 | 285 | ### Unicorn 286 | 287 | unicorn.rb 288 | 289 | $ cat unicorn.rb 290 | worker_processes 8 291 | preload_app true 292 | listen "/dev/shm/app.sock" 293 | 294 | command to run 295 | 296 | $ bundle exec unicorn -c unicorn.rb -E production config.ru 297 | 298 | #### Hello World/Rack Application 299 | 300 | $ ./wrk -t 4 -c 500 -d 30 http://localhost/ 301 | Running 30s test @ http://localhost/ 302 | 4 threads and 500 connections 303 | Thread Stats Avg Stdev Max +/- Stdev 304 | Latency 3.50ms 518.60us 30.28ms 90.35% 305 | Req/Sec 37.99k 4.10k 56.56k 72.14% 306 | 4294095 requests in 30.00s, 786.07MB read 307 | Requests/sec: 143140.20 308 | Transfer/sec: 26.20MB 309 | 310 | #### Sinatra 311 | 312 | $ ./wrk -t 4 -c 500 -d 30 http://localhost/ 313 | Running 30s test @ http://localhost/ 314 | 4 threads and 500 connections 315 | Thread Stats Avg Stdev Max +/- Stdev 316 | Latency 19.31ms 1.09ms 65.92ms 89.94% 317 | Req/Sec 6.55k 312.92 7.24k 73.41% 318 | 775712 requests in 30.00s, 244.09MB read 319 | Requests/sec: 25857.85 320 | Transfer/sec: 8.14MB 321 | 322 | #### Rails 323 | 324 | $ ./wrk -t 4 -c 500 -d 30 http://localhost/ 325 | Running 30s test @ http://localhost/ 326 | 4 threads and 500 connections 327 | Thread Stats Avg Stdev Max +/- Stdev 328 | Latency 105.70ms 4.70ms 151.11ms 93.50% 329 | Req/Sec 1.19k 44.16 1.25k 89.13% 330 | 141846 requests in 30.00s, 172.74MB read 331 | Requests/sec: 4728.11 332 | Transfer/sec: 5.76MB 333 | 334 | ### Server Environment 335 | 336 | I used EC2 for benchmarking. Instance type if c3.8xlarge(32cores). A benchmark tool and web servers were executed at same hosts. Before benchmark, increase somaxconn and nfiles. 337 | 338 | ## See Also 339 | 340 | [Gazelle](https://metacpan.org/pod/Gazelle) Rhebok is created based on Gazelle code 341 | 342 | [Server::Stater](https://metacpan.org/pod/Server::Starter) a superdaemon for hot-deploying server programs 343 | 344 | [picohttpparser](https://github.com/h2o/picohttpparser) fast http parser 345 | 346 | ## LICENSE 347 | 348 | Copyright (C) Masahiro Nagano. 349 | 350 | This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. 351 | 352 | ## Contributing 353 | 354 | 1. Fork it ( https://github.com/kazeburo/rhebok/fork ) 355 | 2. Create your feature branch (`git checkout -b my-new-feature`) 356 | 3. Commit your changes (`git commit -am 'Add some feature'`) 357 | 4. Push to the branch (`git push origin my-new-feature`) 358 | 5. Create a new Pull Request 359 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rake/extensiontask" 3 | 4 | Rake::ExtensionTask.new "rhebok" do |ext| 5 | ext.lib_dir = "lib/rhebok" 6 | end 7 | 8 | task :bacon do 9 | opts = ENV['TEST'] || '-a' 10 | specopts = ENV['TESTOPTS'] || '-q' 11 | sh "bacon -I./lib:./test -w #{opts} #{specopts}" 12 | end 13 | 14 | task :test do 15 | Rake::Task["clobber"].invoke 16 | Rake::Task["compile"].invoke 17 | Rake::Task["bacon"].invoke 18 | end 19 | 20 | 21 | task :default => :test 22 | -------------------------------------------------------------------------------- /ext/rhebok/extconf.rb: -------------------------------------------------------------------------------- 1 | require "mkmf" 2 | create_makefile("rhebok/rhebok") 3 | -------------------------------------------------------------------------------- /ext/rhebok/rhebok.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #ifndef __need_IOV_MAX 6 | #define __need_IOV_MAX 7 | #endif 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include "picohttpparser/picohttpparser.c" 19 | 20 | #ifndef IOV_MAX 21 | #if defined(__FreeBSD__) || defined(__APPLE__) 22 | # define IOV_MAX 128 23 | #endif 24 | #endif 25 | 26 | #ifndef IOV_MAX 27 | # error "Unable to determine IOV_MAX from system headers" 28 | #endif 29 | 30 | #define MAX_HEADER_SIZE 16384 31 | #define MAX_HEADER_NAME_LEN 1024 32 | #define MAX_HEADERS 128 33 | #define BAD_REQUEST "HTTP/1.0 400 Bad Request\r\nConnection: close\r\n\r\n400 Bad Request\r\n" 34 | #define EXPECT_CONTINUE "HTTP/1.1 100 Continue\r\n\r\n" 35 | #define EXPECT_FAILED "HTTP/1.1 417 Expectation Failed\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nExpectation Failed\r\n" 36 | #define READ_BUF 16384 37 | #define TOU(ch) (('a' <= ch && ch <= 'z') ? ch - ('a' - 'A') : ch) 38 | #define RETURN_STATUS_MESSAGE(s, l) l = sizeof(s) - 1; return s; 39 | 40 | static const char *DoW[] = { 41 | "Sun","Mon","Tue","Wed","Thu","Fri","Sat" 42 | }; 43 | static const char *MoY[] = { 44 | "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" 45 | }; 46 | static const char xdigit[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 47 | 48 | 49 | /* stolen from HTTP::Status and Feersum */ 50 | /* Unmarked codes are from RFC 2616 */ 51 | /* See also: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes */ 52 | static const char * 53 | status_message (int code, size_t *mlen) { 54 | switch (code) { 55 | case 100: RETURN_STATUS_MESSAGE("Continue", *mlen); 56 | case 101: RETURN_STATUS_MESSAGE("Switching Protocols", *mlen); 57 | case 102: RETURN_STATUS_MESSAGE("Processing", *mlen); /* RFC 2518 (WebDAV) */ 58 | case 200: RETURN_STATUS_MESSAGE("OK", *mlen); 59 | case 201: RETURN_STATUS_MESSAGE("Created", *mlen); 60 | case 202: RETURN_STATUS_MESSAGE("Accepted", *mlen); 61 | case 203: RETURN_STATUS_MESSAGE("Non-Authoritative Information", *mlen); 62 | case 204: RETURN_STATUS_MESSAGE("No Content", *mlen); 63 | case 205: RETURN_STATUS_MESSAGE("Reset Content", *mlen); 64 | case 206: RETURN_STATUS_MESSAGE("Partial Content", *mlen); 65 | case 207: RETURN_STATUS_MESSAGE("Multi-Status", *mlen); /* RFC 2518 (WebDAV) */ 66 | case 208: RETURN_STATUS_MESSAGE("Already Reported", *mlen); /* RFC 5842 */ 67 | case 300: RETURN_STATUS_MESSAGE("Multiple Choices", *mlen); 68 | case 301: RETURN_STATUS_MESSAGE("Moved Permanently", *mlen); 69 | case 302: RETURN_STATUS_MESSAGE("Found", *mlen); 70 | case 303: RETURN_STATUS_MESSAGE("See Other", *mlen); 71 | case 304: RETURN_STATUS_MESSAGE("Not Modified", *mlen); 72 | case 305: RETURN_STATUS_MESSAGE("Use Proxy", *mlen); 73 | case 307: RETURN_STATUS_MESSAGE("Temporary Redirect", *mlen); 74 | case 400: RETURN_STATUS_MESSAGE("Bad Request", *mlen); 75 | case 401: RETURN_STATUS_MESSAGE("Unauthorized", *mlen); 76 | case 402: RETURN_STATUS_MESSAGE("Payment Required", *mlen); 77 | case 403: RETURN_STATUS_MESSAGE("Forbidden", *mlen); 78 | case 404: RETURN_STATUS_MESSAGE("Not Found", *mlen); 79 | case 405: RETURN_STATUS_MESSAGE("Method Not Allowed", *mlen); 80 | case 406: RETURN_STATUS_MESSAGE("Not Acceptable", *mlen); 81 | case 407: RETURN_STATUS_MESSAGE("Proxy Authentication Required", *mlen); 82 | case 408: RETURN_STATUS_MESSAGE("Request Timeout", *mlen); 83 | case 409: RETURN_STATUS_MESSAGE("Conflict", *mlen); 84 | case 410: RETURN_STATUS_MESSAGE("Gone", *mlen); 85 | case 411: RETURN_STATUS_MESSAGE("Length Required", *mlen); 86 | case 412: RETURN_STATUS_MESSAGE("Precondition Failed", *mlen); 87 | case 413: RETURN_STATUS_MESSAGE("Request Entity Too Large", *mlen); 88 | case 414: RETURN_STATUS_MESSAGE("Request-URI Too Large", *mlen); 89 | case 415: RETURN_STATUS_MESSAGE("Unsupported Media Type", *mlen); 90 | case 416: RETURN_STATUS_MESSAGE("Request Range Not Satisfiable", *mlen); 91 | case 417: RETURN_STATUS_MESSAGE("Expectation Failed", *mlen); 92 | case 418: RETURN_STATUS_MESSAGE("I'm a teapot", *mlen); /* RFC 2324 */ 93 | case 422: RETURN_STATUS_MESSAGE("Unprocessable Entity", *mlen); /* RFC 2518 (WebDAV) */ 94 | case 423: RETURN_STATUS_MESSAGE("Locked", *mlen); /* RFC 2518 (WebDAV) */ 95 | case 424: RETURN_STATUS_MESSAGE("Failed Dependency", *mlen); /* RFC 2518 (WebDAV) */ 96 | case 425: RETURN_STATUS_MESSAGE("No code", *mlen); /* WebDAV Advanced Collections */ 97 | case 426: RETURN_STATUS_MESSAGE("Upgrade Required", *mlen); /* RFC 2817 */ 98 | case 428: RETURN_STATUS_MESSAGE("Precondition Required", *mlen); 99 | case 429: RETURN_STATUS_MESSAGE("Too Many Requests", *mlen); 100 | case 431: RETURN_STATUS_MESSAGE("Request Header Fields Too Large", *mlen); 101 | case 449: RETURN_STATUS_MESSAGE("Retry with", *mlen); /* unofficial Microsoft */ 102 | case 500: RETURN_STATUS_MESSAGE("Internal Server Error", *mlen); 103 | case 501: RETURN_STATUS_MESSAGE("Not Implemented", *mlen); 104 | case 502: RETURN_STATUS_MESSAGE("Bad Gateway", *mlen); 105 | case 503: RETURN_STATUS_MESSAGE("Service Unavailable", *mlen); 106 | case 504: RETURN_STATUS_MESSAGE("Gateway Timeout", *mlen); 107 | case 505: RETURN_STATUS_MESSAGE("HTTP Version Not Supported", *mlen); 108 | case 506: RETURN_STATUS_MESSAGE("Variant Also Negotiates", *mlen); /* RFC 2295 */ 109 | case 507: RETURN_STATUS_MESSAGE("Insufficient Storage", *mlen); /* RFC 2518 (WebDAV) */ 110 | case 509: RETURN_STATUS_MESSAGE("Bandwidth Limit Exceeded", *mlen); /* unofficial */ 111 | case 510: RETURN_STATUS_MESSAGE("Not Extended", *mlen); /* RFC 2774 */ 112 | case 511: RETURN_STATUS_MESSAGE("Network Authentication Required", *mlen); 113 | default: break; 114 | } 115 | /* default to the Nxx group names in RFC 2616 */ 116 | if (100 <= code && code <= 199) { 117 | RETURN_STATUS_MESSAGE("Informational", *mlen); 118 | } 119 | else if (200 <= code && code <= 299) { 120 | RETURN_STATUS_MESSAGE("Success", *mlen); 121 | } 122 | else if (300 <= code && code <= 399) { 123 | RETURN_STATUS_MESSAGE("Redirection", *mlen); 124 | } 125 | else if (400 <= code && code <= 499) { 126 | RETURN_STATUS_MESSAGE("Client Error", *mlen); 127 | } 128 | else { 129 | RETURN_STATUS_MESSAGE("Error", *mlen); 130 | } 131 | } 132 | 133 | static VALUE cRhebok; 134 | 135 | static VALUE request_method_key; 136 | static VALUE request_uri_key; 137 | static VALUE script_name_key; 138 | static VALUE server_protocol_key; 139 | static VALUE query_string_key; 140 | static VALUE remote_addr_key; 141 | static VALUE remote_port_key; 142 | static VALUE path_info_key; 143 | 144 | static VALUE vacant_string_val; 145 | static VALUE zero_string_val; 146 | 147 | static VALUE http10_val; 148 | static VALUE http11_val; 149 | 150 | static VALUE expect_key; 151 | 152 | struct common_header { 153 | const char * name; 154 | size_t name_len; 155 | VALUE key; 156 | }; 157 | static int common_headers_num = 0; 158 | static struct common_header common_headers[20]; 159 | 160 | static char date_buf[sizeof("Date: Sat, 19 Dec 2015 14:16:27 GMT\r\n")-1]; 161 | 162 | static 163 | void set_common_header(const char * key, int key_len, const int raw) 164 | { 165 | char tmp[MAX_HEADER_NAME_LEN + sizeof("HTTP_") - 1]; 166 | const char* name; 167 | size_t name_len = 0; 168 | const char * s; 169 | char* d; 170 | size_t n; 171 | VALUE env_key; 172 | 173 | if ( raw == 1) { 174 | for (s = key, n = key_len, d = tmp; 175 | n != 0; 176 | s++, --n, d++) { 177 | *d = *s == '-' ? '_' : TOU(*s); 178 | name = tmp; 179 | name_len = key_len; 180 | } 181 | } else { 182 | strcpy(tmp, "HTTP_"); 183 | for (s = key, n = key_len, d = tmp + 5; 184 | n != 0; 185 | s++, --n, d++) { 186 | *d = *s == '-' ? '_' : TOU(*s); 187 | name = tmp; 188 | name_len = key_len + 5; 189 | } 190 | } 191 | env_key = rb_obj_freeze(rb_str_new(name,name_len)); 192 | common_headers[common_headers_num].name = key; 193 | common_headers[common_headers_num].name_len = key_len; 194 | common_headers[common_headers_num].key = env_key; 195 | rb_gc_register_address(&common_headers[common_headers_num].key); 196 | common_headers_num++; 197 | } 198 | 199 | static 200 | long find_lf(const char* v, ssize_t offset, ssize_t len) 201 | { 202 | ssize_t i; 203 | for ( i=offset; i < len; i++) { 204 | if (v[i] == 10) { 205 | return i; 206 | } 207 | } 208 | return len; 209 | } 210 | 211 | static 212 | size_t find_ch(const char* s, size_t len, char ch) 213 | { 214 | size_t i; 215 | for (i = 0; i != len; ++i, ++s) 216 | if (*s == ch) 217 | break; 218 | return i; 219 | } 220 | 221 | static 222 | int header_is(const struct phr_header* header, const char* name, 223 | size_t len) 224 | { 225 | const char* x, * y; 226 | if (header->name_len != len) 227 | return 0; 228 | for (x = header->name, y = name; len != 0; --len, ++x, ++y) 229 | if (TOU(*x) != *y) 230 | return 0; 231 | return 1; 232 | } 233 | 234 | static 235 | VALUE find_common_header(const struct phr_header* header) { 236 | int i; 237 | for ( i = 0; i < common_headers_num; i++ ) { 238 | if ( header_is(header, common_headers[i].name, common_headers[i].name_len) ) { 239 | return common_headers[i].key; 240 | } 241 | } 242 | return Qnil; 243 | } 244 | 245 | static 246 | int store_path_info(VALUE env, const char* src, size_t src_len) { 247 | int dlen = 0; 248 | size_t i = 0; 249 | char *d; 250 | char s2, s3; 251 | d = ALLOC_N(char, src_len * 3 + 1); 252 | for (i = 0; i < src_len; i++ ) { 253 | if ( src[i] == '%' ) { 254 | if ( !isxdigit(src[i+1]) || !isxdigit(src[i+2]) ) { 255 | free(d); 256 | return -1; 257 | } 258 | s2 = src[i+1]; 259 | s3 = src[i+2]; 260 | s2 -= s2 <= '9' ? '0' 261 | : s2 <= 'F' ? 'A' - 10 262 | : 'a' - 10; 263 | s3 -= s3 <= '9' ? '0' 264 | : s3 <= 'F' ? 'A' - 10 265 | : 'a' - 10; 266 | d[dlen++] = s2 * 16 + s3; 267 | i += 2; 268 | } 269 | else { 270 | d[dlen++] = src[i]; 271 | } 272 | } 273 | d[dlen]='0'; 274 | rb_hash_aset(env, path_info_key, rb_str_new(d, dlen)); 275 | xfree(d); 276 | return dlen; 277 | } 278 | 279 | static 280 | int _accept(int fileno, struct sockaddr *addr, unsigned int addrlen) { 281 | int fd; 282 | #ifdef SOCK_NONBLOCK 283 | fd = accept4(fileno, addr, &addrlen, SOCK_CLOEXEC|SOCK_NONBLOCK); 284 | #else 285 | fd = accept(fileno, addr, &addrlen); 286 | #endif 287 | if (fd < 0) { 288 | if ( errno == EINTR ) { 289 | rb_thread_sleep(1); 290 | } 291 | return fd; 292 | } 293 | #ifndef SOCK_NONBLOCK 294 | fcntl(fd, F_SETFD, FD_CLOEXEC); 295 | fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); 296 | #endif 297 | return fd; 298 | } 299 | 300 | static 301 | ssize_t _writev_timeout(const int fileno, const double timeout, struct iovec *iovec, const long iovcnt, const int do_select ) { 302 | ssize_t rv; 303 | int nfound; 304 | int iovcnt_len; 305 | struct pollfd wfds[1]; 306 | if ( iovcnt < 0 ){ 307 | return -1; 308 | } 309 | if ( iovcnt > UINT_MAX ) { 310 | iovcnt_len = UINT_MAX; 311 | } 312 | else { 313 | iovcnt_len = (int)iovcnt; 314 | } 315 | if ( do_select == 1) goto WAIT_WRITE; 316 | DO_WRITE: 317 | rv = writev(fileno, iovec, iovcnt_len); 318 | if ( rv >= 0 ) { 319 | return rv; 320 | } 321 | if ( rv < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK ) { 322 | return rv; 323 | } 324 | WAIT_WRITE: 325 | while (1) { 326 | wfds[0].fd = fileno; 327 | wfds[0].events = POLLOUT; 328 | nfound = poll(wfds, 1, (int)(timeout*1000)); 329 | if ( nfound == 1 ) { 330 | break; 331 | } 332 | if ( nfound == 0 && errno != EINTR ) { 333 | return -1; 334 | } 335 | } 336 | goto DO_WRITE; 337 | } 338 | 339 | static 340 | ssize_t _read_timeout(const int fileno, const double timeout, char * read_buf, const ssize_t read_len ) { 341 | ssize_t rv; 342 | int nfound; 343 | struct pollfd rfds[1]; 344 | DO_READ: 345 | rfds[0].fd = fileno; 346 | rfds[0].events = POLLIN; 347 | //rv = read(fileno, read_buf, read_len); 348 | rv = recvfrom(fileno, read_buf, read_len, 0, NULL, NULL); 349 | if ( rv >= 0 ) { 350 | return rv; 351 | } 352 | if ( rv < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK ) { 353 | return rv; 354 | } 355 | while (1) { 356 | nfound = poll(rfds, 1, (int)(timeout*1000)); 357 | if ( nfound == 1 ) { 358 | break; 359 | } 360 | if ( nfound == 0 && errno != EINTR ) { 361 | return -1; 362 | } 363 | } 364 | goto DO_READ; 365 | } 366 | 367 | static 368 | ssize_t _write_timeout(const int fileno, const double timeout, char * write_buf, const long write_len ) { 369 | ssize_t rv; 370 | int nfound; 371 | struct pollfd wfds[1]; 372 | size_t write_buf_len; 373 | if ( write_len < 0 ) { 374 | return -1; 375 | } 376 | if ( write_len > UINT_MAX ) { 377 | write_buf_len = UINT_MAX; 378 | } 379 | else { 380 | write_buf_len = (unsigned int)write_len; 381 | } 382 | 383 | DO_WRITE: 384 | rv = write(fileno, write_buf, write_buf_len); 385 | if ( rv >= 0 ) { 386 | return rv; 387 | } 388 | if ( rv < 0 && errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK ) { 389 | return rv; 390 | } 391 | while (1) { 392 | wfds[0].fd = fileno; 393 | wfds[0].events = POLLOUT; 394 | nfound = poll(wfds, 1, (int)(timeout*1000)); 395 | if ( nfound == 1 ) { 396 | break; 397 | } 398 | if ( nfound == 0 && errno != EINTR ) { 399 | return -1; 400 | } 401 | } 402 | goto DO_WRITE; 403 | } 404 | 405 | static 406 | void str_s(char * dst, int *dst_len, const char * src, const unsigned long src_len) { 407 | unsigned long i; 408 | int dlen = *dst_len; 409 | for ( i=0; i= *dst_len ); 423 | *dst_len += fig; 424 | } 425 | 426 | static 427 | int _chunked_header(char *buf, ssize_t len) { 428 | int dlen = 0, i; 429 | ssize_t l = len; 430 | while ( l > 0 ) { 431 | dlen++; 432 | l /= 16; 433 | } 434 | i = dlen; 435 | buf[i++] = 13; 436 | buf[i++] = 10; 437 | while ( len > 0 ) { 438 | buf[--dlen] = xdigit[len % 16]; 439 | len /= 16; 440 | } 441 | return i; 442 | } 443 | 444 | static 445 | char * _date_header(void) { 446 | static time_t last; 447 | struct tm gtm; 448 | time_t lt; 449 | int i = 0; 450 | time(<); 451 | if ( last == lt ) return date_buf; 452 | last = lt; 453 | gmtime_r(<, >m); 454 | date_buf[i++] = 'D'; 455 | date_buf[i++] = 'a'; 456 | date_buf[i++] = 't'; 457 | date_buf[i++] = 'e'; 458 | date_buf[i++] = ':'; 459 | date_buf[i++] = ' '; 460 | str_s(date_buf, &i, DoW[gtm.tm_wday], 3); 461 | date_buf[i++] = ','; 462 | date_buf[i++] = ' '; 463 | str_i(date_buf, &i, gtm.tm_mday, 2); 464 | date_buf[i++] = ' '; 465 | str_s(date_buf, &i, MoY[gtm.tm_mon], 3); 466 | date_buf[i++] = ' '; 467 | str_i(date_buf, &i, gtm.tm_year + 1900, 4); 468 | date_buf[i++] = ' '; 469 | str_i(date_buf, &i, gtm.tm_hour,2); 470 | date_buf[i++] = ':'; 471 | str_i(date_buf, &i, gtm.tm_min,2); 472 | date_buf[i++] = ':'; 473 | str_i(date_buf, &i, gtm.tm_sec,2); 474 | date_buf[i++] = ' '; 475 | date_buf[i++] = 'G'; 476 | date_buf[i++] = 'M'; 477 | date_buf[i++] = 'T'; 478 | date_buf[i++] = 13; 479 | date_buf[i++] = 10; 480 | return date_buf; 481 | } 482 | 483 | static 484 | int _parse_http_request(char *buf, ssize_t buf_len, VALUE env) { 485 | const char* method; 486 | size_t method_len; 487 | const char* path; 488 | size_t path_len; 489 | int minor_version; 490 | struct phr_header headers[MAX_HEADERS]; 491 | size_t num_headers, question_at; 492 | size_t i; 493 | int ret; 494 | char tmp[MAX_HEADER_NAME_LEN + sizeof("HTTP_") - 1] = "HTTP_"; 495 | VALUE last_value; 496 | 497 | num_headers = MAX_HEADERS; 498 | ret = phr_parse_request(buf, buf_len, &method, &method_len, &path, 499 | &path_len, &minor_version, headers, &num_headers, 0); 500 | if (ret < 0) 501 | goto done; 502 | 503 | rb_hash_aset(env, request_method_key, rb_str_new(method,method_len)); 504 | rb_hash_aset(env, request_uri_key, rb_str_new(path, path_len)); 505 | rb_hash_aset(env, script_name_key, vacant_string_val); 506 | rb_hash_aset(env, server_protocol_key, (minor_version == 1) ? http11_val : http10_val); 507 | 508 | /* PATH_INFO QUERY_STRING */ 509 | path_len = find_ch(path, path_len, '#'); /* strip off all text after # after storing request_uri */ 510 | question_at = find_ch(path, path_len, '?'); 511 | if ( store_path_info(env, path, question_at) < 0 ) { 512 | rb_hash_clear(env); 513 | ret = -1; 514 | goto done; 515 | } 516 | if (question_at != path_len) ++question_at; 517 | rb_hash_aset(env, query_string_key, rb_str_new(path + question_at, path_len - question_at)); 518 | last_value = Qnil; 519 | 520 | for (i = 0; i < num_headers; ++i) { 521 | if (headers[i].name != NULL) { 522 | const char* name; 523 | size_t name_len; 524 | VALUE slot; 525 | VALUE env_key; 526 | env_key = find_common_header(headers + i); 527 | if ( NIL_P(env_key) ) { 528 | const char* s; 529 | char* d; 530 | size_t n; 531 | if (sizeof(tmp) - 5 < headers[i].name_len) { 532 | rb_hash_clear(env); 533 | ret = -1; 534 | goto done; 535 | } 536 | for (s = headers[i].name, n = headers[i].name_len, d = tmp + 5; 537 | n != 0; 538 | s++, --n, d++) { 539 | *d = *s == '-' ? '_' : TOU(*s); 540 | name = tmp; 541 | name_len = headers[i].name_len + 5; 542 | env_key = rb_str_new(name, name_len); 543 | } 544 | } 545 | slot = rb_hash_aref(env, env_key); 546 | if ( !NIL_P(slot) ) { 547 | rb_str_cat2(slot, ", "); 548 | rb_str_cat(slot, headers[i].value, headers[i].value_len); 549 | } else { 550 | slot = rb_str_new(headers[i].value, headers[i].value_len); 551 | rb_hash_aset(env, env_key, slot); 552 | last_value = slot; 553 | } 554 | } else { 555 | // continuing lines of a mulitiline header 556 | if ( !NIL_P(last_value) ) 557 | rb_str_cat(last_value, headers[i].value, headers[i].value_len); 558 | } 559 | } 560 | done: 561 | return ret; 562 | } 563 | 564 | 565 | 566 | static 567 | VALUE rhe_accept(VALUE self, VALUE fileno, VALUE timeoutv, VALUE tcp, VALUE env) { 568 | struct sockaddr_in cliaddr; 569 | unsigned int len; 570 | char read_buf[MAX_HEADER_SIZE]; 571 | VALUE req; 572 | int flag = 1; 573 | ssize_t rv = 0; 574 | ssize_t buf_len; 575 | ssize_t reqlen; 576 | int fd; 577 | double timeout = NUM2DBL(timeoutv); 578 | 579 | len = sizeof(cliaddr); 580 | fd = _accept(NUM2INT(fileno), (struct sockaddr *)&cliaddr, len); 581 | 582 | /* endif */ 583 | if (fd < 0) { 584 | goto badexit; 585 | } 586 | 587 | rv = _read_timeout(fd, timeout, &read_buf[0], MAX_HEADER_SIZE); 588 | if ( rv <= 0 ) { 589 | close(fd); 590 | goto badexit; 591 | } 592 | 593 | if ( tcp == Qtrue ) { 594 | setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int)); 595 | rb_hash_aset(env, remote_addr_key, rb_str_new2(inet_ntoa(cliaddr.sin_addr))); 596 | rb_hash_aset(env, remote_port_key, rb_fix2str(INT2FIX(ntohs(cliaddr.sin_port)),10)); 597 | } 598 | else { 599 | rb_hash_aset(env, remote_addr_key, vacant_string_val); 600 | rb_hash_aset(env, remote_port_key, zero_string_val); 601 | } 602 | 603 | buf_len = rv; 604 | while (1) { 605 | reqlen = _parse_http_request(&read_buf[0],buf_len,env); 606 | if ( reqlen >= 0 ) { 607 | break; 608 | } 609 | else if ( reqlen == -1 ) { 610 | /* error */ 611 | close(fd); 612 | goto badexit; 613 | } 614 | if ( MAX_HEADER_SIZE - buf_len == 0 ) { 615 | /* too large header */ 616 | char* badreq; 617 | badreq = BAD_REQUEST; 618 | rv = _write_timeout(fd, timeout, badreq, sizeof(BAD_REQUEST) - 1); 619 | close(fd); 620 | goto badexit; 621 | } 622 | /* request is incomplete */ 623 | rv = _read_timeout(fd, timeout, &read_buf[buf_len], MAX_HEADER_SIZE - buf_len); 624 | if ( rv <= 0 ) { 625 | close(fd); 626 | goto badexit; 627 | } 628 | buf_len += rv; 629 | } 630 | 631 | //rv = _write_timeout(fd, timeout, "HTTP/1.0 200 OK\r\nConnection: close\r\n\r\n200 OK\r\n", 632 | // sizeof("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\n200 OK\r\n") - 1); 633 | //close(fd); 634 | //goto badexit; 635 | 636 | VALUE expect_val = rb_hash_aref(env, expect_key); 637 | if ( !NIL_P(expect_val) ) { 638 | if ( strncmp(RSTRING_PTR(expect_val), "100-continue", RSTRING_LEN(expect_val)) == 0 ) { 639 | rv = _write_timeout(fd, timeout, EXPECT_CONTINUE, sizeof(EXPECT_CONTINUE) - 1); 640 | if ( rv <= 0 ) { 641 | close(fd); 642 | goto badexit; 643 | } 644 | } else { 645 | rv = _write_timeout(fd, timeout, EXPECT_FAILED, sizeof(EXPECT_FAILED) - 1); 646 | close(fd); 647 | goto badexit; 648 | } 649 | } 650 | 651 | req = rb_ary_new2(2); 652 | rb_ary_push(req, INT2NUM(fd)); 653 | rb_ary_push(req, rb_str_new(&read_buf[reqlen],buf_len - reqlen)); 654 | return req; 655 | badexit: 656 | return Qnil; 657 | } 658 | 659 | static 660 | VALUE rhe_read_timeout(VALUE self, VALUE filenov, VALUE rbuf, VALUE lenv, VALUE offsetv, VALUE timeoutv) { 661 | char * d; 662 | ssize_t rv; 663 | int fileno; 664 | double timeout; 665 | ssize_t offset; 666 | ssize_t len; 667 | fileno = NUM2INT(filenov); 668 | timeout = NUM2DBL(timeoutv); 669 | offset = NUM2LONG(offsetv); 670 | len = NUM2LONG(lenv); 671 | if ( len > READ_BUF ) 672 | len = READ_BUF; 673 | d = ALLOC_N(char, len); 674 | rv = _read_timeout(fileno, timeout, &d[offset], len); 675 | if ( rv > 0 ) { 676 | rb_str_cat(rbuf, d, rv); 677 | } 678 | xfree(d); 679 | return SSIZET2NUM(rv); 680 | } 681 | 682 | static 683 | VALUE rhe_write_timeout(VALUE self, VALUE fileno, VALUE buf, VALUE len, VALUE offset, VALUE timeout) { 684 | char* d; 685 | ssize_t rv; 686 | buf = rb_String(buf); 687 | d = RSTRING_PTR(buf); 688 | rv = _write_timeout(NUM2INT(fileno), NUM2DBL(timeout), &d[NUM2LONG(offset)], NUM2LONG(len)); 689 | if ( rv < 0 ) { 690 | return Qnil; 691 | } 692 | return SSIZET2NUM(rv); 693 | } 694 | 695 | 696 | static 697 | VALUE rhe_write_all(VALUE self, VALUE fileno, VALUE buf, VALUE offsetv, VALUE timeout) { 698 | char * d; 699 | ssize_t buf_len; 700 | ssize_t rv = 0; 701 | ssize_t written = 0; 702 | 703 | buf = rb_String(buf); 704 | d = RSTRING_PTR(buf); 705 | buf_len = RSTRING_LEN(buf); 706 | 707 | written = 0; 708 | while ( buf_len > written ) { 709 | rv = _write_timeout(NUM2INT(fileno), NUM2DBL(timeout), &d[written], buf_len - written); 710 | if ( rv <= 0 ) { 711 | break; 712 | } 713 | written += rv; 714 | } 715 | if (rv < 0) { 716 | return Qnil; 717 | } 718 | return SSIZET2NUM(written); 719 | } 720 | 721 | static 722 | VALUE rhe_write_chunk(VALUE self, VALUE fileno, VALUE buf, VALUE offsetv, VALUE timeout) { 723 | ssize_t buf_len; 724 | ssize_t rv = 0; 725 | ssize_t written = 0; 726 | ssize_t vec_offset = 0; 727 | ssize_t count =0; 728 | ssize_t remain; 729 | ssize_t iovcnt = 3; 730 | char chunked_header_buf[18]; 731 | 732 | buf = rb_String(buf); 733 | buf_len = RSTRING_LEN(buf); 734 | 735 | if ( buf_len == 0 ){ 736 | return INT2FIX(0); 737 | } 738 | 739 | { 740 | struct iovec v[iovcnt]; // Needs C99 compiler 741 | v[0].iov_len = _chunked_header(chunked_header_buf,buf_len); 742 | v[0].iov_base = chunked_header_buf; 743 | v[1].iov_len = buf_len; 744 | v[1].iov_base = RSTRING_PTR(buf); 745 | v[2].iov_base = "\r\n"; 746 | v[2].iov_len = sizeof("\r\n") -1; 747 | 748 | vec_offset = 0; 749 | written = 0; 750 | remain = iovcnt; 751 | while ( remain > 0 ) { 752 | count = (iovcnt > IOV_MAX) ? IOV_MAX : iovcnt; 753 | rv = _writev_timeout(NUM2INT(fileno), NUM2DBL(timeout), &v[vec_offset], count - vec_offset, (vec_offset == 0) ? 0 : 1); 754 | if ( rv <= 0 ) { 755 | // error or disconnected 756 | break; 757 | } 758 | written += rv; 759 | while ( rv > 0 ) { 760 | if ( (unsigned int)rv >= v[vec_offset].iov_len ) { 761 | rv -= v[vec_offset].iov_len; 762 | vec_offset++; 763 | remain--; 764 | } 765 | else { 766 | v[vec_offset].iov_base = (char*)v[vec_offset].iov_base + rv; 767 | v[vec_offset].iov_len -= rv; 768 | rv = 0; 769 | } 770 | } 771 | } 772 | } 773 | if ( rv < 0 ) { 774 | return Qnil; 775 | } 776 | return SSIZET2NUM(written); 777 | } 778 | 779 | static 780 | int header_to_array(VALUE key_obj, VALUE val_obj, VALUE ary) { 781 | ssize_t val_len; 782 | ssize_t val_offset; 783 | long val_lf; 784 | char * val; 785 | 786 | val_obj = rb_String(val_obj); 787 | val = RSTRING_PTR(val_obj); 788 | val_len = RSTRING_LEN(val_obj); 789 | val_offset = 0; 790 | val_lf = find_lf(val, val_offset, val_len); 791 | if ( val_lf < val_len ) { 792 | /* contain "\n" */ 793 | while ( val_offset < val_len ) { 794 | if ( val_offset != val_lf ) { 795 | rb_ary_push(ary, key_obj); 796 | rb_ary_push(ary, rb_str_new(&val[val_offset],val_lf - val_offset)); 797 | } 798 | val_offset = val_lf + 1; 799 | val_lf = find_lf(val, val_offset, val_len); 800 | } 801 | } 802 | else { 803 | rb_ary_push(ary, key_obj); 804 | rb_ary_push(ary, val_obj); 805 | } 806 | return ST_CONTINUE; 807 | } 808 | 809 | static 810 | VALUE rhe_close(VALUE self, VALUE fileno) { 811 | close(NUM2INT(fileno)); 812 | return Qnil; 813 | } 814 | 815 | static 816 | VALUE rhe_write_response(VALUE self, VALUE filenov, VALUE timeoutv, VALUE status_codev, VALUE headers, VALUE body, VALUE use_chunkedv, VALUE header_onlyv) { 817 | ssize_t hlen = 0; 818 | ssize_t blen = 0; 819 | 820 | ssize_t rv = 0; 821 | ssize_t iovcnt; 822 | ssize_t vec_offset; 823 | ssize_t written; 824 | ssize_t count; 825 | int i; 826 | ssize_t remain; 827 | char status_line[512] = "HTTP/1.1 "; 828 | char * date_line; 829 | int date_pushed = 0; 830 | char * server_line; 831 | int server_pushed = 0; 832 | VALUE harr; 833 | VALUE key_obj; 834 | VALUE val_obj; 835 | char * key; 836 | ssize_t key_len; 837 | const char * message; 838 | 839 | const char * s; 840 | char * d; 841 | ssize_t n; 842 | 843 | char * chunked_header_buf; 844 | 845 | int fileno = NUM2INT(filenov); 846 | double timeout = NUM2DBL(timeoutv); 847 | int status_code = NUM2INT(status_codev); 848 | int use_chunked = NUM2INT(use_chunkedv); 849 | int header_only = NUM2INT(header_onlyv); 850 | 851 | /* status_with_no_entity_body */ 852 | if ( status_code < 200 || status_code == 204 || status_code == 304 ) { 853 | use_chunked = 0; 854 | } 855 | 856 | harr = rb_ary_new2(RHASH_SIZE(headers) * 2); 857 | RB_GC_GUARD(harr); 858 | rb_hash_foreach(headers, header_to_array, harr); 859 | hlen = RARRAY_LEN(harr); 860 | blen = RARRAY_LEN(body); 861 | iovcnt = 10 + (hlen * 2) + blen; 862 | if ( use_chunked ) { 863 | iovcnt += blen*2; 864 | chunked_header_buf = ALLOC_N(char, 32 * blen); 865 | } 866 | 867 | { 868 | struct iovec v[iovcnt]; // Needs C99 compiler 869 | size_t mlen; 870 | /* status line */ 871 | iovcnt = 0; 872 | i = sizeof("HTTP/1.1 ") - 1; 873 | str_i(status_line,&i,status_code,3); 874 | status_line[i++] = ' '; 875 | message = status_message(status_code, &mlen); 876 | str_s(status_line, &i, message, mlen); 877 | status_line[i++] = 13; 878 | status_line[i++] = 10; 879 | v[iovcnt].iov_base = status_line; 880 | v[iovcnt].iov_len = i; 881 | iovcnt++; 882 | 883 | /* for date header */ 884 | iovcnt++; 885 | 886 | v[iovcnt].iov_base = "Server: Rhebok\r\n"; 887 | v[iovcnt].iov_len = sizeof("Server: Rhebok\r\n")-1; 888 | iovcnt++; 889 | 890 | date_pushed = 0; 891 | 892 | for ( i = 0; i < hlen; i++ ) { 893 | key_obj = rb_ary_entry(harr, i); 894 | key = RSTRING_PTR(key_obj); 895 | key_len = RSTRING_LEN(key_obj); 896 | i++; 897 | 898 | if ( strncasecmp(key,"Connection",key_len) == 0 ) { 899 | continue; 900 | } 901 | 902 | val_obj = rb_ary_entry(harr, i); 903 | 904 | if ( strncasecmp(key,"Date",key_len) == 0 ) { 905 | date_line = ALLOC_N(char, sizeof("Date: ")-1 + RSTRING_LEN(val_obj) + sizeof("\r\n")-1); 906 | strcpy(date_line, "Date: "); 907 | for ( s=RSTRING_PTR(val_obj), n = RSTRING_LEN(val_obj), d=date_line+sizeof("Date: ")-1; n !=0; s++, --n, d++) { 908 | *d = *s; 909 | } 910 | date_line[sizeof("Date: ") -1 + RSTRING_LEN(val_obj)] = 13; 911 | date_line[sizeof("Date: ") -1 + RSTRING_LEN(val_obj) + 1] = 10; 912 | v[1].iov_base = date_line; 913 | v[1].iov_len = sizeof("Date: ") -1 + RSTRING_LEN(val_obj) + 2; 914 | date_pushed = 1; 915 | continue; 916 | } 917 | if ( strncasecmp(key,"Server",key_len) == 0 ) { 918 | server_line = ALLOC_N(char, sizeof("Server: ")-1 + RSTRING_LEN(val_obj) + sizeof("\r\n")-1); 919 | strcpy(server_line, "Server: "); 920 | for ( s=RSTRING_PTR(val_obj), n = RSTRING_LEN(val_obj), d=server_line+sizeof("Server: ")-1; n !=0; s++, --n, d++) { 921 | *d = *s; 922 | } 923 | server_line[sizeof("Server: ") -1 + RSTRING_LEN(val_obj)] = 13; 924 | server_line[sizeof("Server: ") -1 + RSTRING_LEN(val_obj) + 1] = 10; 925 | v[2].iov_base = server_line; 926 | v[2].iov_len = sizeof("Server: ") -1 + RSTRING_LEN(val_obj) + 2; 927 | server_pushed = 1; 928 | continue; 929 | } 930 | 931 | v[iovcnt].iov_base = key; 932 | v[iovcnt].iov_len = key_len; 933 | iovcnt++; 934 | v[iovcnt].iov_base = ": "; 935 | v[iovcnt].iov_len = sizeof(": ") - 1; 936 | iovcnt++; 937 | 938 | // value 939 | v[iovcnt].iov_base = RSTRING_PTR(val_obj); 940 | v[iovcnt].iov_len = RSTRING_LEN(val_obj); 941 | iovcnt++; 942 | v[iovcnt].iov_base = "\r\n"; 943 | v[iovcnt].iov_len = sizeof("\r\n") - 1; 944 | iovcnt++; 945 | } 946 | 947 | if ( date_pushed == 0 ) { 948 | v[1].iov_len = sizeof("Date: Sat, 19 Dec 2015 14:16:27 GMT\r\n") - 1; 949 | v[1].iov_base = _date_header(); 950 | } 951 | 952 | if ( use_chunked ) { 953 | v[iovcnt].iov_base = "Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n"; 954 | v[iovcnt].iov_len = sizeof("Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n") - 1; 955 | iovcnt++; 956 | } 957 | else { 958 | v[iovcnt].iov_base = "Connection: close\r\n\r\n"; 959 | v[iovcnt].iov_len = sizeof("Connection: close\r\n\r\n") - 1; 960 | iovcnt++; 961 | } 962 | 963 | ssize_t chb_offset = 0; 964 | for ( i=0; i 0 ) { 994 | count = (iovcnt > IOV_MAX) ? IOV_MAX : iovcnt; 995 | rv = _writev_timeout(fileno, timeout, &v[vec_offset], count - vec_offset, (vec_offset == 0) ? 0 : 1); 996 | if ( rv <= 0 ) { 997 | // error or disconnected 998 | break; 999 | } 1000 | written += rv; 1001 | while ( rv > 0 ) { 1002 | if ( (unsigned int)rv >= v[vec_offset].iov_len ) { 1003 | rv -= v[vec_offset].iov_len; 1004 | vec_offset++; 1005 | remain--; 1006 | } 1007 | else { 1008 | v[vec_offset].iov_base = (char*)v[vec_offset].iov_base + rv; 1009 | v[vec_offset].iov_len -= rv; 1010 | rv = 0; 1011 | } 1012 | } 1013 | } 1014 | } 1015 | if ( use_chunked ) 1016 | xfree(chunked_header_buf); 1017 | if ( server_pushed ) 1018 | xfree(server_line); 1019 | if ( date_pushed ) 1020 | xfree(date_line); 1021 | if ( rv < 0 ) { 1022 | return Qnil; 1023 | } 1024 | return SSIZET2NUM(written); 1025 | } 1026 | 1027 | void Init_rhebok() 1028 | { 1029 | request_method_key = rb_obj_freeze(rb_str_new2("REQUEST_METHOD")); 1030 | rb_gc_register_address(&request_method_key); 1031 | path_info_key = rb_obj_freeze(rb_str_new2("PATH_INFO")); 1032 | rb_gc_register_address(&path_info_key); 1033 | request_uri_key = rb_obj_freeze(rb_str_new2("REQUEST_URI")); 1034 | rb_gc_register_address(&request_uri_key); 1035 | script_name_key = rb_obj_freeze(rb_str_new2("SCRIPT_NAME")); 1036 | rb_gc_register_address(&script_name_key); 1037 | server_protocol_key = rb_obj_freeze(rb_str_new2("SERVER_PROTOCOL")); 1038 | rb_gc_register_address(&server_protocol_key); 1039 | query_string_key = rb_obj_freeze(rb_str_new2("QUERY_STRING")); 1040 | rb_gc_register_address(&query_string_key); 1041 | remote_addr_key = rb_obj_freeze(rb_str_new2("REMOTE_ADDR")); 1042 | rb_gc_register_address(&remote_addr_key); 1043 | remote_port_key = rb_obj_freeze(rb_str_new2("REMOTE_PORT")); 1044 | rb_gc_register_address(&remote_port_key); 1045 | 1046 | vacant_string_val = rb_obj_freeze(rb_str_new("",0)); 1047 | rb_gc_register_address(&vacant_string_val); 1048 | zero_string_val = rb_obj_freeze(rb_str_new("0",1)); 1049 | rb_gc_register_address(&zero_string_val); 1050 | 1051 | http10_val = rb_obj_freeze(rb_str_new2("HTTP/1.0")); 1052 | rb_gc_register_address(&http10_val); 1053 | http11_val = rb_obj_freeze(rb_str_new2("HTTP/1.1")); 1054 | rb_gc_register_address(&http11_val); 1055 | 1056 | expect_key = rb_obj_freeze(rb_str_new2("HTTP_EXPECT")); 1057 | rb_gc_register_address(&expect_key); 1058 | 1059 | set_common_header("HOST",sizeof("HOST") - 1, 0); 1060 | set_common_header("ACCEPT",sizeof("ACCEPT") - 1, 0); 1061 | set_common_header("ACCEPT-ENCODING",sizeof("ACCEPT-ENCODING") - 1, 0); 1062 | set_common_header("ACCEPT-LANGUAGE",sizeof("ACCEPT-LANGUAGE") - 1, 0); 1063 | set_common_header("CACHE-CONTROL",sizeof("CACHE-CONTROL") - 1, 0); 1064 | set_common_header("CONNECTION",sizeof("CONNECTION") - 1, 0); 1065 | set_common_header("CONTENT-LENGTH",sizeof("CONTENT-LENGTH") - 1, 1); 1066 | set_common_header("CONTENT-TYPE",sizeof("CONTENT-TYPE") - 1, 1); 1067 | set_common_header("COOKIE",sizeof("COOKIE") - 1, 0); 1068 | set_common_header("IF-MODIFIED-SINCE",sizeof("IF-MODIFIED-SINCE") - 1, 0); 1069 | set_common_header("REFERER",sizeof("REFERER") - 1, 0); 1070 | set_common_header("USER-AGENT",sizeof("USER-AGENT") - 1, 0); 1071 | set_common_header("X-FORWARDED-FOR",sizeof("X-FORWARDED-FOR") - 1, 0); 1072 | 1073 | cRhebok = rb_const_get(rb_cObject, rb_intern("Rhebok")); 1074 | rb_define_module_function(cRhebok, "accept_rack", rhe_accept, 4); 1075 | rb_define_module_function(cRhebok, "read_timeout", rhe_read_timeout, 5); 1076 | rb_define_module_function(cRhebok, "write_timeout", rhe_write_timeout, 5); 1077 | rb_define_module_function(cRhebok, "write_all", rhe_write_all, 4); 1078 | rb_define_module_function(cRhebok, "write_chunk", rhe_write_chunk, 4); 1079 | rb_define_module_function(cRhebok, "close_rack", rhe_close, 1); 1080 | rb_define_module_function(cRhebok, "write_response", rhe_write_response, 7); 1081 | } 1082 | -------------------------------------------------------------------------------- /lib/rack/handler/rhebok.rb: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) 4 | require 'rubygems' 5 | require 'rack' 6 | require 'stringio' 7 | require 'tempfile' 8 | require 'socket' 9 | require 'rack/utils' 10 | require 'io/nonblock' 11 | require 'prefork_engine' 12 | require 'rhebok' 13 | require 'rhebok/config' 14 | require 'rhebok/buffered' 15 | 16 | $RACK_HANDLER_RHEBOK_GCTOOL = true 17 | begin 18 | require 'gctools/oobgc' 19 | rescue LoadError 20 | $RACK_HANDLER_RHEBOK_GCTOOL = false 21 | end 22 | 23 | module Rack 24 | module Handler 25 | class Rhebok 26 | MAX_MEMORY_BUFFER_SIZE = 1024 * 1024 27 | DEFAULT_OPTIONS = { 28 | :Host => '0.0.0.0', 29 | :Port => 9292, 30 | :Path => nil, 31 | :MaxWorkers => 5, 32 | :Timeout => 300, 33 | :MaxRequestPerChild => 1000, 34 | :MinRequestPerChild => nil, 35 | :SpawnInterval => nil, 36 | :ErrRespawnInterval => nil, 37 | :OobGC => false, 38 | :MaxGCPerRequest => 5, 39 | :MinGCPerRequest => nil, 40 | :BackLog => Socket::SOMAXCONN, 41 | :BeforeFork => nil, 42 | :AfterFork => nil, 43 | :ReusePort => false, 44 | :ChunkedTransfer => false, 45 | } 46 | NULLIO = StringIO.new("").set_encoding('BINARY') 47 | 48 | def self.run(app, options={}) 49 | slf = new(options) 50 | slf.setup_listener() 51 | slf.run_worker(app) 52 | end 53 | 54 | def self.valid_options 55 | { 56 | "Host=HOST" => "Hostname to listen on (default: 0.0.0.0)", 57 | "Port=PORT" => "Port to listen on (default: 9292)", 58 | } 59 | end 60 | 61 | def initialize(options={}) 62 | if options[:OobGC].instance_of?(String) 63 | options[:OobGC] = options[:OobGC].match(/^(true|yes|1)$/i) ? true : false 64 | end 65 | if options[:ReusePort].instance_of?(String) 66 | options[:ReusePort] = options[:ReusePort].match(/^(true|yes|1)$/i) ? true : false 67 | end 68 | if options[:ChunkedTransfer].instance_of?(String) 69 | options[:ChunkedTransfer] = options[:ChunkedTransfer].match(/^(true|yes|1)$/i) ? true : false 70 | end 71 | 72 | @options = DEFAULT_OPTIONS.merge(options) 73 | if @options[:ConfigFile] != nil 74 | puts "loading from config_file:#{options[:ConfigFile]}" 75 | config = ::Rhebok::Config.new 76 | config.instance_eval(::File.read @options.delete(:ConfigFile)) 77 | @options.merge!(config.retrieve) 78 | end 79 | @server = nil 80 | @_is_tcp = false 81 | @_using_defer_accept = false 82 | end 83 | 84 | def setup_listener() 85 | if ENV.has_key?("SERVER_STARTER_PORT") && ENV["SERVER_STARTER_PORT"].to_s.match(/=/) 86 | hostport, fd = ENV["SERVER_STARTER_PORT"].split("=",2) 87 | if m = hostport.match(/(.*):(\d+)/) 88 | @options[:Host] = m[0] 89 | @options[:Port] = m[1].to_i 90 | else 91 | @options[:Port] = hostport 92 | end 93 | @server = Socket.for_fd(fd.to_i) 94 | @_is_tcp = true if !@server.local_address.unix? 95 | end 96 | 97 | if @server == nil 98 | if @options[:Path] != nil 99 | if ::File.socket?(@options[:Path]) 100 | puts "removing existing socket file:#{@options[:Path]}"; 101 | ::File.unlink(@options[:Path]) 102 | end 103 | begin 104 | ::File.unlink(@options[:Path]) 105 | rescue 106 | #ignore 107 | end 108 | puts "Rhebok starts Listening on :unix:#{@options[:Path]} Pid:#{$$}" 109 | oldmask = ::File.umask(0) 110 | @server = Socket.new(Socket::AF_UNIX, Socket::SOCK_STREAM, 0) 111 | @server.bind(Addrinfo.unix(@options[:Path])) 112 | ::File.umask(oldmask) 113 | @_is_tcp = false 114 | @options[:Host] = "0.0.0.0" 115 | @options[:Port] = 0 116 | else 117 | puts "Rhebok starts Listening on #{@options[:Host]}:#{@options[:Port]} Pid:#{$$}" 118 | addrinfo = Addrinfo.tcp(@options[:Host], @options[:Port]) 119 | @server = Socket.new(defined?(Socket::AF_INET6) && addrinfo.afamily == Socket::AF_INET6 ? 120 | Socket::AF_INET6 : Socket::AF_INET, Socket::SOCK_STREAM, 0) 121 | @server.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1) 122 | if @options[:ReusePort] 123 | @server.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEPORT, 1); 124 | end 125 | @server.bind(addrinfo) 126 | @_is_tcp = true 127 | end 128 | @server.listen(@options[:BackLog].to_i) 129 | end # @server == nil 130 | 131 | if RUBY_PLATFORM.match(/linux/) && @_is_tcp == true 132 | begin 133 | @server.setsockopt(Socket::IPPROTO_TCP, 9, 1) 134 | @_using_defer_accept = true 135 | end 136 | end 137 | 138 | if @server.respond_to?("autoclose=") 139 | @server.autoclose = false 140 | end 141 | 142 | end 143 | 144 | def run_worker(app) 145 | pm_args = { 146 | "max_workers" => @options[:MaxWorkers].to_i, 147 | "trap_signals" => { 148 | "TERM" => 'TERM', 149 | "HUP" => 'TERM', 150 | }, 151 | } 152 | if @options[:SpawnInterval] 153 | pm_args["trap_signals"]["USR1"] = ["TERM", @options[:SpawnInterval].to_i] 154 | pm_args["spawn_interval"] = @options[:SpawnInterval].to_i 155 | end 156 | if @options[:ErrRespawnInterval] 157 | pm_args["err_respawn_interval"] = @options[:ErrRespawnInterval].to_i 158 | end 159 | if @options[:BeforeFork] 160 | pm_args["before_fork"] = proc { |pe2| 161 | @options[:BeforeFork].call 162 | } 163 | end 164 | Signal.trap('INT','SYSTEM_DEFAULT') # XXX 165 | 166 | pe = PreforkEngine.new(pm_args) 167 | while !pe.signal_received.match(/^(TERM|USR1)$/) 168 | pe.start do 169 | srand 170 | if @options[:AfterFork] 171 | @options[:AfterFork].call 172 | end 173 | self.accept_loop(app) 174 | end 175 | end 176 | 177 | while pe.wait_all_children(1) > 0 178 | pe.signal_all_children('TERM') 179 | end 180 | end 181 | 182 | def _calc_reqs_per_child 183 | if @options[:MinRequestPerChild] == nil 184 | return @options[:MaxRequestPerChild].to_i 185 | end 186 | max = @options[:MaxRequestPerChild].to_i 187 | min = @options[:MinRequestPerChild].to_i 188 | if min < max 189 | max - ((max - min + 1) * rand).to_i 190 | else 191 | max 192 | end 193 | end 194 | 195 | def _calc_gc_per_req 196 | if @options[:MinGCPerRequest] == nil 197 | return @options[:MaxGCPerRequest].to_i 198 | end 199 | max = @options[:MaxGCPerRequest].to_i 200 | min = @options[:MinGCPerRequest].to_i 201 | if min < max 202 | max - ((max - min + 1) * rand).to_i 203 | else 204 | max 205 | end 206 | end 207 | 208 | 209 | def accept_loop(app) 210 | @term_received = 0 211 | proc_req_count = 0 212 | Signal.trap(:TERM) do 213 | @term_received += 1 214 | end 215 | Signal.trap(:PIPE, "IGNORE") 216 | max_reqs = self._calc_reqs_per_child() 217 | gc_reqs = self._calc_gc_per_req() 218 | fileno = @server.fileno 219 | 220 | env_template = { 221 | "SERVER_NAME" => @options[:Host], 222 | "SERVER_PORT" => @options[:Port].to_s, 223 | "rack.version" => [1,1], 224 | "rack.errors" => STDERR, 225 | "rack.multithread" => false, 226 | "rack.multiprocess" => true, 227 | "rack.run_once" => false, 228 | "rack.url_scheme" => "http", 229 | "rack.input" => NULLIO 230 | } 231 | 232 | while @options[:MaxRequestPerChild].to_i == 0 || proc_req_count < max_reqs 233 | if @term_received > 0 234 | exit!(true) 235 | end 236 | env = env_template.clone 237 | connection, buf = ::Rhebok.accept_rack(fileno, @options[:Timeout], @_is_tcp, env) 238 | if connection 239 | # for tempfile 240 | buffer = nil 241 | begin 242 | proc_req_count += 1 243 | # handle request 244 | if env.key?("CONTENT_LENGTH") && env["CONTENT_LENGTH"].to_i > 0 245 | cl = env["CONTENT_LENGTH"].to_i 246 | buffer = ::Rhebok::Buffered.new(cl,MAX_MEMORY_BUFFER_SIZE) 247 | while cl > 0 248 | chunk = "" 249 | if buf.bytesize > 0 250 | chunk = buf 251 | buf = "" 252 | else 253 | readed = ::Rhebok.read_timeout(connection, chunk, cl, 0, @options[:Timeout]) 254 | if readed == nil 255 | return 256 | end 257 | end 258 | buffer.print(chunk) 259 | cl -= chunk.bytesize 260 | end 261 | env["rack.input"] = buffer.rewind 262 | elsif env.key?("HTTP_TRANSFER_ENCODING") && env.delete("HTTP_TRANSFER_ENCODING") == 'chunked' 263 | buffer = ::Rhebok::Buffered.new(0,MAX_MEMORY_BUFFER_SIZE) 264 | chunked_buffer = ''; 265 | complete = false 266 | while !complete 267 | chunk = "" 268 | if buf.bytesize > 0 269 | chunk = buf 270 | buf = "" 271 | else 272 | readed = ::Rhebok.read_timeout(connection, chunk, 16384, 0, @options[:Timeout]) 273 | if readed == nil 274 | return 275 | end 276 | end 277 | chunked_buffer << chunk 278 | while chunked_buffer.sub!(/^(([0-9a-fA-F]+).*\015\012)/,"") != nil 279 | trailer = $1 280 | chunked_len = $2.hex 281 | if chunked_len == 0 282 | complete = true 283 | break 284 | elsif chunked_buffer.bytesize < chunked_len + 2 285 | chunked_buffer = trailer + chunked_buffer 286 | break 287 | end 288 | buffer.print(chunked_buffer.byteslice(0,chunked_len)) 289 | chunked_buffer = chunked_buffer.byteslice(chunked_len,chunked_buffer.bytesize-chunked_len) 290 | chunked_buffer.sub!(/^\015\012/,"") 291 | end 292 | break if complete 293 | end 294 | env["CONTENT_LENGTH"] = buffer.size.to_s 295 | env["rack.input"] = buffer.rewind 296 | end 297 | 298 | status_code, headers, body = app.call(env) 299 | 300 | use_chunked = 0 301 | if @options[:ChunkedTransfer] 302 | use_chunked = env["SERVER_PROTOCOL"] != "HTTP/1.1" || 303 | headers.key?("Transfer-Encoding") || 304 | headers.key?("Content-Length") ? 0 : 1 305 | end 306 | 307 | if body.instance_of?(Array) 308 | ::Rhebok.write_response(connection, @options[:Timeout], status_code.to_i, headers, body, use_chunked, 0) 309 | else 310 | ::Rhebok.write_response(connection, @options[:Timeout], status_code.to_i, headers, [], use_chunked, 1) 311 | body.each do |part| 312 | ret = nil 313 | if use_chunked == 1 314 | ret = ::Rhebok.write_chunk(connection, part, 0, @options[:Timeout]) 315 | else 316 | ret = ::Rhebok.write_all(connection, part, 0, @options[:Timeout]) 317 | end 318 | if ret == nil 319 | break 320 | end 321 | end #body.each 322 | ::Rhebok.write_all(connection, "0\015\012\015\012", 0, @options[:Timeout]) if use_chunked == 1 323 | body.respond_to?(:close) and body.close 324 | end 325 | #p [env,status_code,headers,body] 326 | ensure 327 | if buffer != nil 328 | buffer.close 329 | end 330 | ::Rhebok.close_rack(connection) 331 | # out of band gc 332 | if @options[:OobGC] 333 | if $RACK_HANDLER_RHEBOK_GCTOOL 334 | GC::OOB.run 335 | elsif proc_req_count % gc_reqs == 0 336 | disabled = GC.enable 337 | GC.start 338 | GC.disable if disabled 339 | end 340 | end 341 | end #begin 342 | end # accept 343 | end #while max_reqs 344 | end #def 345 | 346 | end 347 | end 348 | end 349 | -------------------------------------------------------------------------------- /lib/rhebok.rb: -------------------------------------------------------------------------------- 1 | require "rhebok/version" 2 | require "rhebok/rhebok" 3 | 4 | class Rhebok 5 | # see Rack::Handler::Rhebok 6 | end 7 | 8 | -------------------------------------------------------------------------------- /lib/rhebok/buffered.rb: -------------------------------------------------------------------------------- 1 | require 'stringio' 2 | require 'tempfile' 3 | 4 | class Rhebok 5 | class Buffered 6 | def initialize(length=0,memory_max=1048576) 7 | @length = length 8 | @memory_max = memory_max 9 | @size = 0 10 | if length > memory_max 11 | @buffer = Tempfile.open('r') 12 | @buffer.binmode 13 | @buffer.set_encoding('BINARY') 14 | else 15 | @buffer = StringIO.new("").set_encoding('BINARY') 16 | end 17 | end 18 | 19 | def print(buf) 20 | if @size + buf.bytesize > @memory_max && @buffer.instance_of?(StringIO) 21 | new_buffer = Tempfile.open('r') 22 | new_buffer.binmode 23 | new_buffer.set_encoding('BINARY') 24 | new_buffer << @buffer.string 25 | @buffer = new_buffer 26 | end 27 | @buffer << buf 28 | @size += buf.bytesize 29 | end 30 | 31 | def size 32 | @size 33 | end 34 | 35 | def rewind 36 | @buffer.rewind 37 | @buffer 38 | end 39 | 40 | def close 41 | if @buffer.instance_of?(Tempfile) 42 | @buffer.close! 43 | end 44 | end 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /lib/rhebok/config.rb: -------------------------------------------------------------------------------- 1 | class Rhebok 2 | class Config 3 | def initialize(options={}) 4 | @config = options 5 | end 6 | 7 | def host(val) 8 | @config[:Host] = val 9 | end 10 | 11 | def port(val) 12 | @config[:Port] = val 13 | end 14 | 15 | def path(val) 16 | @config[:Path] = val 17 | end 18 | 19 | def max_workers(val) 20 | @config[:MaxWorkers] = val 21 | end 22 | 23 | def timeout(val) 24 | @config[:Timeout] = val 25 | end 26 | 27 | def max_request_per_child(val) 28 | @config[:MaxRequestPerChild] = val 29 | end 30 | 31 | def min_request_per_child(val) 32 | @config[:MinRequestPerChild] = val 33 | end 34 | 35 | def spawn_interval(val) 36 | @config[:SpawnInterval] = val 37 | end 38 | 39 | def err_respawn_interval(val) 40 | @config[:ErrRespawnInterval] = val 41 | end 42 | 43 | def oobgc(val) 44 | @config[:OobGC] = val 45 | end 46 | 47 | def max_gc_per_request(val) 48 | @config[:MaxGCPerRequest] = val 49 | end 50 | 51 | def min_gc_per_request(val) 52 | @config[:MinGCPerRequest] = val 53 | end 54 | 55 | def backlog(val) 56 | @config[:BackLog] = val 57 | end 58 | 59 | def before_fork(&block) 60 | @config[:BeforeFork] = block 61 | end 62 | 63 | def after_fork(&block) 64 | @config[:AfterFork] = block 65 | end 66 | 67 | def reuseport(&block) 68 | @config[:ReusePort] = block 69 | end 70 | 71 | def chunked_transfer(&block) 72 | @config[:ChunkedTransfer] = block 73 | end 74 | 75 | def retrieve 76 | @config 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /lib/rhebok/version.rb: -------------------------------------------------------------------------------- 1 | class Rhebok 2 | VERSION = "0.9.3" 3 | end 4 | -------------------------------------------------------------------------------- /rhebok.gemspec: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | lib = File.expand_path('../lib', __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require 'rhebok/version' 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "rhebok" 8 | spec.version = Rhebok::VERSION 9 | spec.authors = ["Masahiro Nagano"] 10 | spec.email = ["kazeburo@gmail.com"] 11 | spec.summary = %q{High Performance Preforked Rack Handler} 12 | spec.description = %q{High Performance and Optimized Preforked Rack Handler} 13 | spec.homepage = "https://github.com/kazeburo/rhebok" 14 | spec.license = "Artistic" 15 | spec.extensions = %w[ext/rhebok/extconf.rb] 16 | 17 | spec.files = `git ls-files -z`.split("\x0") 18 | spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } 19 | spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) 20 | spec.require_paths = ["lib"] 21 | 22 | spec.required_ruby_version = '>= 2.2.2' 23 | spec.add_development_dependency "bundler", "~> 1.7" 24 | spec.add_development_dependency "rake", "~> 10.0" 25 | spec.add_development_dependency "bacon" 26 | spec.add_dependency "rack" 27 | spec.add_dependency "prefork_engine", ">= 0.0.7" 28 | 29 | # get an array of submodule dirs by executing 'pwd' inside each submodule 30 | `git submodule --quiet foreach pwd`.split($\).each do |submodule_path| 31 | # for each submodule, change working directory to that submodule 32 | Dir.chdir(submodule_path) do 33 | 34 | # issue git ls-files in submodule's directory 35 | submodule_files = `git ls-files`.split($\) 36 | 37 | # prepend the submodule path to create absolute file paths 38 | submodule_files_fullpaths = submodule_files.map do |filename| 39 | "#{submodule_path}/#{filename}" 40 | end 41 | 42 | # remove leading path parts to get paths relative to the gem's root dir 43 | # (this assumes, that the gemspec resides in the gem's root dir) 44 | submodule_files_paths = submodule_files_fullpaths.map do |filename| 45 | filename.gsub "#{File.dirname(__FILE__)}/", "" 46 | end 47 | 48 | # add relative paths to gem.files 49 | spec.files += submodule_files_paths 50 | end 51 | end 52 | 53 | end 54 | -------------------------------------------------------------------------------- /test/spec_01_basic.rb: -------------------------------------------------------------------------------- 1 | require 'rack/handler/rhebok' 2 | 3 | describe Rhebok do 4 | should 'has a version number' do 5 | Rhebok::VERSION.should.not.equal nil 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /test/spec_02_server.rb: -------------------------------------------------------------------------------- 1 | require 'rack' 2 | require File.expand_path('../testrequest', __FILE__) 3 | require 'timeout' 4 | require 'rack/handler/rhebok' 5 | 6 | describe Rhebok do 7 | extend TestRequest::Helpers 8 | begin 9 | 10 | @host = '127.0.0.1' 11 | @port = 9202 12 | @app = Rack::Lint.new(TestRequest.new) 13 | @pid = fork 14 | if @pid == nil 15 | #child 16 | Rack::Handler::Rhebok.run(@app, :Host=>'127.0.0.1', :Port=>9202, :MaxWorkers=>1) 17 | exit!(true) 18 | end 19 | sleep 1 20 | 21 | # test 22 | should "respond" do 23 | GET("/") 24 | response.should.not.be.nil 25 | end 26 | 27 | should "be a Rhebok" do 28 | GET("/") 29 | status.should.equal 200 30 | response["SERVER_PROTOCOL"].should.equal "HTTP/1.1" 31 | response["SERVER_PORT"].should.equal "9202" 32 | response["SERVER_NAME"].should.equal "127.0.0.1" 33 | end 34 | 35 | should "have rack headers" do 36 | GET("/") 37 | response["rack.version"].should.equal [1,1] 38 | response["rack.multithread"].should.equal false 39 | response["rack.multiprocess"].should.equal true 40 | response["rack.run_once"].should.equal false 41 | end 42 | 43 | should "multiple header" do 44 | GET("/") 45 | header["Content-Type"].should.equal "text/yaml" 46 | header["X-Foo"].should.equal "Foo, Bar" 47 | header["X-Bar"].should.equal "Foo, Bar" 48 | header["X-Baz"].should.equal "Baz" 49 | header["X-Fuga"].should.equal "Fuga" 50 | end 51 | 52 | should "date header" do 53 | GET("/date") 54 | header["Date"].should.equal "Foooo" 55 | end 56 | 57 | should "ignore connection header" do 58 | GET("/connection") 59 | header["Connection"].should.equal "close" 60 | header["Content-Type"].should.equal "text/yaml" 61 | header["Date"].should.match(/20/) 62 | end 63 | 64 | should "have CGI headers on GET" do 65 | GET("/") 66 | response["REQUEST_METHOD"].should.equal "GET" 67 | response["PATH_INFO"].should.be.equal "/" 68 | response["QUERY_STRING"].should.equal "" 69 | response["test.postdata"].should.equal "" 70 | 71 | GET("/test/foo?quux=1") 72 | response["REQUEST_METHOD"].should.equal "GET" 73 | response["PATH_INFO"].should.equal "/test/foo" 74 | response["QUERY_STRING"].should.equal "quux=1" 75 | end 76 | 77 | should "have CGI headers on POST" do 78 | POST("/", {"rack-form-data" => "23"}, {'X-test-header' => '42'}) 79 | status.should.equal 200 80 | response["REQUEST_METHOD"].should.equal "POST" 81 | response["QUERY_STRING"].should.equal "" 82 | response["HTTP_X_TEST_HEADER"].should.equal "42" 83 | response["test.postdata"].should.equal "rack-form-data=23" 84 | end 85 | 86 | should "support HTTP auth" do 87 | GET("/test", {:user => "ruth", :passwd => "secret"}) 88 | response["HTTP_AUTHORIZATION"].should.equal "Basic cnV0aDpzZWNyZXQ=" 89 | end 90 | 91 | should "set status" do 92 | GET("/test?secret") 93 | status.should.equal 403 94 | response["rack.url_scheme"].should.equal "http" 95 | end 96 | 97 | 98 | ensure 99 | sleep 1 100 | if @pid != nil 101 | Process.kill(:TERM, @pid) 102 | Process.wait() 103 | end 104 | end 105 | 106 | end 107 | 108 | 109 | -------------------------------------------------------------------------------- /test/spec_03_unix.rb: -------------------------------------------------------------------------------- 1 | require 'rack' 2 | require File.expand_path('../testrequest', __FILE__) 3 | require 'timeout' 4 | require 'socket' 5 | require 'rack/handler/rhebok' 6 | 7 | describe Rhebok do 8 | extend TestRequest::Helpers 9 | begin 10 | 11 | @path = "/tmp/app_spec_03_unix.sock" 12 | @app = Rack::Lint.new(TestRequest.new) 13 | @pid = fork 14 | if @pid == nil 15 | #child 16 | Rack::Handler::Rhebok.run(@app, :Path=>@path, :MaxWorkers=>1) 17 | exit!(true) 18 | end 19 | sleep 1 20 | 21 | c = UNIXSocket.open(@path) 22 | c.write("GET / HTTP/1.0\r\n\r\n"); 23 | outbuf = "" 24 | c.read(nil,outbuf) 25 | header,body = outbuf.split(/\r\n\r\n/,2) 26 | response = YAML.load(body) 27 | 28 | should "unix domain" do 29 | header.should.not.be.nil 30 | response["rack.version"].should.equal [1,1] 31 | response["rack.url_scheme"].should.equal "http" 32 | response["SERVER_NAME"].should.equal "0.0.0.0" 33 | response["SERVER_PORT"].should.equal "0" 34 | response["REMOTE_ADDR"].should.equal "" 35 | response["REMOTE_PORT"].should.equal "0" 36 | end 37 | 38 | ensure 39 | sleep 1 40 | if @pid != nil 41 | Process.kill(:TERM, @pid) 42 | Process.wait() 43 | end 44 | end 45 | 46 | end 47 | -------------------------------------------------------------------------------- /test/spec_04_hook.rb: -------------------------------------------------------------------------------- 1 | require 'rack' 2 | require File.expand_path('../testrequest', __FILE__) 3 | require 'timeout' 4 | require 'rack/handler/rhebok' 5 | 6 | describe Rhebok do 7 | extend TestRequest::Helpers 8 | begin 9 | 10 | @host = '127.0.0.1' 11 | @port = 9202 12 | @app = Rack::Lint.new(TestRequest.new) 13 | @pid = fork 14 | if @pid == nil 15 | #child 16 | Rack::Handler::Rhebok.run(@app, :Host=>'127.0.0.1', :Port=>9202, :MaxWorkers=>1, 17 | :BeforeFork => proc { ENV["TEST_FOO"] = "FOO" }, 18 | :AfterFork => proc { ENV["TEST_BAR"] = "BAR" }, 19 | ) 20 | exit!(true) 21 | end 22 | sleep 1 23 | 24 | # test 25 | should "hook env" do 26 | GET("/") 27 | response["TEST_FOO"].should.equal "FOO" 28 | response["TEST_BAR"].should.equal "BAR" 29 | end 30 | 31 | ensure 32 | sleep 1 33 | if @pid != nil 34 | Process.kill(:TERM, @pid) 35 | Process.wait() 36 | end 37 | end 38 | 39 | end 40 | -------------------------------------------------------------------------------- /test/spec_05_config.rb: -------------------------------------------------------------------------------- 1 | require 'rack' 2 | require File.expand_path('../testrequest', __FILE__) 3 | require 'timeout' 4 | require 'rack/handler/rhebok' 5 | 6 | describe Rhebok do 7 | extend TestRequest::Helpers 8 | begin 9 | 10 | @host = '127.0.0.1' 11 | @port = 9202 12 | @app = Rack::Lint.new(TestRequest.new) 13 | @pid = fork 14 | if @pid == nil 15 | #child 16 | Rack::Handler::Rhebok.run(@app, :BeforeFork=>proc { ENV["TEST_FOO"]="BAZ" }, :ConfigFile=>File.expand_path('../testconfig.rb', __FILE__)) 17 | exit!(true) 18 | end 19 | sleep 1 20 | 21 | # test 22 | should "hook env" do 23 | GET("/") 24 | response["TEST_FOO"].should.equal "FOO" 25 | response["TEST_BAR"].should.equal "BAR" 26 | end 27 | 28 | ensure 29 | sleep 1 30 | if @pid != nil 31 | Process.kill(:TERM, @pid) 32 | Process.wait() 33 | end 34 | end 35 | 36 | end 37 | -------------------------------------------------------------------------------- /test/spec_06_curl.rb: -------------------------------------------------------------------------------- 1 | require 'rack' 2 | require File.expand_path('../testrequest', __FILE__) 3 | require 'timeout' 4 | require 'socket' 5 | require 'rack/handler/rhebok' 6 | 7 | class ZeroStreamBody 8 | def self.each 9 | yield "Content" 10 | yield "" 11 | yield "Again" 12 | yield nil 13 | yield 0 14 | end 15 | end 16 | 17 | class VacantStreamBody 18 | def self.each 19 | end 20 | end 21 | 22 | 23 | describe Rhebok do 24 | extend TestRequest::Helpers 25 | 26 | @host = '127.0.0.1' 27 | @port = 9202 28 | 29 | test_rhebok(TestRequest.new, proc { 30 | command = 'curl --stderr - -sv -X POST -T "'+File.expand_path('../testrequest.rb', __FILE__)+'" -H "Content-type: text/plain" --header "Transfer-Encoding: chunked" http://127.0.0.1:9202/remove_length' 31 | curl_yaml(command) 32 | should "chunked with curl" do 33 | @request["Transfer-Encoding"].should.equal "chunked" 34 | @request["Expect"].should.equal "100-continue" 35 | @response.key?("Transfer-Encoding").should.equal false 36 | @response["CONTENT_LENGTH"].should.equal File.stat(File.expand_path('../testrequest.rb', __FILE__)).size.to_s 37 | @response["test.postdata"].bytesize.should.equal File.stat(File.expand_path('../testrequest.rb', __FILE__)).size 38 | @header["Transfer-Encoding"].should.equal "chunked" 39 | @header["Connection"].should.equal "close" 40 | @header.key?("HTTP/1.1 100 Continue").should.equal true 41 | end 42 | 43 | command = 'curl --stderr - --http1.0 -sv -X POST -T "'+File.expand_path('../testrequest.rb', __FILE__)+'" -H "Content-type: text/plain" --header "Transfer-Encoding: chunked" http://127.0.0.1:9202/remove_length' 44 | curl_yaml(command) 45 | should "chunked with curl http1.0" do 46 | @response.key?("Transfer-Encoding").should.equal false 47 | @request.key?("Expect").should.equal false 48 | @response["CONTENT_LENGTH"].should.equal File.stat(File.expand_path('../testrequest.rb', __FILE__)).size.to_s 49 | @response["test.postdata"].bytesize.should.equal File.stat(File.expand_path('../testrequest.rb', __FILE__)).size 50 | @header.key?("Transfer-Encoding").should.equal false 51 | @header["Connection"].should.equal "close" 52 | @header.key?("HTTP/1.1 100 Continue").should.equal false 53 | end 54 | },1) 55 | 56 | test_rhebok( proc { 57 | [200,{"Content-Type"=>"text/plain"},["Content","","Again",nil,0]] 58 | }, proc { 59 | command = 'curl --stderr - -sv http://127.0.0.1:9202/' 60 | curl_request(command) 61 | should "zero length with curl" do 62 | @body.should.equal "ContentAgain0" 63 | end 64 | command = 'curl --stderr - -sv --http1.0 http://127.0.0.1:9202/' 65 | curl_request(command) 66 | should "zero length with curl http/1.0" do 67 | @body.should.equal "ContentAgain0" 68 | end 69 | },1) 70 | 71 | test_rhebok( proc { 72 | [200,{"Content-Type"=>"text/plain"},[]] 73 | }, proc { 74 | command = 'curl --stderr - -sv http://127.0.0.1:9202/' 75 | curl_request(command) 76 | should "vacant res with curl" do 77 | @body.should.equal "" 78 | end 79 | command = 'curl --stderr - -sv --http1.0 http://127.0.0.1:9202/' 80 | curl_request(command) 81 | should "vacant rew with curl http/1.0" do 82 | @body.should.equal "" 83 | end 84 | },1) 85 | 86 | test_rhebok( proc { 87 | [200,{"Content-Type"=>"text/plain"},ZeroStreamBody] 88 | }, proc { 89 | command = 'curl --stderr - -sv http://127.0.0.1:9202/' 90 | curl_request(command) 91 | should "zerostream length with curl" do 92 | @body.should.equal "ContentAgain0" 93 | end 94 | command = 'curl --stderr - -sv --http1.0 http://127.0.0.1:9202/' 95 | curl_request(command) 96 | should "zerostream length with curl http/1.0" do 97 | @body.should.equal "ContentAgain0" 98 | end 99 | },1) 100 | 101 | test_rhebok( proc { 102 | [200,{"Content-Type"=>"text/plain"},VacantStreamBody] 103 | }, proc { 104 | command = 'curl --stderr - -sv http://127.0.0.1:9202/' 105 | curl_request(command) 106 | should "vacantstream length with curl" do 107 | @body.should.equal "" 108 | end 109 | command = 'curl --stderr - -sv --http1.0 http://127.0.0.1:9202/' 110 | curl_request(command) 111 | should "vacantstream length with curl http/1.0" do 112 | @body.should.equal "" 113 | end 114 | },1) 115 | 116 | end 117 | -------------------------------------------------------------------------------- /test/testconfig.rb: -------------------------------------------------------------------------------- 1 | host '127.0.0.1' 2 | port 9202 3 | max_workers 1 4 | before_fork { 5 | ENV["TEST_FOO"] = "FOO" 6 | } 7 | after_fork { 8 | ENV["TEST_BAR"] = "BAR" 9 | } 10 | -------------------------------------------------------------------------------- /test/testrequest.rb: -------------------------------------------------------------------------------- 1 | require 'yaml' 2 | require 'net/http' 3 | require 'rack/lint' 4 | 5 | class TestRequest 6 | NOSERIALIZE = [Method, Proc, Rack::Lint::InputWrapper] 7 | 8 | def call(env) 9 | 10 | test_header = {}; 11 | status = env["QUERY_STRING"] =~ /secret/ ? 403 : 200 12 | if env["PATH_INFO"] =~ /date/ then 13 | test_header["Date"] = "Foooo" 14 | end 15 | if env["PATH_INFO"] =~ /connection/ then 16 | test_header["Connection"] = "keepalive" 17 | end 18 | env["test.postdata"] = env["rack.input"].read 19 | minienv = env.dup 20 | # This may in the future want to replace with a dummy value instead. 21 | minienv.delete_if { |k,v| NOSERIALIZE.any? { |c| v.kind_of?(c) } } 22 | ENV.has_key?("TEST_FOO") and minienv["TEST_FOO"] = ENV["TEST_FOO"] 23 | ENV.has_key?("TEST_BAR") and minienv["TEST_BAR"] = ENV["TEST_BAR"] 24 | body = minienv.to_yaml 25 | size = body.respond_to?(:bytesize) ? body.bytesize : body.size 26 | res_header = {"Content-Length" => size.to_s, "Content-Type" => "text/yaml", "X-Foo" => "Foo\nBar", "X-Bar"=>"Foo\n\nBar", "X-Baz"=>"\nBaz", "X-Fuga"=>"Fuga\n"} 27 | if env["PATH_INFO"] =~ /remove_length/ 28 | res_header.delete("Content-Length") 29 | end 30 | [status, res_header.merge(test_header), [body]] 31 | end 32 | 33 | module Helpers 34 | attr_reader :status, :response, :header 35 | 36 | ROOT = File.expand_path(File.dirname(__FILE__) + "/..") 37 | ENV["RUBYOPT"] = "-I#{ROOT}/lib -rubygems" 38 | 39 | def root 40 | ROOT 41 | end 42 | 43 | def rackup 44 | "#{ROOT}/bin/rackup" 45 | end 46 | 47 | def GET(path, header={}) 48 | Net::HTTP.start(@host, @port) { |http| 49 | user = header.delete(:user) 50 | passwd = header.delete(:passwd) 51 | 52 | get = Net::HTTP::Get.new(path, header) 53 | get.basic_auth user, passwd if user && passwd 54 | http.request(get) { |response| 55 | @status = response.code.to_i 56 | @header = response 57 | begin 58 | @response = YAML.load(response.body) 59 | rescue TypeError, ArgumentError 60 | @response = nil 61 | end 62 | } 63 | } 64 | end 65 | 66 | def POST(path, formdata={}, header={}) 67 | Net::HTTP.start(@host, @port) { |http| 68 | user = header.delete(:user) 69 | passwd = header.delete(:passwd) 70 | 71 | post = Net::HTTP::Post.new(path, header) 72 | post.form_data = formdata 73 | post.basic_auth user, passwd if user && passwd 74 | http.request(post) { |response| 75 | @status = response.code.to_i 76 | @response = YAML.load(response.body) 77 | } 78 | } 79 | end 80 | 81 | def test_rhebok(app,cb,chunked=0) 82 | begin 83 | @pid = fork 84 | if @pid == nil 85 | # child 86 | Rack::Handler::Rhebok.run(app, :Host=>@host, :Port=>@port, :MaxWorkers=>1, :ChunkedTransfer=>chunked) 87 | exit!(true) 88 | end 89 | cb.call 90 | ensure 91 | sleep 1 92 | if @pid != nil 93 | Process.kill(:TERM, @pid) 94 | Process.wait() 95 | end 96 | end 97 | end 98 | 99 | 100 | def curl_request(command) 101 | body = "" 102 | header = {} 103 | request = {} 104 | open("|" + command) { |f| 105 | while (line = f.gets) 106 | next if line.match(/^(\*|}|{) /) 107 | if line.match(/^> /) 108 | line.sub!(/^> /,"") 109 | line.gsub!(/[\r\n]/,"") 110 | key,val = line.split(/: /,2) 111 | request[key.to_s] = val.to_s 112 | next 113 | end 114 | if line.match(/^< /) 115 | line.sub!(/^< /,"") 116 | line.gsub!(/[\r\n]/,"") 117 | key,val = line.split(/: /,2) 118 | header[key.to_s] = val.to_s 119 | next 120 | end 121 | line.sub!(/\* Closing connection #?0\n/,"") 122 | body += line 123 | end 124 | } 125 | @request = request 126 | @body = body 127 | @header = header 128 | end 129 | 130 | def curl_yaml(command) 131 | curl_request(command) 132 | @response = YAML.load(@body) 133 | end 134 | 135 | end 136 | end 137 | 138 | class StreamingRequest 139 | def self.call(env) 140 | [200, {"Content-Type" => "text/plain"}, new] 141 | end 142 | 143 | def each 144 | yield "hello there!\n" 145 | sleep 5 146 | yield "that is all.\n" 147 | end 148 | end 149 | 150 | --------------------------------------------------------------------------------