├── .dockerignore ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── background_image.h ├── longs.c ├── longs.h ├── longs_test.c ├── server.c ├── sqlite3.c ├── sqlite3.h ├── styles.h ├── wafer.c ├── wafer.h ├── waferapi.c └── waferapi.h /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | *.db 3 | *.o 4 | longs 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Object files 2 | *.o 3 | *.ko 4 | *.obj 5 | *.elf 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Libraries 12 | *.lib 13 | *.a 14 | *.la 15 | *.lo 16 | 17 | # Shared objects (inc. Windows DLLs) 18 | *.dll 19 | *.so 20 | *.so.* 21 | *.dylib 22 | 23 | # Executables 24 | *.exe 25 | *.out 26 | *.app 27 | *.i*86 28 | *.x86_64 29 | *.hex 30 | 31 | # Databases 32 | *.db 33 | 34 | #Intellij 35 | .idea/* 36 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:jessie 2 | 3 | RUN apt-get -y update \ 4 | && apt-get -y install build-essential 5 | 6 | # Bundle app source 7 | WORKDIR /var/www/longs 8 | COPY . /var/www/longs 9 | RUN make 10 | RUN mkdir /data && chown :0 /data && chmod 775 /data && chmod g+s /data 11 | ENV DB_PATH=/data/URL_Records.db 12 | EXPOSE 8080 13 | CMD PORT=8080 ./longs 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #!/bin/make 2 | 3 | ifdef THREADS 4 | NTHREAD=-D NOPE_THREADS=$(THREADS) 5 | endif 6 | 7 | 8 | ifdef DEBUG 9 | ifeq ($(DEBUG),0) 10 | DEBUG_OPT=-ggdb 11 | else 12 | DEBUG_OPT=-D NOPE_DEBUG -ggdb 13 | endif 14 | endif 15 | 16 | ifdef PROCESSES 17 | PROCESSES_OPT=-D NOPE_PROCESSES=$(PROCESSES) -ggdb 18 | endif 19 | 20 | ifdef LOOP 21 | ifeq ($(LOOP),epoll) 22 | LOOP_OPT=-D NOPE_EPOLL 23 | endif 24 | endif 25 | 26 | ifdef MAX_CON_CONS 27 | MAX_CON_CONS_OPT=-D NOPE_MAX_CON_CONS=$(MAX_CON_CONS) 28 | endif 29 | 30 | ifndef CC 31 | CC=gcc 32 | endif 33 | 34 | EXT_OPTIONS=$(NTHREAD) $(DEBUG_OPT) $(PROCESSES_OPT) $(LOOP_OPT) $(MAX_CON_CONS_OPT) -pthread 35 | 36 | AR=ar 37 | CFLAGS=-W -Wall -O2 -Wno-unused-parameter -g $(EXT_OPTIONS) 38 | LIBLONG_OBJ=wafer.o waferapi.o sqlite3.o 39 | LIBLONG=liblong.a 40 | MODULES=longs 41 | OPTIONS=-ldl 42 | 43 | all: $(MODULES) 44 | 45 | # rule to build modules 46 | %: %.c $(LIBLONG) 47 | $(CC) $(CFLAGS) -o $@ $^ $(OPTIONS) 48 | 49 | $(LIBLONG): $(LIBLONG_OBJ) 50 | $(AR) r $@ $^ 51 | 52 | %.o: %.c 53 | $(CC) $(CFLAGS) -c -o $@ $< 54 | 55 | test: 56 | $(CC) $(CFLAGS) -o longs_test longs_test.c $(LIBLONG) $(OPTIONS) 57 | 58 | clean: 59 | rm -f $(LIBLONG_OBJ) $(MODULES) 60 | 61 | distclean: 62 | rm -f $(LIBLONG) $(LIBNOPE_OBJ) $(MODULES) 63 | 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lon.gs 2 | 3 | 4 | | Component | Build Status | Demo | 5 | | --- | --- | --- | 6 | | Longs |[![Build Status](https://jenkins-longs.hotbed.io/buildStatus/icon?job=longs-longs)](https://jenkins-longs.hotbed.io/job/longs-longs/)| https://longs-longs.hotbed.io/ | 7 | Welcome to Lon.gs, the url shortner. 8 | 9 | Lon.gs is built upon [WAFer](https://github.com/riolet/WAFer), a light flyweight platform for creating lightning fast and scalable network applications using the C language. 10 | 11 | Lon.gs is built with [SQLite](https://www.sqlite.org/), a self-contained, embeddable, zero-configuration SQL database engine, so no database setup is necessary. 12 | 13 | Lon.gs will happily do 10K concurrent connections on an AWS t2.nano, where our website is being served from. 14 | 15 | You can configure the app using the following environmental variables: 16 | 17 | | Option | Defualt Value | 18 | |--------|---------| 19 | | PORT | 4242 | 20 | | BASE_URL | lon.gs | 21 | | DB_PATH | URL_Records.db | 22 | | HASH_LENGTH | 5 | 23 | 24 | 25 | 26 | ## Docker 27 | 28 | You may use our official image on [Docker Hub](https://hub.docker.com/r/riolet/longs/). 29 | 30 | ```bash 31 | docker docker pull riolet/longs 32 | docker run -p 80:80 riolet/longs 33 | ``` 34 | 35 | 36 | This repo includes a Dockerfile, which allows it to be built into a docker container. 37 | 38 | ```bash 39 | docker build --tag=longs . 40 | docker run -p 80:80 longs 41 | ``` 42 | 43 | This will start Lon.gs listening on port 80 on your Docker net IP 44 | -------------------------------------------------------------------------------- /background_image.h: -------------------------------------------------------------------------------- 1 | #define BG_IMAGE "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAJxAAAABkCAMAAAAXOdrQAAACjlBMVEX//////8z//5n//2b//zP//wD/zP//zMz/zJn/zGb/zDP/zAD/mf//mcz/mZn/mWb/mTP/mQD/Zv//Zsz/Zpn/Zmb/ZjP/ZgD/M///M8z/M5n/M2b/MzP/MwD/AP//AMz/AJn/AGb/ADP/AADM///M/8zM/5nM/2bM/zPM/wDMzP/MzMzMzJnMzGbMzDPMzADMmf/MmczMmZnMmWbMmTPMmQDMZv/MZszMZpnMZmbMZjPMZgDMM//MM8zMM5nMM2bMMzPMMwDMAP/MAMzMAJnMAGbMADPMAACZ//+Z/8yZ/5mZ/2aZ/zOZ/wCZzP+ZzMyZzJmZzGaZzDOZzACZmf+ZmcyZmZmZmWaZmTOZmQCZZv+ZZsyZZpmZZmaZZjOZZgCZM/+ZM8yZM5mZM2aZMzOZMwCZAP+ZAMyZAJmZAGaZADOZAABm//9m/8xm/5lm/2Zm/zNm/wBmzP9mzMxmzJlmzGZmzDNmzABmmf9mmcxmmZlmmWZmmTNmmQBmZv9mZsxmZplmZmZmZjNmZgBmM/9mM8xmM5lmM2ZmMzNmMwBmAP9mAMxmAJlmAGZmADNmAAAz//8z/8wz/5kz/2Yz/zMz/wAzzP8zzMwzzJkzzGYzzDMzzAAzmf8zmcwzmZkzmWYzmTMzmQAzZv8zZswzZpkzZmYzZjMzZgAzM/8zM8wzM5kzM2YzMzMzMwAzAP8zAMwzAJkzAGYzADMzAAAA//8A/8wA/5kA/2YA/zMA/wAAzP8AzMwAzJkAzGYAzDMAzAAAmf8AmcwAmZkAmWYAmTMAmQAAZv8AZswAZpkAZmYAZjMAZgAAM/8AM8wAM5kAM2YAMzMAMwAAAP8AAMwAAJkAAGYAADMAAADg4ODExMTbIFSsAAAAAXRSTlMAQObYZgAAAAlwSFlzAAALEwAACxMBAJqcGAAABXxJREFUeNrt2kENACAMwED8KwQ3qNgezZ2LJj0HAAAAAAAABr0LAACwQ4EBAAAAAAAwyhAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAACAIQ4AAAAAAIAEQxwAAGCIAwAAAAAAIMEQBwAAGOIAAAAAAABIMMQBAACGOAAAAAAAABIMcQAAgCEOAAAAAACABEMcAABgiAMAAAAAACDBEAcAABjiAAAAAAAASDDEAQAAhjgAAAAAAAASDHEAAIAhDgAAAAAAgARDHAAAYIgDAAAAAAAgwRAHAAAY4gAAAAAAAEgwxAEAAIY4AAAAAAAAEgxxAADAlg+/cu4npXkzNQAAAABJRU5ErkJggg==" 2 | -------------------------------------------------------------------------------- /longs.c: -------------------------------------------------------------------------------- 1 | #include "wafer.h" 2 | #include "waferapi.h" 3 | #include 4 | #include 5 | #include "sqlite3.h" 6 | #include 7 | #include "styles.h" 8 | #include "longs.h" 9 | 10 | 11 | void server(Request * request, Response * response) { 12 | // open sqlite3 database "URL_Records" 13 | 14 | char *envBaseUrl = getenv("BASE_URL"); 15 | if (envBaseUrl != NULL) { 16 | baseUrl = envBaseUrl; 17 | } 18 | 19 | char *envDbPath = getenv("DB_PATH"); 20 | if (envDbPath != NULL) { 21 | dbPath = envDbPath; 22 | } 23 | 24 | char *envHashLength = getenv("HASH_LENGTH"); 25 | if (envHashLength != NULL) { 26 | hashLength = strtol(envHashLength, (char **)NULL, 10); 27 | } 28 | 29 | int rc = sqlite3_open(dbPath, &db); 30 | // if db exist it will open otherwise create a db 31 | if (rc) { 32 | fprintf(stderr, "sqlite db connectivity error."); 33 | exit(0); 34 | } 35 | //query to create "Records" table if not exists. 36 | char * sql = "CREATE TABLE if not exists Records(URL TEXT PRIMARY KEY NOT NULL);"; 37 | 38 | char * zErrMsg; 39 | Params params; 40 | rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg); 41 | //Execute the sql statement. 42 | if (rc != SQLITE_OK) { 43 | fprintf(stderr, "SQL table creating error: %s\n", zErrMsg); 44 | sqlite3_free(zErrMsg); 45 | } 46 | 47 | dbgprintf("%s %s\n", request->method, request->reqStr); 48 | 49 | if (routeRequest(request, response, "/shorten", form) 50 | || routeRequest(request, response, "/", form)) { 51 | //Request to shorten the URL 52 | } else if (routeRequest(request, response, "/favicon.ico", favicon)) { 53 | 54 | } else { 55 | 56 | char * queryPath = getQueryPath(request); 57 | params.response = response; 58 | getLongUrl(queryPath, ¶ms); 59 | free(queryPath); 60 | } 61 | 62 | sqlite3_close(db); 63 | } 64 | 65 | static void favicon(Request *request, Response *response) { 66 | 67 | } 68 | 69 | static void form(Request *request, Response *response) { 70 | resPrintf(response,HEADER_LAYOUT,"Longs"); 71 | char *longUrl = QUICK_FORM_TEXT(request, response, "URL to shorten "); 72 | dbgprintf("form longUrl %s\n",longUrl); 73 | if (longUrl != NULL) { 74 | shorten(longUrl, response); 75 | } 76 | free(longUrl); 77 | resPrintf(response,WELCOME_PAGE); 78 | resPrintf(response,FOOTER_LAYOUT,2016); 79 | } 80 | 81 | static void shorten(char *longUrl, Response *response) { 82 | 83 | //Validate url 84 | if (!validate_url(longUrl)) { 85 | resPrintf(response, "Must be a valid URL."); 86 | return; 87 | } 88 | 89 | sqlite3_stmt *ppStmt; 90 | 91 | //To prevent bobbytabling, we encode the URL 92 | int rc; 93 | 94 | //Try to insert it. Dupes will be ignored. 95 | sqlite3_prepare_v2(db, "INSERT OR IGNORE INTO Records(URL) VALUES (?1);", -1, &ppStmt, NULL); 96 | sqlite3_bind_text(ppStmt, 1, longUrl, -1, SQLITE_STATIC); 97 | 98 | rc = sqlite3_step(ppStmt); 99 | if (rc != SQLITE_DONE) { 100 | fprintf(stderr, "SQL query execution error: INSERT OR IGNORE INTO Records(URL) VALUES (?1); : %s\n", sqlite3_errmsg(db)); 101 | goto out; 102 | } 103 | 104 | sqlite3_finalize(ppStmt); 105 | 106 | //Fetch it again 107 | sqlite3_prepare_v2(db, "SELECT ROWID from Records where URL = ?1;", -1, &ppStmt, NULL); 108 | sqlite3_bind_text(ppStmt, 1, longUrl, -1, SQLITE_STATIC); 109 | 110 | 111 | rc = sqlite3_step(ppStmt); 112 | 113 | if (rc == SQLITE_ROW) { 114 | int id = sqlite3_column_int(ppStmt, 0); 115 | char hash[hashLength+1]; 116 | alphabet_base_encode(hash, id); 117 | dbgprintf("%s\n",hash); 118 | Params params; 119 | params.longUrl = longUrl; 120 | params.response = response; 121 | printShortUrl(hash, ¶ms) ; 122 | } else if (rc != SQLITE_DONE) { 123 | fprintf(stderr, "SQL query execution error: SELECT ROWID from Records where URL = ?1; : %s\n", sqlite3_errmsg(db)); 124 | goto out; 125 | } 126 | 127 | out: 128 | sqlite3_close(db); 129 | sqlite3_finalize(ppStmt); 130 | } 131 | 132 | static void getLongUrl(char *shortUrl, Params * params) { 133 | sqlite3_stmt *ppStmt; 134 | long id = alphabet_base_decode(shortUrl); 135 | sqlite3_prepare_v2(db, "SELECT URL from Records where ROWID = ?1;", -1, &ppStmt, NULL); 136 | sqlite3_bind_int(ppStmt, 1, id); 137 | int rc = sqlite3_step(ppStmt); 138 | 139 | if (rc == SQLITE_ROW) { 140 | params->response->apiFlags |= API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING; 141 | STATIC_SEND(params->response->fd, "HTTP/1.1 301 Moved Permanently\r\n"); 142 | STATIC_SEND(params->response->fd, "Content-Type: */*; charset=\"UTF-8\"\r\n"); 143 | STATIC_SEND(params->response->fd, "Content-Length: 0\r\n"); 144 | resPrintf(params->response, "Location: %s\r\n", sqlite3_column_text(ppStmt, 0)); 145 | STATIC_SEND(params->response->fd, "\r\n"); 146 | } else { 147 | resPrintf(params->response, HEADER_LAYOUT,"Longs"); 148 | resPrintf(params->response, "We have no record of that short URL%s ", shortUrl); 149 | resPrintf(params->response, WELCOME_PAGE); 150 | resPrintf(params->response,FOOTER_LAYOUT,2016); 151 | } 152 | sqlite3_finalize(ppStmt); 153 | sqlite3_close(db); 154 | } 155 | 156 | static void printShortUrl(char * hash, Params * params) { 157 | char shortUrl[SIZE]; 158 | snprintf(shortUrl, SIZE, "%s/%s",baseUrl,hash); 159 | resPrintf(params->response, "Here's the short url of %s ", params->longUrl); 160 | resPrintf(params->response, 161 | STAG(input, type="text" readonly="readonly" value="%s"), 162 | shortUrl); 163 | } 164 | 165 | /* Encoding/Decoding Tables */ 166 | 167 | static char* alphabet_base_encode(char *hash1, int id) { 168 | int i; 169 | dbgprintf("%d\n", id); 170 | 171 | for (i=0;i=c_len||c[i]!=http_string[i]) { 198 | dbgprintf ("Invalid Scheme http A %c, E %c, %d\n",c[i],http_string[i],i); 199 | return false; 200 | } 201 | } 202 | if (i=c_len||c[i]!=colslashslash[i-cursor]) { 209 | dbgprintf ("Invalid Scheme :// A %c, E %c, %d\n",c[i],colslashslash[i-cursor],i); 210 | return false; 211 | } 212 | } 213 | 214 | cursor=i; 215 | 216 | for (i=cursor;i 3 | 4 | #define dbgprintf printf 5 | 6 | bool validate_url(char *c) { 7 | char * http_string = "http"; 8 | int c_len = strlen(c); 9 | int i; 10 | 11 | for (i=0;i<4;i++) { 12 | if (i>=c_len||c[i]!=http_string[i]) { 13 | dbgprintf ("Invalid Scheme http A %c, E %c, %d\n",c[i],http_string[i],i); 14 | return false; 15 | } 16 | } 17 | if (i=c_len||c[i]!=colslashslash[i-cursor]) { 24 | dbgprintf ("Invalid Scheme :// A %c, E %c, %d\n",c[i],colslashslash[i-cursor],i); 25 | return false; 26 | } 27 | } 28 | 29 | cursor=i; 30 | 31 | for (i=cursor;i\r\n\t\t\tCopyright \u00A9 " QLINK("https://riolet.com","Riolet Corporation") ", %d\r\n\t\t\r\n\t\r\n" HP_CLOSE 49 | 50 | #define WELCOME_PAGE \ 51 | CTAG(div)\ 52 | OTAGA(div,id="content")\ 53 | QTAG(h2, "Welcome to Lon.gs, the url shortener.")\ 54 | QTAG(P, "Lon.gs is built upon " QLINK("https://github.com/riolet/WAFer","WAFer") ", a light flyweight platform for creating lightning fast and scalable network applications using C language.")\ 55 | QTAG(P, "Lon.gs is built with " QLINK("https://www.sqlite.org/","SQLite") ", a self-contained, embeddable, zero-configuration SQL database engine, so no database setup is necessary.")\ 56 | QTAG(P, "Lon.gs will happily do 10K concurrent connections on an AWS t2.nano, where this website is being served from.")\ 57 | QTAG(P, "Lon.gs is open source, check us out on " QLINK("https://github.com/riolet/longs","github"))\ 58 | QTAG(P, QTAG(EM,"N.B. This website is for demonstration purposes only. We clean the database regularly."))\ 59 | CTAG(div)\ 60 | 61 | #include "background_image.h" 62 | 63 | #define MAIN_CSS "#container{margin:0 auto;width:100%;background:#fff}"\ 64 | "#header{background:#ccc;padding:20px}"\ 65 | "#header h1{margin:0}"\ 66 | "#navigation{float:left;width:100%;background:#333}"\ 67 | "#navigation ul{margin:0;padding:0}"\ 68 | "#navigation ul li{list-style-type:none;display:inline}"\ 69 | "#navigation li a{display:block;float:left;padding:5px 10px;color:#fff;text-decoration:none;border-right:1px solid #fff}"\ 70 | "#navigation li a:hover{background:#383}"\ 71 | "#content-container{float:left;width:100%;background:#FFF url(" BG_IMAGE ") repeat-y 68% 0}"\ 72 | "#content{clear:left;float:left;width:60%;padding:20px 0;margin:0 0 0 4%;display:inline}"\ 73 | "#content h2{margin:0}"\ 74 | "#aside{float:right;width:26%;padding:20px 0;margin:0 3%;display:inline}"\ 75 | "#aside h3{margin:0}"\ 76 | "#footer{clear:left;background:#ccc;text-align:right;padding:20px;height:1%}"\ 77 | "div.console{padding:.5em;clear:both;overflow:auto;background:#000;color:#FFF;font-family:\"Courier New\",Courier,monospace}"\ 78 | "div.code{border:1px solid #DCDCDC;padding:1em;overflow:auto;background:#FFF}"\ 79 | "@media only screen and (device-width: 360px) and (device-height: 640px) and (orientation: portrait) {"\ 80 | "#container{margin:0;padding:0;font-size: 2em;}"\ 81 | "#content-container{float:left;width:100%;background:#FFF}"\ 82 | "#aside,#content{clear:both;width:100%;margin:0;display:inline}"\ 83 | "div.code{max-height:800px}"\ 84 | "#footer{clear:both;text-align:right}}"\ 85 | "@media only screen and (device-width: 720px) and (device-height: 1280px) and (orientation: portrait) {"\ 86 | "#container{margin:0;padding:0;font-size: 2em;}"\ 87 | "#content-container{float:left;width:100%;background:#FFF}"\ 88 | "#aside,#content{clear:both;width:100%;margin:0;display:inline}"\ 89 | "div.code{max-height:800px}"\ 90 | "#footer{clear:both;text-align:right}}"\ 91 | "@media only screen and (max-width:767px) {"\ 92 | "#container{margin:0;padding:0;font-size: large;font-size: 2em;}"\ 93 | "#content-container{float:left;width:100%;background:#FFF}"\ 94 | "#aside,#content{clear:both;width:100%;margin:0;display:inline}"\ 95 | "div.code{max-height:400px}"\ 96 | "#footer{clear:both;text-align:right}}"\ 97 | ".comment { color: #999999; font-style: italic; }"\ 98 | ".pre { color: #000099; }\r\n.string { color: #009900; }"\ 99 | ".char { color: #009900; }\r\n.float { color: #996600; }"\ 100 | ".int { color: #999900; }\r\n.bool { color: #000000; font-weight: bold; }"\ 101 | ".type { color: #FF6633; }\r\n.flow { color: #FF0000; }\r\n.keyword { color: #990000; }"\ 102 | ".operator { color: #663300; font-weight: bold; }" 103 | 104 | #define SINGLE_COLUMN_CSS "#content{clear:left;float:left;width:90%;padding:20px 0;margin:0 0 0 4%;display:inline}"\ 105 | "#content-container{float:left;width:100%;background:#FFF}" 106 | 107 | #endif /* STYLES_H_*/ 108 | -------------------------------------------------------------------------------- /wafer.c: -------------------------------------------------------------------------------- 1 | /* Author: Rohana Rezel, Riolet Corporation 2 | * Please visit waferdotc.com for more information 3 | */ 4 | 5 | #include "wafer.h" 6 | 7 | static inline bool on_conditition_terminate_string_change_state(bool conditition, char * str, int i, short int * cur_state, int state) { 8 | if (conditition) { 9 | *str=0; 10 | *cur_state = state; 11 | return true; 12 | } 13 | return false; 14 | } 15 | 16 | #define FCNTL_ADD(s, fl) fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0) | fl) 17 | #define FCNTL_NONBLOCK(s) FCNTL_ADD(s, O_NONBLOCK) 18 | 19 | void new_fd_data(FdData * fd) 20 | { 21 | fd->state = STATE_PRE_REQUEST; 22 | LOG_ERROR_ON_NULL(fd->readBuffer = 23 | malloc((MAX_REQUEST_SIZE + 1) * SIZE_OF_CHAR), 24 | "Can't malloc " WAFER_STR(__LINE__)); 25 | LOG_ERROR_ON_NULL(fd->method = 26 | malloc((MAX_METHOD_SIZE + 1) * SIZE_OF_CHAR), 27 | "Can't malloc " WAFER_STR(__LINE__)); 28 | LOG_ERROR_ON_NULL(fd->uri = 29 | malloc((MAX_REQUEST_SIZE + 1) * SIZE_OF_CHAR), 30 | " Can't malloc " WAFER_STR(__LINE__)); 31 | LOG_ERROR_ON_NULL(fd->ver = 32 | malloc((MAX_VER_SIZE + 1) * SIZE_OF_CHAR), 33 | " Can't malloc " WAFER_STR(__LINE__)); 34 | LOG_ERROR_ON_NULL(fd->headers = 35 | malloc(MAX_HEADERS * sizeof(char *)), 36 | " Can't malloc " WAFER_STR(__LINE__)); 37 | fd->readBufferIdx = 0; 38 | fd->readBufferLen = 0; 39 | fd->methodIdx = 0; 40 | fd->uriIdx = 0; 41 | fd->verIdx = 0; 42 | fd->headersIdx = 0; 43 | fd->headers[fd->headersIdx] = NULL; 44 | fd->withinHeaderIdx = 0; 45 | } 46 | 47 | void free_fd_data(FdData * fd) 48 | { 49 | free(fd->readBuffer); 50 | free(fd->method); 51 | free(fd->uri); 52 | freeHeaders(fd->headers); 53 | free(fd->ver); 54 | fd->readBufferIdx = 0; 55 | fd->readBufferLen = 0; 56 | fd->methodIdx = 0; 57 | fd->uriIdx = 0; 58 | fd->verIdx = 0; 59 | fd->headersIdx = 0; 60 | fd->withinHeaderIdx = 0; 61 | } 62 | 63 | /* Free thy mallocs */ 64 | void freeHeaders(char **headers) 65 | { 66 | int i = 0; 67 | while (headers[i] != NULL) { 68 | free(headers[i]); 69 | i++; 70 | } 71 | free(headers); 72 | } 73 | 74 | long dbgprintf(const char *format, ...) 75 | { 76 | long done = 0; 77 | #ifdef WAFER_DEBUG 78 | int len; 79 | va_list arg; 80 | va_start(arg, format); 81 | done = vprintf(format, arg); 82 | va_end(arg); 83 | #endif 84 | return done; 85 | } 86 | 87 | /* Simplifies calls to bind(), connect(), and accept() */ 88 | typedef struct sockaddr SA; 89 | 90 | int open_listenfd(int port) 91 | { 92 | int listenfd, optval = 1; 93 | struct sockaddr_in serveraddr; 94 | 95 | /* Create a socket descriptor */ 96 | if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) 97 | return -1; 98 | 99 | /* Eliminates "Address already in use" error from bind. */ 100 | if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, 101 | (const void *)&optval, sizeof(int)) < 0) 102 | return -1; 103 | 104 | /* TCP_CORK: If set, don't send out partial frames. */ 105 | #ifdef TCP_CORK 106 | if (setsockopt(listenfd, IPPROTO_TCP, TCP_CORK, 107 | (const void *)&optval, sizeof(int)) < 0) 108 | return -1; 109 | #endif 110 | 111 | /* Listenfd will be an endpoint for all requests to port 112 | on any IP address for this host */ 113 | memset(&serveraddr, 0, sizeof(serveraddr)); 114 | serveraddr.sin_family = AF_INET; 115 | serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); 116 | serveraddr.sin_port = htons((unsigned short)port); 117 | if (bind(listenfd, (SA *) & serveraddr, sizeof(serveraddr)) < 0) 118 | return -1; 119 | 120 | /* Make it a listening socket ready to accept connection requests */ 121 | if (listen(listenfd, LISTENQ) < 0) 122 | return -1; 123 | return listenfd; 124 | } 125 | 126 | void *get_in_addr(struct sockaddr *sa) 127 | { 128 | if (sa->sa_family == AF_INET) { 129 | return &(((struct sockaddr_in *)sa)->sin_addr); 130 | } 131 | 132 | return &(((struct sockaddr_in6 *)sa)->sin6_addr); 133 | } 134 | 135 | void accept_connection(FdData * fds, int listenfd, char *remote_ip, int *fdmax, 136 | fd_set * master) 137 | { 138 | socklen_t addrlen; 139 | struct sockaddr_storage remoteaddr; // client address 140 | int newfd; // newly accept()ed socket descriptor 141 | 142 | /* handle new connections */ 143 | addrlen = sizeof remoteaddr; 144 | newfd = accept(listenfd, (struct sockaddr *)&remoteaddr, &addrlen); 145 | if (newfd > MAX_NO_FDS) { 146 | fprintf(stderr, "Max FD Size reached. Can't continue"); 147 | return; 148 | } 149 | 150 | if (newfd == -1) { 151 | perror("accept"); 152 | exit(1); 153 | } else { 154 | FD_SET(newfd, master); // add to master set 155 | if (newfd > *fdmax) { // keep track of the max 156 | *fdmax = newfd; 157 | } 158 | dbgprintf("selectserver: new connection from %s on " 159 | "socket %d\n", 160 | inet_ntop(remoteaddr.ss_family, 161 | get_in_addr((struct sockaddr *)&remoteaddr), 162 | remote_ip, INET6_ADDRSTRLEN), newfd); 163 | fds[newfd].state = STATE_PRE_REQUEST; 164 | new_fd_data(&fds[newfd]); 165 | } 166 | } 167 | 168 | void shutdown_connection(FdData * fds, int i, ssize_t nbytes, fd_set * pMaster) 169 | { 170 | /* got error or connection closed by client */ 171 | if (nbytes == 0) { 172 | /* connection closed */ 173 | dbgprintf("selectserver: socket %d hung up\n", i); 174 | } else { 175 | perror("recv"); 176 | } 177 | if (fds[i].state != STATE_PRE_REQUEST) 178 | free_fd_data(&fds[i]); 179 | fds[i].state = STATE_PRE_REQUEST; 180 | 181 | FD_CLR(i, pMaster); // remove from master set 182 | 183 | close(i); 184 | } 185 | 186 | void clear_connection_baggage(FdData * fdDataList, int fd, fd_set * pMaster) 187 | { 188 | /*Todo: Merge with shutdown_connection() */ 189 | if (fdDataList[fd].state != STATE_PRE_REQUEST) 190 | free_fd_data(&fdDataList[fd]); 191 | fdDataList[fd].state = STATE_PRE_REQUEST; 192 | 193 | int result; 194 | if (pMaster != NULL) { 195 | dbgprintf("Clearing connection baggage for %d\n", fd); 196 | FD_CLR(fd, pMaster); /*In Select mode only */ 197 | result = shutdown(fd, 2); 198 | if (result == -1) { 199 | perror("shutdown"); 200 | } 201 | dbgprintf("Shutdown for %d is %d\n", fd, result); 202 | } 203 | result = close(fd); 204 | if (result == -1) { 205 | perror("close"); 206 | } 207 | 208 | } 209 | 210 | int state_machine(FdData * fdDataList, int i, int nbytes, fd_set * pMaster) 211 | { 212 | int idx, j, len; 213 | fdDataList[i].readBufferLen += nbytes; 214 | 215 | bool done = false; 216 | /* we got some data from a client */ 217 | if (fdDataList[i].state == STATE_PRE_REQUEST) { 218 | fdDataList[i].state = STATE_METHOD; 219 | } 220 | 221 | if (fdDataList[i].state == STATE_METHOD) { 222 | idx = fdDataList[i].methodIdx; 223 | j = fdDataList[i].readBufferIdx; 224 | len = fdDataList[i].readBufferLen; 225 | 226 | while (j < len && idx < MAX_METHOD_SIZE) { 227 | if (on_conditition_terminate_string_change_state(isspace(fdDataList[i].readBuffer[j]),&fdDataList[i].method[idx],i,&fdDataList[i].state,STATE_URI)) { 228 | j++; 229 | break; 230 | } else if (on_conditition_terminate_string_change_state(fdDataList[i].readBuffer[j]=='\n',&fdDataList[i].method[idx],i,&fdDataList[i].state,STATE_HEADER)) { 231 | j++; 232 | break; 233 | } else if (fdDataList[i].readBuffer[j]=='\r') { 234 | /*do nothing */ 235 | } else { 236 | fdDataList[i].method[idx++] = fdDataList[i].readBuffer[j]; 237 | } 238 | j++; 239 | } 240 | 241 | fdDataList[i].methodIdx = idx; 242 | fdDataList[i].readBufferIdx = j; 243 | 244 | /*We don't like really long methods. Cut em off */ 245 | if (idx == MAX_METHOD_SIZE) { 246 | fdDataList[i].method[idx] = 0; 247 | fdDataList[i].state = STATE_URI; 248 | } 249 | } 250 | 251 | if (fdDataList[i].state == STATE_URI) { 252 | idx = fdDataList[i].uriIdx; 253 | j = fdDataList[i].readBufferIdx; 254 | len = fdDataList[i].readBufferLen; 255 | 256 | while (j < len && idx < MAX_REQUEST_SIZE) { 257 | if (on_conditition_terminate_string_change_state(isspace(fdDataList[i].readBuffer[j]),&fdDataList[i].uri[idx],i,&fdDataList[i].state,STATE_VERSION)) { 258 | j++; 259 | break; 260 | } else if (on_conditition_terminate_string_change_state(fdDataList[i].readBuffer[j]=='\n',&fdDataList[i].uri[idx],i,&fdDataList[i].state,STATE_HEADER)) { 261 | j++; 262 | break; 263 | } else if (fdDataList[i].readBuffer[j]=='\r') { 264 | /*do nothing */ 265 | } else { 266 | fdDataList[i].uri[idx++] = fdDataList[i].readBuffer[j]; 267 | } 268 | j++; 269 | } 270 | 271 | fdDataList[i].uriIdx = idx; 272 | fdDataList[i].readBufferIdx = j; 273 | 274 | /*We don't like really long URIs either. Cut em off */ 275 | if (idx == MAX_REQUEST_SIZE) { 276 | fdDataList[i].uri[idx] = 0; 277 | fdDataList[i].state = STATE_VERSION; 278 | } 279 | } 280 | 281 | if (fdDataList[i].state == STATE_VERSION) { 282 | idx = fdDataList[i].verIdx; 283 | j = fdDataList[i].readBufferIdx; 284 | len = fdDataList[i].readBufferLen; 285 | 286 | while (j < len && idx < MAX_VER_SIZE) { 287 | if (on_conditition_terminate_string_change_state(fdDataList[i].readBuffer[j]=='\n',&fdDataList[i].ver[idx],i,&fdDataList[i].state,STATE_HEADER)) { 288 | j++; 289 | break; 290 | } else if (fdDataList[i].readBuffer[j]=='\r') { 291 | /*do nothing */ 292 | } else { 293 | fdDataList[i].ver[idx++] = fdDataList[i].readBuffer[j]; 294 | } 295 | j++; 296 | } 297 | fdDataList[i].verIdx = idx; 298 | fdDataList[i].readBufferIdx = j; 299 | 300 | /*We don't like really long version either. Cut em off */ 301 | if (idx == MAX_VER_SIZE) { 302 | fdDataList[i].ver[idx] = 0; 303 | fdDataList[i].state = STATE_HEADER; 304 | } 305 | } 306 | 307 | if (fdDataList[i].state == STATE_HEADER) { 308 | idx = fdDataList[i].withinHeaderIdx; 309 | j = fdDataList[i].readBufferIdx; 310 | len = fdDataList[i].readBufferLen; 311 | 312 | while (j < len) { 313 | if (fdDataList[i].readBuffer[j] == '\n') { 314 | if (idx == 0) { 315 | fdDataList[i].state = STATE_COMPLETE_READING; 316 | j++; 317 | break; /* The last of headers */ 318 | } 319 | fdDataList[i].headers[fdDataList[i].headersIdx][idx] = 0; 320 | if (fdDataList[i].headersIdx < MAX_HEADERS) 321 | fdDataList[i].headersIdx++; 322 | else { 323 | /* OK, buddy, you have sent us MAX_HEADERS headers. That's all yer get */ 324 | fdDataList[i].state = STATE_COMPLETE_READING; 325 | j++; 326 | break; 327 | } 328 | fdDataList[i].headers[fdDataList[i].headersIdx] = NULL; 329 | idx = 0; 330 | } else if (fdDataList[i].readBuffer[j] == '\r') { 331 | /*Skip over \r */ 332 | } else { 333 | if (idx == 0) 334 | fdDataList[i].headers[fdDataList[i].headersIdx] = 335 | malloc(MAX_BUFFER_SIZE * sizeof(char)); 336 | if (idx%d\n" KNRM, fifo->head, fifo->tail); 375 | farmer_thread(td); 376 | dbgprintf(KNRM "SM:Done Farming %d->%d\n" KNRM, fifo->head, fifo->tail); 377 | done = false; 378 | #else 379 | server(&request,&response); 380 | dbgprintf(KGRN "Worker: completed with response %d\n" KNRM, response.status); 381 | done = true; 382 | #endif 383 | } 384 | return done; 385 | } 386 | 387 | #ifdef WAFER_THREADS 388 | void initialize_threads() 389 | { 390 | 391 | pthread_t con; 392 | 393 | LOG_ERROR_ON_NULL(fifo = queueInit(), "main: Clean queue Init failed.\n"); 394 | 395 | LOG_ERROR_ON_NULL(cleaner_fifo = queueInit(), "main: Clean queue Init failed.\n"); 396 | 397 | dbgprintf("Creating threads\n"); 398 | int i; 399 | fd_mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); 400 | pthread_mutex_init(fd_mutex, NULL); 401 | for (i = 0; i < WAFER_THREADS; i++) { 402 | pthread_create(&con, NULL, &worker_thread, fifo); 403 | //con+=sizeof(pthread_t); 404 | } 405 | socketpair(AF_UNIX, SOCK_STREAM, 0, socketpair_fd); 406 | if (FCNTL_NONBLOCK(socketpair_fd[0]) < 0) perror("fcntl"); 407 | if (FCNTL_NONBLOCK(socketpair_fd[1]) < 0) perror("fcntl"); 408 | dbgprintf("Socketpair 1 %d and 2 %d \n", socketpair_fd[0], socketpair_fd[1]); 409 | } 410 | #endif 411 | 412 | void select_loop(int listenfd) 413 | { 414 | 415 | /* Common vars */ 416 | #ifdef WAFER_THREADS 417 | char socket_pair_buffer[2]; 418 | #endif 419 | int nbytes; 420 | 421 | char remote_ip[INET6_ADDRSTRLEN]; 422 | 423 | int fd, fdmax; 424 | int done = 0; 425 | 426 | #ifndef WAFER_MAX_CON_CONS 427 | FdData fdDataList[MAX_NO_FDS]; 428 | #else 429 | FdData *fdDataList; 430 | LOG_ERROR_ON_NULL(fdDataList = 431 | malloc(sizeof(FdData) * MAX_NO_FDS), 432 | "Can't malloc() on fdDataList"); 433 | #endif 434 | 435 | 436 | 437 | /* keep track of the biggest file descriptor */ 438 | fdmax = listenfd; /* so far, it's this one */ 439 | 440 | for (fd = 0; fd < fdmax; fd++) { 441 | fdDataList[fd].state = STATE_PRE_REQUEST; 442 | } 443 | #ifdef WAFER_EPOLL 444 | 445 | struct timeval tv; 446 | int poll_timeout = POLL_TIMEOUT; 447 | tv.tv_sec = 0; 448 | tv.tv_usec = POLL_TIMEOUT * 1000; 449 | 450 | int eventfd; 451 | struct epoll_event event; 452 | struct epoll_event *events; 453 | 454 | eventfd = epoll_create(1234); /*Number is ignored */ 455 | 456 | if (eventfd == -1) { 457 | perror("epoll_create"); 458 | return; 459 | } 460 | 461 | event.data.fd = listenfd; 462 | event.events = EPOLLIN | EPOLLET; 463 | 464 | if (epoll_ctl(eventfd, EPOLL_CTL_ADD, listenfd, &event)) { 465 | perror("epoll_ctl"); 466 | return; 467 | } 468 | #ifdef WAFER_THREADS 469 | /* Socket Pair */ 470 | event.data.fd = socketpair_fd[1]; 471 | event.events = EPOLLIN | EPOLLET; 472 | 473 | if (epoll_ctl(eventfd, EPOLL_CTL_ADD, socketpair_fd[1], &event)) { 474 | perror("epoll_ctl_socketpair"); 475 | return; 476 | } 477 | #endif 478 | 479 | events = calloc(MAX_EVENTS, sizeof event); 480 | /* Epoll main loop */ 481 | while (1) { 482 | 483 | #ifdef WAFER_THREADS 484 | cleaner_thread(); /*Run the thread clearer */ 485 | #endif 486 | int n, e; 487 | dbgprintf(KCYN "Waiting for events \n" KNRM); 488 | n = epoll_wait(eventfd, events, MAX_EVENTS, poll_timeout); 489 | dbgprintf(KCYN "Detected %d events \n" KNRM, n); 490 | for (e = 0; e < n; e++) { 491 | if ((events[e].events & EPOLLERR) || 492 | (events[e].events & EPOLLHUP) || (!(events[e].events & EPOLLIN))) { 493 | fprintf(stderr, "epoll error detected in line %d\n", __LINE__); 494 | close(events[e].data.fd); 495 | continue; 496 | } 497 | 498 | else if (listenfd == events[e].data.fd) { 499 | while (1) { 500 | struct sockaddr in_addr; 501 | socklen_t in_len; 502 | int newfd; 503 | char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; 504 | 505 | in_len = sizeof in_addr; 506 | 507 | newfd = accept(listenfd, &in_addr, &in_len); 508 | 509 | if (newfd == -1) { 510 | if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { 511 | /* We have processed all incoming connections. */ 512 | break; 513 | } else { 514 | perror("accept"); 515 | break; 516 | } 517 | } else if (newfd >= MAX_NO_FDS) { 518 | /* Process some events before accepting more */ 519 | fprintf(stderr, "Reached MAX_NO_FDS at %d\n", newfd); 520 | break; 521 | } 522 | 523 | if (getnameinfo(&in_addr, in_len, 524 | hbuf, sizeof hbuf, 525 | sbuf, sizeof sbuf, 526 | NI_NUMERICHOST | NI_NUMERICSERV) == 0) { 527 | 528 | /*dbgprintf("accept()ed connection on %d (host=%s, port=%s)\n", 529 | newfd, hbuf, sbuf); */ 530 | 531 | fdDataList[newfd].state = STATE_PRE_REQUEST; 532 | new_fd_data(&fdDataList[newfd]); 533 | } 534 | 535 | /* Make the incoming socket non-blocking and add it to the list of fds to monitor. */ 536 | if (FCNTL_NONBLOCK(newfd) < 0) { 537 | perror("fcntl"); 538 | return; 539 | } 540 | 541 | event.data.fd = newfd; 542 | event.events = EPOLLIN | EPOLLET; 543 | if (epoll_ctl(eventfd, EPOLL_CTL_ADD, newfd, &event) < 0) { 544 | perror("epoll_ctl"); 545 | return; 546 | } 547 | } 548 | continue; 549 | } 550 | #ifdef WAFER_THREADS 551 | else if (socketpair_fd[1] == events[e].data.fd) { 552 | nbytes = read(events[e].data.fd, socket_pair_buffer, 1); 553 | dbgprintf(KCYN "SocketPair Read %d : %d\n" KCYN, events[e].data.fd, 554 | nbytes); 555 | if (nbytes == -1) { 556 | if (errno != EAGAIN) { /* EAGAINs we have read all data */ 557 | perror("read"); 558 | } 559 | } 560 | } 561 | #endif 562 | else { 563 | fd = events[e].data.fd; 564 | while (1) { 565 | nbytes = 566 | read(fd, fdDataList[fd].readBuffer + fdDataList[fd].readBufferIdx, 567 | MAX_REQUEST_SIZE - fdDataList[fd].readBufferLen); 568 | dbgprintf(KCYN "Read %d : %d\n" KCYN, fd, nbytes); 569 | if (nbytes == -1) { 570 | if (errno != EAGAIN) { /* EAGAINs we have read all data */ 571 | perror("read"); 572 | done = true; 573 | } 574 | break; 575 | } else if (nbytes == 0) { 576 | done = true; 577 | break; 578 | } 579 | if ((done = state_machine(fdDataList, fd, nbytes, NULL))) { 580 | break; 581 | } 582 | } 583 | 584 | if (done) { 585 | clear_connection_baggage(fdDataList, fd, NULL); 586 | } 587 | 588 | } 589 | } 590 | } 591 | #else 592 | /* Select stuff 593 | * Thank you Brian "Beej Jorgensen" Hall */ 594 | fd_set master; // pMaster file descriptor list 595 | fd_set read_fds; // temp file descriptor list for select() 596 | 597 | FD_ZERO(&master); /* clear the pMaster and temp sets */ 598 | FD_ZERO(&read_fds); 599 | 600 | /* add the listener to the master set */ 601 | FD_SET(listenfd, &master); 602 | 603 | /* Select main loop */ 604 | while (1) { 605 | 606 | #ifdef WAFER_THREADS 607 | cleaner_thread(); /*Run the thread clearer */ 608 | #endif 609 | 610 | read_fds = master; /* copy it */ 611 | 612 | dbgprintf(KRED "Select blocking\n" KNRM); 613 | if (select(fdmax + 1, &read_fds, NULL, NULL, NULL) == -1) { 614 | perror("select"); 615 | exit(4); 616 | } 617 | dbgprintf(KRED "Select blocked\n" KNRM); 618 | /* run through the existing connections looking for data to read */ 619 | for (fd = 0; fd <= fdmax; fd++) { 620 | if (!FD_ISSET(fd, &read_fds)) // we got one!! 621 | continue; 622 | if (fd == listenfd) { 623 | accept_connection(fdDataList, listenfd, remote_ip, &fdmax, &master); 624 | break; 625 | } 626 | nbytes = 627 | recv(fd, fdDataList[fd].readBuffer + fdDataList[fd].readBufferIdx, 628 | MAX_REQUEST_SIZE - fdDataList[fd].readBufferLen, 0); 629 | /* read failure */ 630 | if (nbytes <= 0) { 631 | shutdown_connection(fdDataList, fd, nbytes, &master); 632 | break; 633 | } 634 | 635 | /* State Machine */ 636 | done = state_machine(fdDataList, fd, nbytes, &master); 637 | if (done) { 638 | clear_connection_baggage(fdDataList, fd, &master); 639 | } 640 | } // END looping through file descriptors 641 | } // END for(;;)--and you thought it would never end! 642 | #endif 643 | return; 644 | } 645 | 646 | #ifdef WAFER_THREADS 647 | 648 | void notify_parent() 649 | { 650 | dbgprintf("Notifying parent\n"); 651 | 652 | int written = write(socketpair_fd[0], "C", 1); 653 | if (written == -1) { 654 | if (errno != EAGAIN) { /* EAGAINs we have read all data */ 655 | perror("notify_parent_write"); 656 | } 657 | } 658 | dbgprintf("Wrote socketpair %d : %d\n", socketpair_fd[0], written); 659 | } 660 | 661 | void farmer_thread(THREAD_DATA td) 662 | { 663 | dbgprintf(KYEL "farmer: Gonna get the the mutex for %d\n" KYEL, td.fd); 664 | pthread_mutex_lock(fifo->mut); 665 | dbgprintf(KYEL "farmer: Got the the mutex %d\n" KYEL, td.fd); 666 | while (fifo->full) { 667 | printf(KRED "producer: queue FULL.\n" KNRM); 668 | pthread_cond_wait(fifo->notFull, fifo->mut); 669 | } 670 | queueAdd(fifo, td); 671 | pthread_mutex_unlock(fifo->mut); 672 | pthread_cond_signal(fifo->notEmpty); 673 | } 674 | 675 | void cleaner_thread(void) 676 | { 677 | THREAD_DATA td; 678 | dbgprintf(KMAG "cleaner: Gonna get the the mutex\n" KNRM); 679 | pthread_mutex_lock(cleaner_fifo->mut); 680 | dbgprintf(KMAG "cleaner: Got the mutex\n" KNRM); 681 | if (cleaner_fifo->empty) { 682 | dbgprintf(KMAG "cleaner: queue EMPTY.\n" KNRM); 683 | pthread_mutex_unlock(cleaner_fifo->mut); 684 | } else { 685 | while (!cleaner_fifo->empty) { 686 | queueDel(cleaner_fifo, &td); 687 | dbgprintf(KMAG "cleaner: cleaning %d\n" KNRM, td.fd); 688 | clear_connection_baggage(td.fdDataList, td.fd, td.pMaster); 689 | } 690 | dbgprintf(KMAG "cleaner: NOW queue EMPTY.\n" KNRM); 691 | pthread_mutex_unlock(cleaner_fifo->mut); 692 | pthread_cond_signal(cleaner_fifo->notFull); 693 | } 694 | } 695 | 696 | void *worker_thread(void *arg) 697 | { 698 | THREAD_DATA td; 699 | struct timespec tim, tim2; 700 | 701 | dbgprintf("Creating consumer\n"); 702 | for (;;) { 703 | dbgprintf(KBLU "Worker: Gonna get the the mutex\n" KNRM); 704 | pthread_mutex_lock(fifo->mut); 705 | dbgprintf(KBLU "Worker: Got the mutex\n" KNRM); 706 | while (fifo->empty) { 707 | dbgprintf("Worker: task queue EMPTY.\n"); 708 | pthread_cond_wait(fifo->notEmpty, fifo->mut); 709 | } 710 | queueDel(fifo, &td); 711 | dbgprintf(KGRN "Worker: starting %d\n" KNRM, td.fd); 712 | pthread_mutex_unlock(fifo->mut); 713 | pthread_cond_signal(fifo->notFull); 714 | dbgprintf("td.fdDataList %d, td.fd %d, td.pMaster %d, td.request.headers0 %s\n", 715 | td.fdDataList, td.fd, td.pMaster, td.request.headers[0]); 716 | server(&td.request,&td.response); 717 | dbgprintf(KGRN "Worker: completed %d with response %d\n" KNRM, td.fd,td.response.status); 718 | //clear_connection_baggage(td.fdDataList, td.fd, td.pMaster); 719 | pthread_mutex_lock(cleaner_fifo->mut); 720 | while (cleaner_fifo->full) { 721 | printf(KCYN "Worker: clean queue FULL.\n" KNRM); 722 | pthread_cond_wait(cleaner_fifo->notFull, cleaner_fifo->mut); 723 | } 724 | queueAdd(cleaner_fifo, td); 725 | pthread_mutex_unlock(cleaner_fifo->mut); 726 | pthread_cond_signal(cleaner_fifo->notEmpty); 727 | //notify_parent(); 728 | 729 | /* 730 | tim.tv_sec = 0; 731 | tim.tv_nsec = 1000; 732 | nanosleep(&tim , &tim2); 733 | */ 734 | } 735 | } 736 | 737 | queue *queueInit(void) 738 | { 739 | queue *q; 740 | 741 | q = (queue *) malloc(sizeof(queue)); 742 | if (q == NULL) 743 | return (NULL); 744 | 745 | q->empty = 1; 746 | q->full = 0; 747 | q->head = 0; 748 | q->tail = 0; 749 | 750 | #ifdef WAFER_MAX_CON_CONS 751 | q->buf = malloc(sizeof(THREAD_DATA) * MAX_NO_FDS); 752 | #endif 753 | q->mut = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); 754 | pthread_mutex_init(q->mut, NULL); 755 | q->notFull = (pthread_cond_t *) malloc(sizeof(pthread_cond_t)); 756 | pthread_cond_init(q->notFull, NULL); 757 | q->notEmpty = (pthread_cond_t *) malloc(sizeof(pthread_cond_t)); 758 | pthread_cond_init(q->notEmpty, NULL); 759 | 760 | return (q); 761 | } 762 | 763 | void queueDelete(queue * q) 764 | { 765 | #ifdef WAFER_MAX_CON_CONS 766 | free(q->buf); 767 | #endif 768 | pthread_mutex_destroy(q->mut); 769 | free(q->mut); 770 | pthread_cond_destroy(q->notFull); 771 | free(q->notFull); 772 | pthread_cond_destroy(q->notEmpty); 773 | free(q->notEmpty); 774 | free(q); 775 | } 776 | 777 | void queueAdd(queue * q, THREAD_DATA in) 778 | { 779 | q->buf[q->tail] = in; 780 | q->tail++; 781 | if (q->tail == QUEUESIZE) 782 | q->tail = 0; 783 | if (q->tail == q->head) 784 | q->full = 1; 785 | q->empty = 0; 786 | 787 | return; 788 | } 789 | 790 | void queueDel(queue * q, THREAD_DATA * out) 791 | { 792 | *out = q->buf[q->head]; 793 | 794 | q->head++; 795 | if (q->head == QUEUESIZE) 796 | q->head = 0; 797 | if (q->head == q->tail) 798 | q->empty = 1; 799 | q->full = 0; 800 | 801 | return; 802 | } 803 | #endif 804 | 805 | int main(void) 806 | { 807 | default_port = DEFAULT_PORT; 808 | 809 | int listenfd; 810 | 811 | char *pPort = getenv("PORT"); 812 | char *pUid = getenv ("RUNASUID"); 813 | 814 | if (pPort != NULL) 815 | default_port = (u_short) strtol(pPort, (char **)NULL, 10); 816 | 817 | if (pUid != NULL) { 818 | int uid = (u_short) strtol(pPort, (char **)NULL, 10); 819 | setuid(uid); 820 | if (getuid()!=uid) { 821 | fprintf(stderr, "Could not set UID"); 822 | exit(EXIT_FAILURE); 823 | } 824 | } 825 | 826 | 827 | listenfd = open_listenfd(default_port); 828 | if (listenfd > 0) { 829 | dbgprintf("listen on port %d, fd is %d\n", default_port, listenfd); 830 | } else { 831 | perror("ERROR"); 832 | exit(listenfd); 833 | } 834 | /*Ignore SIGPIPE signal, so if browser cancels the request, it won't kill the whole process. */ 835 | signal(SIGPIPE, SIG_IGN); 836 | 837 | #ifdef WAFER_THREADS 838 | struct rlimit limit; 839 | 840 | limit.rlim_cur = MAX_NO_FDS * 4; 841 | limit.rlim_max = MAX_NO_FDS * 4; 842 | 843 | setrlimit(RLIMIT_NOFILE, &limit); 844 | 845 | /* Get max number of files. */ 846 | getrlimit(RLIMIT_NOFILE, &limit); 847 | 848 | dbgprintf("The soft limit is %llu\n", limit.rlim_cur); 849 | dbgprintf("The hard limit is %llu\n", limit.rlim_max); 850 | initialize_threads(); 851 | #endif 852 | 853 | #ifdef WAFER_PROCESSES 854 | for (i = 0; i < WAFER_PROCESSES; i++) { 855 | int pid = fork(); 856 | if (pid == 0) { // child 857 | select_loop(listenfd); 858 | } else if (pid > 0) { // parent 859 | dbgprintf("child pid is %d\n", pid); 860 | } else { 861 | perror("fork"); 862 | } 863 | } 864 | #else /* Non-blocking if single processes */ 865 | if (FCNTL_NONBLOCK(listenfd) < 0) 866 | perror("fcntl"); 867 | #endif 868 | 869 | select_loop(listenfd); 870 | return 0; 871 | } 872 | -------------------------------------------------------------------------------- /wafer.h: -------------------------------------------------------------------------------- 1 | #ifndef WAFER_H_ 2 | #define WAFER_H_ 3 | 4 | #include /* inet_ntoa */ 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #ifdef WAFER_EPOLL 17 | #include 18 | #else 19 | #include 20 | #endif 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #ifdef WAFER_THREADS 29 | #include 30 | #include 31 | #endif 32 | 33 | /* Colors. Why not ? */ 34 | #define KNRM "\x1B[0m" 35 | #define KRED "\x1B[31m" 36 | #define KGRN "\x1B[32m" 37 | #define KYEL "\x1B[33m" 38 | #define KBLU "\x1B[34m" 39 | #define KMAG "\x1B[35m" 40 | #define KCYN "\x1B[36m" 41 | #define KWHT "\x1B[37m" 42 | #define RESET "\033[0m" 43 | 44 | /* Define boolean */ 45 | typedef int bool; 46 | #define true 1 47 | #define false 0 48 | 49 | #define SERVER_STRING "Server: wafer.chttpd/0.1.0\r\n" 50 | #define ToHex(Y) (Y>='0'&&Y<='9'?Y-'0':Y-'A'+10) 51 | #define UNDEFINED "VALUE_UNDEFINED" 52 | 53 | /* Settings */ 54 | #define WAFER_ONE_K 1024 55 | #define MAX_HEADERS 1024 56 | #define MAX_BUFFER_SIZE 8192 57 | #define MAX_DPRINTF_SIZE 64 58 | #ifdef WAFER_MAX_CON_CONS 59 | #define MAX_NO_FDS WAFER_MAX_CON_CONS 60 | #else 61 | #define MAX_NO_FDS 1024 62 | #endif 63 | #define MAX_METHOD_SIZE 32 64 | #define MAX_VER_SIZE 32 65 | #define MAX_REQUEST_SIZE 8192 66 | #define MAX_EVENTS MAX_NO_FDS/2 67 | #define POLL_TIMEOUT 100 /* ms */ 68 | /* Define HTTP request parsing states */ 69 | #define STATE_PRE_REQUEST 0 70 | #define STATE_METHOD 1 71 | #define STATE_URI 2 72 | #define STATE_VERSION 3 73 | #define STATE_HEADER 4 74 | #define STATE_COMPLETE_READING 5 75 | 76 | #define STATUS_HTTP_OK 200 77 | #define STATUS_HTTP_NOT_FOUND 404 78 | 79 | typedef struct struct_request { 80 | char *reqStr; 81 | size_t reqStrLen; 82 | char *method; 83 | size_t methodLen; 84 | char *ver; 85 | size_t verLen; 86 | char **headers; 87 | size_t headersLen; 88 | } Request; 89 | 90 | typedef struct struct_response { 91 | int fd; 92 | char **headers; 93 | int flags; 94 | int apiFlags; 95 | int status; 96 | } Response; 97 | 98 | typedef struct { 99 | short int state; 100 | char *readBuffer; 101 | short readBufferIdx; 102 | short readBufferLen; 103 | char *method; 104 | short methodIdx; 105 | char *uri; 106 | short uriIdx; 107 | char *ver; 108 | short verIdx; 109 | char **headers; 110 | short headersIdx; 111 | short withinHeaderIdx; 112 | } FdData; 113 | 114 | #define LISTENQ 1024 /* second argument to listen() */ 115 | #define MAXLINE 1024 /* max length of a line */ 116 | #define RIO_BUFSIZE 1024 117 | 118 | #define DEFAULT_PORT 4242 119 | #define DEFAULT_N_CHILDREN 0 120 | 121 | /*Preprocessor abuse */ 122 | #define SIZE_OF_CHAR sizeof(char) 123 | #define LOG_ERROR_ON(_statement_,_condition_,_message_) do { if ((_statement_)==_condition_) fprintf(stderr,_message_); } while(0) 124 | #define LOG_ERROR_ON_NULL(_statement_,_message_) LOG_ERROR_ON(_statement_,NULL,_message_) 125 | #define NEW(T,v) do { T * v = malloc(sizeof(T)); } while (0) 126 | #define WAFER_STR(X) #X 127 | /* Globals */ 128 | int default_port; 129 | 130 | /*Thread stuff!*/ 131 | #ifdef WAFER_THREADS 132 | #define QUEUESIZE MAX_NO_FDS 133 | 134 | /* select_loop stuff */ 135 | typedef struct { 136 | Request request; 137 | Response response; 138 | int fd; 139 | FdData *fdDataList; 140 | fd_set *pMaster; 141 | } THREAD_DATA; 142 | 143 | typedef struct { 144 | #ifdef WAFER_MAX_CON_CONS 145 | THREAD_DATA *buf; 146 | #else 147 | THREAD_DATA buf[QUEUESIZE]; 148 | #endif 149 | long head, tail; 150 | int full, empty; 151 | pthread_mutex_t *mut; 152 | pthread_cond_t *notFull, *notEmpty; 153 | } queue; 154 | 155 | pthread_mutex_t *fd_mutex; 156 | 157 | /*Globals*/ 158 | queue *fifo; 159 | queue *cleaner_fifo; 160 | int socketpair_fd[2]; 161 | 162 | /*Functions*/ 163 | void farmer_thread(THREAD_DATA); 164 | void *worker_thread(void *arg); 165 | void cleaner_thread(void); 166 | queue *queueInit(void); 167 | void queueDelete(queue * q); 168 | void queueAdd(queue * q, THREAD_DATA in); 169 | void queueDel(queue * q, THREAD_DATA * out); 170 | #endif 171 | 172 | void freeHeaders(char **); 173 | long dbgprintf(const char *format, ...); 174 | 175 | void server(Request * request, Response * response); 176 | 177 | #endif /* WAFER_H_ */ 178 | -------------------------------------------------------------------------------- /waferapi.c: -------------------------------------------------------------------------------- 1 | #include "wafer.h" 2 | #include "waferapi.h" 3 | 4 | /* Ver 0.0.5 Functions 5 | * Parameters: request, format, (optional) variadargs 6 | * Returns: the number of characters printed 7 | */ 8 | 9 | /*Internal functions don't use */ 10 | ssize_t writeLongString(int client, const char *longString, size_t len); 11 | static void sendFileWithSelect(int client, int read_fd, struct stat stat_buf); 12 | #ifndef __linux__ 13 | sendfile_wafer (int write_fd, int read_fd, off_t *offset,int remain); 14 | #endif 15 | char * getBufferSpace (); 16 | /*End internal functions */ 17 | 18 | long resPrintf(Response * response, const char *format, ...) 19 | { 20 | dbgprintf("Flags %d API Flags% d response.status %d\n",response->flags,response->apiFlags,response->status); 21 | if (!(response->apiFlags&API_FLAGS_HEADER_SENT)) { 22 | if (!(response->apiFlags&API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING)) { 23 | response->apiFlags|=API_FLAGS_HEADER_SENT; 24 | sendStatusOKHeadersTypeEncoding(response,"text/html",NULL); 25 | } else { 26 | 27 | /*sendHeadersResponse*/ 28 | } 29 | } 30 | /* initial buffer large enough for most cases, will resize if required */ 31 | char *buf = getBufferSpace(); 32 | int len; 33 | 34 | va_list arg; 35 | long done; 36 | va_start(arg, format); 37 | len = vsnprintf(buf, MAX_BUFFER_SIZE, format, arg); 38 | va_end(arg); 39 | 40 | if (len > MAX_BUFFER_SIZE) { 41 | /* buffer size was not enough */ 42 | free(buf); 43 | buf = malloc(len + 1); 44 | if (buf == NULL) { 45 | printf("Could not allocate memory."); 46 | exit(EXIT_FAILURE); 47 | } 48 | va_start(arg, format); 49 | vsnprintf(buf, len + 1, format, arg); 50 | va_end(arg); 51 | } 52 | 53 | if (len < MAX_BUFFER_SIZE) { 54 | done = (int)send(response->fd, buf, len, 0); 55 | } else { 56 | done = writeLongString(response->fd, buf, len); 57 | } 58 | 59 | free(buf); 60 | return done; 61 | } 62 | 63 | /*Writes the given null-terminated string to the compressed file, excluding the terminating null character. 64 | Returns the number of characters written, or -1 in case of error */ 65 | long resPuts(Response * response, const char *buffer) 66 | { 67 | if (!(response->apiFlags&API_FLAGS_HEADER_SENT)) { 68 | if (!(response->apiFlags&API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING)) { 69 | response->apiFlags|=API_FLAGS_HEADER_SENT; 70 | sendStatusOKHeadersTypeEncoding(response,"text/html",NULL); 71 | } else { 72 | /*sendHeadersResponse*/ 73 | } 74 | } 75 | return send(response->fd, buffer, strlen(buffer), 0); 76 | } 77 | 78 | /* Serve file. */ 79 | /* If displayFilename is not null, the file will be downloadable */ 80 | void serveFile(Response * response, const char *filename, const char *displayFilename, 81 | const char *type) 82 | { 83 | FILE *pFile = NULL; 84 | response->apiFlags |= API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING; 85 | 86 | pFile = fopen(filename, "r"); 87 | if (pFile == NULL) { 88 | sendResourceNotFound(response); 89 | } else { 90 | int read_fd = fileno(pFile); 91 | struct stat stat_buf; 92 | fstat (read_fd, &stat_buf); 93 | 94 | STATIC_SEND(response->fd, "HTTP/1.0 200 OK\r\n"); 95 | STATIC_SEND(response->fd, SERVER_STRING); 96 | 97 | resPrintf(response, "Content-Type: %s\r\n", type); 98 | resPrintf(response, "Content-Length: %d\r\n", stat_buf.st_size); 99 | if (displayFilename!=NULL) { 100 | resPrintf(response, "Content-Disposition: attachment; filename=\"%s\"\r\n", 101 | displayFilename); 102 | } 103 | 104 | STATIC_SEND(response->fd, "\r\n"); 105 | 106 | sendFileWithSelect(response->fd, read_fd, stat_buf); 107 | } 108 | fclose(pFile); 109 | } 110 | 111 | void sendStatusOKHeadersTypeEncoding(Response * response, const char *type, const char *encoding) 112 | { 113 | STATIC_SEND(response->fd, "HTTP/1.0 200 OK\r\n"); 114 | STATIC_SEND(response->fd, SERVER_STRING); 115 | resPrintf(response, "Content-Type: %s\r\n", type); 116 | if (encoding != NULL) { 117 | resPrintf(response, "Content-Encoding: %s\r\n", encoding); 118 | } 119 | STATIC_SEND(response->fd, "Vary: Accept-Encoding\r\n"); 120 | STATIC_SEND(response->fd, "\r\n"); 121 | response->status=STATUS_HTTP_OK; 122 | } 123 | 124 | void sendResourceNotFound(Response * response) 125 | { 126 | STATIC_SEND(response->fd, "HTTP/1.0 404 NOT FOUND\r\n"); 127 | STATIC_SEND(response->fd, "Content-Type: text/html\r\n"); 128 | STATIC_SEND(response->fd, "\r\n"); 129 | STATIC_SEND(response->fd, "Not Found\r\n"); 130 | STATIC_SEND(response->fd, "

The server could not fulfill\r\n"); 131 | STATIC_SEND(response->fd, "your request because the resource specified\r\n"); 132 | STATIC_SEND(response->fd, "is unavailable or nonexistent.\r\n"); 133 | STATIC_SEND(response->fd, "

\r\n"); 134 | response->status=STATUS_HTTP_NOT_FOUND; 135 | } 136 | 137 | /*Input Functions */ 138 | char *resQuickForm(Request *request, Response *response, const char *msg, const char *inputstr) 139 | { 140 | char *qpath = getQueryPath(request); 141 | char *qparam = getQueryParam(request,"q"); 142 | if (!((API_FLAGS_FORM_ONLY_ON_NULL&response->apiFlags)&&qparam != NULL)) { 143 | resPrintf(response, OTAGA(form, action = "%s") 144 | "%s%s" STAG(input, type = "submit") CTAG(form), qpath, msg, inputstr); 145 | } 146 | free(qpath); 147 | return qparam; 148 | } 149 | 150 | /* Utility Functions */ 151 | char *getHeader(char **headers, char *header) 152 | { 153 | char *current_header, *matching_header, *value; 154 | // Not sure if MAX_BUFFER_SIZE is right. 155 | char *retval = getBufferSpace(); 156 | 157 | int i; 158 | for (i = 0; headers[i] != NULL; i++) { 159 | current_header = headers[i]; 160 | if ((matching_header = strstr(current_header, header))) { 161 | value = matching_header + strlen(header); 162 | if (*value == ':') { 163 | while (*value == ' ' || *value == ':') { 164 | value++; 165 | } 166 | strncpy(retval, value, MAX_BUFFER_SIZE); 167 | return retval; 168 | } 169 | } 170 | } 171 | memcpy(retval, UNDEFINED, sizeof(UNDEFINED)); 172 | return retval; 173 | } 174 | 175 | /**********************************************************************/ 176 | /* Return the value of a query parameter. 177 | * Parameters: the query string 178 | * the name of the parameter 179 | * Returns: the value of the query parameter */ 180 | /**********************************************************************/ 181 | 182 | char *getQueryParam(Request *request, const char *name) 183 | { 184 | char * bufferAmpersand = getBufferSpace();; 185 | char * bufferQuestion = getBufferSpace();; 186 | snprintf(bufferQuestion, MAX_BUFFER_SIZE - 1, "?%s=", name); 187 | snprintf(bufferAmpersand, MAX_BUFFER_SIZE - 1, "&%s=", name); 188 | char *buffer; 189 | char *pos1; 190 | 191 | char *value = getBufferSpace();; 192 | 193 | int i; 194 | 195 | buffer = bufferQuestion; 196 | pos1 = strstr(request->reqStr, bufferQuestion); 197 | dbgprintf("Buffer %s Pos %s\n", buffer, pos1); 198 | if (!pos1) { 199 | buffer = bufferAmpersand; 200 | pos1 = strstr(request->reqStr, bufferAmpersand); 201 | } 202 | if (pos1) { 203 | pos1 += strlen(buffer); 204 | i = 0; 205 | while (*pos1 && *pos1 != '&' && i < MAX_BUFFER_SIZE-1) { 206 | if (*pos1 == '%') { 207 | value[i] = (char)ToHex(pos1[1]) * 16 + ToHex(pos1[2]); 208 | pos1 += 3; 209 | } else if (*pos1 == '+') { 210 | value[i] = ' '; 211 | pos1++; 212 | } else { 213 | value[i] = *pos1++; 214 | } 215 | i++; 216 | } 217 | value[i] = '\0'; 218 | return value; 219 | } 220 | 221 | free(bufferAmpersand); 222 | free(bufferQuestion); 223 | free(value); 224 | value=NULL; 225 | return value; 226 | } 227 | 228 | /**********************************************************************/ 229 | /* Return the query path. For example the query path for 230 | * http://waferdotc.com/faq is /faq 231 | * Note the / at the beginning 232 | * Parameters: the request 233 | * Returns: the query path */ 234 | /**********************************************************************/ 235 | 236 | char *getQueryPath(Request *request) 237 | { 238 | char *queryPath; 239 | queryPath = strdup(request->reqStr); 240 | u_int i; 241 | for (i = 0; i < strlen(request->reqStr) && (queryPath[i] != '?') && (queryPath[i] != '\0'); 242 | i++) { 243 | } 244 | 245 | queryPath[i] = '\0'; 246 | 247 | return queryPath; 248 | } 249 | 250 | bool routeRequest(Request *request, Response * response, const char *path, void (*function) (Request *, Response *)) 251 | { 252 | char *queryPath = getQueryPath(request); 253 | if (strcmp(queryPath, path) == 0) { 254 | free(queryPath); 255 | if (function != NULL) 256 | function(request, response); 257 | return true; 258 | } else { 259 | free(queryPath); 260 | return false; 261 | } 262 | } 263 | 264 | /*Internal stuff follows. Could change in future. Do not use */ 265 | char * getBufferSpace () { 266 | char *bufferSpace = malloc(MAX_BUFFER_SIZE * sizeof(char)); 267 | if (bufferSpace == NULL) { 268 | fprintf(stderr, "Could not allocate memory."); 269 | exit(EXIT_FAILURE); 270 | } 271 | return bufferSpace; 272 | } 273 | 274 | #ifndef __linux__ 275 | ssize_t sendfile_wafer (int write_fd, int read_fd, off_t *offset,int remain) 276 | { 277 | char * buf = getBufferSpace(); 278 | lseek(read_fd, *offset, SEEK_SET); 279 | ssize_t bytes_read = read(read_fd, buf, MAX_BUFFER_SIZE); 280 | ssize_t bytes_written = write(write_fd, buf, bytes_read); 281 | free(buf); 282 | return bytes_written; 283 | } 284 | #endif // __linux__ 285 | 286 | static void sendFileWithSelect(int write_fd, int read_fd, struct stat stat_buf) 287 | { 288 | off_t offset = 0; 289 | 290 | size_t remain = stat_buf.st_size; 291 | size_t sent = 0; 292 | fd_set write_fds; 293 | FD_ZERO(&write_fds); 294 | FD_SET(write_fd,&write_fds); 295 | struct timeval timeout; 296 | timeout.tv_sec = 5; 297 | timeout.tv_usec = 0; 298 | 299 | while (remain) { 300 | dbgprintf("Remain %d out of %d \n",remain,stat_buf.st_size); 301 | int selected = select (write_fd + 1, NULL, &write_fds, NULL, &timeout); 302 | if (selected < 0) { 303 | return; //TODO-Error Logging 304 | } else if (selected == 0) { 305 | dbgprintf("Timed out. Going back in \n"); 306 | continue; //Timed out. Loop again. 307 | } 308 | #ifdef __linux__ 309 | ssize_t sent_once = sendfile (write_fd, read_fd, &offset, remain); 310 | #else 311 | ssize_t sent_once = sendfile_wafer (write_fd, read_fd, &offset, remain); 312 | #endif // __linux__ 313 | if (sent_once <= 0) 314 | return; 315 | sent += sent_once; 316 | offset = sent; 317 | remain -= sent_once; 318 | } 319 | 320 | 321 | /* Close up. */ 322 | close (read_fd); 323 | } 324 | 325 | ssize_t writeLongString(int client, const char *longString, size_t len) 326 | { 327 | size_t remain = len; 328 | size_t sent = 0; 329 | 330 | while (remain) { 331 | size_t toCpy = remain > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : remain; 332 | ssize_t sent_once = send(client, longString, toCpy, 0); 333 | if (sent_once <= 0) 334 | return -1; 335 | sent += sent_once; 336 | longString += sent_once; 337 | remain -= sent_once; 338 | } 339 | return sent; 340 | } 341 | -------------------------------------------------------------------------------- /waferapi.h: -------------------------------------------------------------------------------- 1 | #ifndef WAFERAPI_H_ 2 | #define WAFERAPI_H_ 3 | /* ENTL */ 4 | #define STR(X) #X 5 | #define WSPC " " 6 | #define CRLF "\r\n" 7 | #define ATTR(key,value) STR(key) STR(=) STR(value) 8 | 9 | #define LT(tag) STR(<) STR(tag) WSPC /*) /*< */ 12 | 13 | #define OTAG(tag) LT(tag) GT /* */ 14 | #define OTAGA(tag,attributes) LTA(tag,attributes) GT /* */ 15 | #define CTAG(tag) STR( */ 16 | 17 | #define ESTAG(tag) LT(tag) WSPC STR(/) GT /* */ 18 | #define STAG(tag,attributes) LTA(tag,attributes) WSPC STR(/) GT /* */ 19 | 20 | #define QTAG(tag,text) OTAG(tag) text CTAG(tag) /* text */ 21 | #define QTAGA(tag,attributes,text) OTAGA(tag,attributes) text CTAG(tag) /* text */ 22 | 23 | /* Extensions */ 24 | #define QLINK(url,text) QTAGA(a,href=url,text) 25 | #define QLINKA(url,attributes,text) QTAGA(a,href=url attributes,text) 26 | #define QIMG(srcurl) STAG(img,src=srcurl) 27 | #define QIMGA(srcurl) STAG(img,src=srcurl attributes) 28 | #define QBR ESTAG(br) 29 | 30 | #define STAGPARAMQ(tag,attributes) LTA(tag,attributes) ATTR(name,STR(q)) WSPC STR(/) GT /* */ 31 | #define QTAGAPARAMQ(tag,attributes,text) OTAGA(tag,attributes name=STR(q)) text CTAG(tag) /* text */ 32 | /* End ENTL */ 33 | 34 | long resPrintf(Response *response, const char *format, ...); 35 | void serveFile(Response *response, const char *filename, const char *displayFilename, 36 | const char *type); 37 | 38 | void sendStatusOKHeadersTypeEncoding(Response *response, const char *type, const char *encoding); 39 | void sendResourceNotFound(Response *response); 40 | 41 | char *resQuickForm(Request *request, Response *response, const char *msg, const char *inputstr); 42 | #define QUICK_FORM_TEXT(request,response,msg) resQuickForm(request,response,msg,STAGPARAMQ(input,type="text")) 43 | 44 | char *getQueryParam(Request *request, const char *name); 45 | char *getQueryPath(Request *request); 46 | bool routeRequest(Request *request, Response * response, const char *path, void (*function) (Request *, Response *)); 47 | long resPuts(Response * response, const char *buffer); 48 | /*Internal stuff follows. Could change in future. Do not use */ 49 | #define STATIC_SEND(_socket, _str) send(_socket, _str, sizeof(_str)-1, 0) 50 | #define API_FLAGS_HEADER_SENT 1 51 | #define API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING API_FLAGS_HEADER_SENT*2 52 | #define API_FLAGS_FORM_ONLY_ON_NULL API_FLAGS_DONT_SET_HEADER_BEFORE_SENDING*2 53 | #endif 54 | --------------------------------------------------------------------------------