├── LICENSE ├── README.md ├── css ├── cssdocument.cpp ├── cssdocument.h ├── cssruleset.cpp └── cssruleset.h ├── html ├── htmldocument.cpp └── htmldocument.h ├── http ├── httpheaders.cpp ├── httpheaders.h ├── httpiodeviceresource.cpp ├── httpiodeviceresource.h ├── httprequest.cpp ├── httprequest.h ├── httpresource.cpp ├── httpresource.h ├── httpresponse.cpp ├── httpresponse.h ├── httpstatuscodes.cpp ├── httpstatuscodes.h ├── httpwebengine.cpp └── httpwebengine.h ├── misc ├── log.cpp ├── log.h ├── logger.cpp ├── logger.h └── threadsafety.h ├── qtwebserver.png ├── qtwebserver.pri ├── qtwebserver.pro ├── sql ├── sqlconnectionpool.cpp └── sqlconnectionpool.h ├── tcp ├── tcpmultithreadedserver.cpp ├── tcpmultithreadedserver.h ├── tcpresponder.h ├── tcpserverthread.cpp └── tcpserverthread.h ├── util ├── utilassetsresource.cpp ├── utilassetsresource.h ├── utildataurlcodec.cpp ├── utildataurlcodec.h ├── utilformurlcodec.cpp └── utilformurlcodec.h ├── weblayout.cpp ├── weblayout.h └── webwidget.h /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9WB9VJA9RGWTN) 2 | 3 | # QtWebServer 4 | 5 | QtWebServer is an attempt to create a high-performance Qt based web application server, ie. a web server that runs native C++/Qt code in order to deliver websites. 6 | 7 | A perfect use-case would be providing a REST API for smaller services. 8 | 9 | ![Concept](https://github.com/cybercatalyst/qtwebserver/blob/master/qtwebserver.png "Concept") 10 | 11 | Within the Qt app, you set up resources and bind them to physical providers, for example files or a database content. A web application object holds information on how to match uri patterns to resources, which again is accessed by a multithreaded tcp server component. The multithreaded server is an extension of Qt's QTcpServer class. 12 | 13 | # Installation and usage 14 | 15 | ```cpp 16 | #include 17 | #include 18 | 19 | #include "tcp/tcpmultithreadedserver.h" 20 | #include "http/httpwebengine.h" 21 | #include "http/httpiodeviceresource.h" 22 | 23 | using namespace QtWebServer; 24 | 25 | int main(int argc, char *argv[]) 26 | { 27 | QCoreApplication a(argc, argv); 28 | 29 | Tcp::MultithreadedServer s; 30 | Http::WebEngine w; 31 | 32 | w.addResource(new Http::IODeviceResource( 33 | "/test", 34 | new QFile("/home/jacob/text.html"))); 35 | 36 | s.setResponder(&w); 37 | s.listen(QHostAddress::Any, 3000); 38 | return a.exec(); 39 | } 40 | ``` 41 | 42 | You can either integrate QtWebServer into your existing application or build a whole standalone web application. There is no distinction between the webserver and the web application, you literally link your web application with your website. 43 | 44 | Installation via qt-pods is perfectly suited for this use-case. You can update your QtWebServer version at any time and switch back flawlessly, since it will be embedded as a git submodule. It is not recommended to plain copy the QtWebServer code into your target application. In order to learn more about qt-pods, see here: 45 | 46 | https://github.com/cybercatalyst/qt-pods 47 | 48 | # License 49 | 50 | Licensed under GNU AGPLv3. Available under a commercial license, too. 51 | -------------------------------------------------------------------------------- /css/cssdocument.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "cssdocument.h" 26 | 27 | namespace QtWebServer { 28 | 29 | namespace Css { 30 | 31 | Document::Document() { 32 | } 33 | 34 | Document::~Document() { 35 | } 36 | 37 | void Document::addRuleSet(RuleSet ruleSet) { 38 | _ruleSets.append(ruleSet); 39 | } 40 | 41 | Document& Document::operator <<(RuleSet ruleSet) { 42 | addRuleSet(ruleSet); 43 | return *this; 44 | } 45 | 46 | QByteArray Document::toByteArray(int indent) { 47 | QByteArray byteArray; 48 | foreach(RuleSet ruleSet, _ruleSets) { 49 | byteArray += ruleSet.toString("", indent).toUtf8() + "\n"; 50 | } 51 | return byteArray; 52 | } 53 | 54 | QString Document::toString(int indent) { 55 | return QString::fromUtf8(toByteArray(indent)); 56 | } 57 | 58 | } // namespace Css 59 | 60 | } // namespace QtWebServer 61 | 62 | -------------------------------------------------------------------------------- /css/cssdocument.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "cssruleset.h" 28 | 29 | // Qt includes 30 | namespace QtWebServer { 31 | 32 | namespace Css { 33 | 34 | class Document { 35 | public: 36 | Document(); 37 | ~Document(); 38 | 39 | void addRuleSet(RuleSet ruleSet); 40 | 41 | Document& operator <<(RuleSet ruleSet); 42 | 43 | QByteArray toByteArray(int indent = 4); 44 | QString toString(int indent = 4); 45 | 46 | private: 47 | QList _ruleSets; 48 | }; 49 | 50 | } // namespace Css 51 | 52 | } // namespace QtWebServer 53 | -------------------------------------------------------------------------------- /css/cssruleset.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "cssruleset.h" 26 | 27 | // Qt includes 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Css { 33 | 34 | RuleSet::RuleSet() : 35 | _element("*") { 36 | } 37 | 38 | RuleSet::RuleSet(QString block, 39 | QString element, 40 | QString modifier, 41 | bool isWrapper) : 42 | _block(block), 43 | _element(element), 44 | _modifier(modifier), 45 | _isWrapper(isWrapper) { 46 | } 47 | 48 | RuleSet::~RuleSet() { 49 | } 50 | 51 | QString RuleSet::block() { 52 | return _block; 53 | } 54 | 55 | void RuleSet::setBlock(QString block) { 56 | _block = block; 57 | } 58 | 59 | QString RuleSet::element() { 60 | return _element; 61 | } 62 | 63 | void RuleSet::setElement(QString selector) { 64 | _element = selector.trimmed(); 65 | } 66 | 67 | QString RuleSet::modifier() { 68 | return _modifier; 69 | } 70 | 71 | void RuleSet::setModifier(QString modifier) { 72 | _modifier = modifier; 73 | } 74 | 75 | bool RuleSet::isWrapper() { 76 | return _isWrapper; 77 | } 78 | 79 | void RuleSet::setWrapper(bool isWrapper) { 80 | _isWrapper = isWrapper; 81 | } 82 | 83 | void RuleSet::addDeclaration(QString property, 84 | QString value) { 85 | _declarations.insert(property, value); 86 | } 87 | 88 | void RuleSet::addDeclarations(QString declarations) { 89 | QStringList splitDeclarations = declarations.split(";", QString::SkipEmptyParts); 90 | foreach(QString declaration, splitDeclarations) { 91 | if(declaration.contains(':')) { 92 | declaration = declaration.trimmed(); 93 | int colonPosition = declaration.indexOf(':'); 94 | 95 | _declarations.insert(declaration.left(colonPosition), 96 | declaration.right(declaration.length() 97 | - colonPosition - 1)); 98 | } 99 | } 100 | } 101 | 102 | void RuleSet::addChild(RuleSet ruleSet) { 103 | _children.append(ruleSet); 104 | } 105 | 106 | QString RuleSet::toString(QString parentSelector, 107 | int indent) { 108 | 109 | QString cssSelector = QString("%1.%2%3%4%5") 110 | .arg(parentSelector) 111 | .arg(_block.isEmpty() ? "" : QString("%1__").arg(_block)) 112 | .arg(_isWrapper ? "wrap__" : "") 113 | .arg(_element) 114 | .arg(_modifier.isEmpty() ? "" : QString("--%1").arg(_modifier)); 115 | 116 | QString indentString; 117 | indentString.fill(' ', indent); 118 | 119 | QString result = cssSelector + " {\n"; 120 | 121 | QStringList properties = _declarations.keys(); 122 | properties.sort(); 123 | foreach(QString property, properties) { 124 | result += QString("%1%2: %3;\n") 125 | .arg(indentString) 126 | .arg(property) 127 | .arg(_declarations.value(property)); 128 | } 129 | 130 | result += QString("}\n"); 131 | 132 | foreach(RuleSet ruleSet, _children) { 133 | result += "\n"; 134 | result += ruleSet.toString(cssSelector, 135 | indent); 136 | } 137 | 138 | return result; 139 | } 140 | 141 | RuleSet& RuleSet::operator <<(QString declaration) { 142 | addDeclarations(declaration); 143 | return *this; 144 | } 145 | 146 | RuleSet& RuleSet::operator <<(RuleSet ruleSet) { 147 | addChild(ruleSet); 148 | return *this; 149 | } 150 | 151 | } // namespace Css 152 | 153 | } // namespace QtWebServer 154 | -------------------------------------------------------------------------------- /css/cssruleset.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | #include 30 | 31 | namespace QtWebServer { 32 | 33 | namespace Css { 34 | 35 | class RuleSet { 36 | public: 37 | RuleSet(); 38 | RuleSet(QString block = "", 39 | QString element = "*", 40 | QString modifier = "", 41 | bool isWrapper = false); 42 | ~RuleSet(); 43 | 44 | QString block(); 45 | void setBlock(QString block); 46 | 47 | QString element(); 48 | void setElement(QString element); 49 | 50 | QString modifier(); 51 | void setModifier(QString modifier); 52 | 53 | bool isWrapper(); 54 | void setWrapper(bool isWrapper); 55 | 56 | void addDeclaration(QString property, QString value); 57 | void addDeclarations(QString declarations); 58 | void addChild(RuleSet ruleSet); 59 | 60 | QString toString(QString parentSelector = "", 61 | int indent = 4); 62 | 63 | RuleSet& operator <<(QString declaration); 64 | RuleSet& operator <<(RuleSet ruleSet); 65 | 66 | private: 67 | QString _block; 68 | QString _element; 69 | QString _modifier; 70 | bool _isWrapper; 71 | 72 | QMap _declarations; 73 | 74 | QList _children; 75 | }; 76 | 77 | } // namespace Css 78 | 79 | } // namespace QtWebServer 80 | -------------------------------------------------------------------------------- /html/htmldocument.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "htmldocument.h" 26 | 27 | // Qt includes 28 | #include 29 | #include 30 | 31 | namespace QtWebServer { 32 | 33 | namespace Html { 34 | 35 | Document::Document(QString documentTypeDeclaration) 36 | : QDomDocument() { 37 | setContent(documentTypeDeclaration); 38 | 39 | _html = createElement("html"); 40 | _head = createElement("head"); 41 | _body = createElement("body"); 42 | QDomElement titleElement = createElement("title"); 43 | _title = createTextNode("Page title"); 44 | titleElement.appendChild(_title); 45 | 46 | _html.appendChild(_head); 47 | _html.appendChild(_body); 48 | _head.appendChild(titleElement); 49 | appendChild(_html); 50 | } 51 | 52 | Document::~Document() { 53 | } 54 | 55 | void Document::setTitle(QString title) { 56 | _title.setNodeValue(title); 57 | } 58 | 59 | QString Document::title() { 60 | return _title.nodeValue(); 61 | } 62 | 63 | QDomElement Document::html() { 64 | return _html; 65 | } 66 | 67 | QDomElement Document::head() { 68 | return _head; 69 | } 70 | 71 | QDomElement Document::body() { 72 | return _body; 73 | } 74 | 75 | bool Document::appendPartial(QDomElement domElement, QString resourceName) { 76 | QFile partialFile(resourceName); 77 | partialFile.open(QFile::ReadOnly); 78 | if(partialFile.isOpen()) { 79 | bool success = appendHtml(domElement, partialFile.readAll()); 80 | partialFile.close(); 81 | return success; 82 | } 83 | return false; 84 | } 85 | 86 | bool Document::appendHtml(QDomElement domElement, QString html) { 87 | QDomDocument domDocument; 88 | bool parseHtml = domDocument.setContent(html); 89 | 90 | if(!parseHtml) { 91 | return false; 92 | } 93 | 94 | // From the Qt documentation on appendChild: 95 | // Returns a new reference to newChild on success or a null node on failure. 96 | return !domElement.appendChild(domDocument.documentElement()).isNull(); 97 | } 98 | 99 | QList Document::elementsByClass(QString className) const { 100 | return elementsByAttribute("class", className); 101 | } 102 | 103 | QList Document::elementsByClass(QDomElement domElement, QString className) const { 104 | return elementsByAttribute(domElement, "class", className); 105 | } 106 | 107 | QDomElement Document::elementById(QString idName) const { 108 | QList elements = elementsById(idName); 109 | if(elements.count() > 0) { 110 | return elements.at(0); 111 | } 112 | return QDomElement(); 113 | } 114 | 115 | QList Document::elementsById(QString idName) const { 116 | return elementsByAttribute("id", idName); 117 | } 118 | 119 | QList Document::elementsById(QDomElement domElement, QString idName) const { 120 | return elementsByAttribute(domElement, "id", idName); 121 | } 122 | 123 | QList Document::elementsByAttribute(QString attributeName, 124 | QString attributeValue, 125 | bool allowMultipleValues) const { 126 | return elementsByAttribute(documentElement(), 127 | attributeName, 128 | attributeValue, 129 | allowMultipleValues); 130 | 131 | } 132 | 133 | QList Document::elementsByAttribute(QDomElement domElement, 134 | QString attributeName, 135 | QString attributeValue, 136 | bool allowMultipleValues) const { 137 | QList elementList; 138 | 139 | if(domElement.hasAttribute(attributeName)) { 140 | QString elementAttributeValue = domElement.attribute(attributeName, ""); 141 | 142 | if(allowMultipleValues) { 143 | QStringList elementAttributeValues = elementAttributeValue.split("\\s+", QString::SkipEmptyParts); 144 | if(elementAttributeValues.contains(attributeValue)) { 145 | elementList.append(domElement); 146 | } 147 | } else { 148 | if(attributeValue == elementAttributeValue) { 149 | elementList.append(domElement); 150 | } 151 | } 152 | } 153 | 154 | QDomNodeList children = domElement.childNodes(); 155 | int count = children.count(); 156 | for(int i = 0; i < count; i++) { 157 | QDomNode child = children.item(i); 158 | if(child.isElement()) { 159 | elementList << elementsByAttribute(child.toElement(), 160 | attributeName, 161 | attributeValue, 162 | allowMultipleValues); 163 | } 164 | } 165 | 166 | return elementList; 167 | } 168 | 169 | } // namespace Html 170 | 171 | } // namespace QtWebServer 172 | -------------------------------------------------------------------------------- /html/htmldocument.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Html { 33 | 34 | /** 35 | * Html document. This extends Qt's default QDomDocument by some 36 | * useful methods. 37 | */ 38 | class Document : 39 | public QDomDocument { 40 | public: 41 | Document(QString documentTypeDeclaration = ""); 42 | ~Document(); 43 | 44 | /** Sets the title element's value. */ 45 | void setTitle(QString title); 46 | 47 | /** @returns the title element's value. */ 48 | QString title(); 49 | 50 | /** @returns the html DOM element. */ 51 | QDomElement html(); 52 | /** @returns the head DOM element. */ 53 | QDomElement head(); 54 | /** @returns the body DOM element. */ 55 | QDomElement body(); 56 | 57 | /** 58 | * Appends a partial to the specific element in the DOM tree. 59 | * @param domElement The element that this partial will be added to. 60 | * @param resourceName The physical resource name. 61 | * @returns true, if the partial could be appended. 62 | */ 63 | bool appendPartial(QDomElement domElement, QString resourceName); 64 | 65 | /** 66 | * Parses and append the given HTML to the DOM. 67 | * @param domElement The DOM element the parsed HTML shall be added to. 68 | * @param html The html code that shall be added. 69 | * @returns true, if the html code could be appended. 70 | */ 71 | bool appendHtml(QDomElement domElement, QString html); 72 | 73 | /** 74 | * Search the document recursively for the given class. For performance 75 | * reasons, always try to use the version that operates on a DOM subtree. 76 | * @param className The class name to search for. 77 | * @returns a list of matching elements. 78 | */ 79 | QList elementsByClass(QString className) const; 80 | 81 | /** Like elementsByClass(), but operations on a DOM subtree. */ 82 | QList elementsByClass(QDomElement domElement, QString className) const; 83 | 84 | /** @returns the first occurrence of an element with the given id attribute. */ 85 | QDomElement elementById(QString idName) const; 86 | 87 | /** 88 | * Search the document recursively for the given id. For performance 89 | * reasons, always try to use the version that operates on a DOM subtree. 90 | * @param idName The id name to search for. 91 | * @returns a list of matching elements. 92 | */ 93 | QList elementsById(QString idName) const; 94 | 95 | /** Like elementsById(), but operations on a DOM subtree. */ 96 | QList elementsById(QDomElement domElement, QString idName) const; 97 | 98 | /** 99 | * Search the document recursively for an attribute. For performance 100 | * reasons, always try to use the version that operates on a DOM subtree. 101 | * @param attributeName The attribute's name. 102 | * @param attributeValue The attribute's value. 103 | * @paramt allowMultipleValues Indicates the the attribute may contain multiple values. 104 | */ 105 | QList elementsByAttribute(QString attributeName, 106 | QString attributeValue, 107 | bool allowMultipleValues = true) const; 108 | 109 | /** Like elementsByAttribute(), but operations on a DOM subtree. */ 110 | QList elementsByAttribute(QDomElement domElement, 111 | QString attributeName, 112 | QString attributeValue, 113 | bool allowMultipleValues = true) const; 114 | private: 115 | QDomElement _html, _head, _body; 116 | QDomText _title; 117 | }; 118 | 119 | } // namespace Html 120 | 121 | } // namespace QtWebServer 122 | -------------------------------------------------------------------------------- /http/httpheaders.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "httpheaders.h" 26 | 27 | namespace QtWebServer { 28 | 29 | namespace Http { 30 | 31 | HeaderNamePair headerNameMap[HEADER_COUNT] = { 32 | {CacheControl, "Cache-Control"}, 33 | {Connection, "Connection"}, 34 | {ContentLength, "Content-Length"}, 35 | {ContentMD5, "Content-MD5"}, 36 | {ContentType, "Content-Type"}, 37 | {Date, "Date"}, 38 | {Pragma, "Pragma"}, 39 | {TransferEncoding, "Transfer-Encoding"}, 40 | {Via, "Via"}, 41 | {Warning, "Warning"}, 42 | 43 | {Accept, "Accept"}, 44 | {AcceptCharset, "Accept-Charset"}, 45 | {AcceptEncoding, "Accept-Encoding"}, 46 | {AcceptLanguage, "Accept-Language"}, 47 | {Authorization, "Authorization"}, 48 | {Cookie, "Cookie"}, 49 | {Expect, "Expect"}, 50 | {From, "From"}, 51 | {Host, "Host"}, 52 | {IfMatch, "If-Match"}, 53 | {IfModifiedSince, "If-Modified-Since"}, 54 | {IfNoneMatch, "If-None-Match"}, 55 | {IfRange, "If-Range"}, 56 | {IfUnmodifiedSince, "If-Unmodified-Since"}, 57 | {MaxForwards, "Max-Forwards"}, 58 | {ProxyAuthorization, "Proxy-Authorization"}, 59 | {Range, "Range"}, 60 | {Referer, "Referer"}, 61 | {TE, "TE"}, 62 | {Upgrade, "Upgrade"}, 63 | {UserAgent, "User-Agent"}, 64 | 65 | {AcceptRanges, "Accept-Ranges"}, 66 | {Age, "Age"}, 67 | {Allow, "Allow"}, 68 | {ContentEncoding, "Content-Encoding"}, 69 | {ContentLanguage, "Content-Language"}, 70 | {ContentLocation, "Content-Location"}, 71 | {ContentDisposition, "Content-Disposition"}, 72 | {ContentRange, "Content-Range"}, 73 | {ContentSecurityPolicy, "Content-Security-Policy"}, 74 | {ETag, "ETag"}, 75 | {Expires, "Expires"}, 76 | {LastModified, "Last-Modified"}, 77 | {Link, "Link"}, 78 | {Location, "Location"}, 79 | {P3P, "P3P"}, 80 | {ProxyAuthenticate, "Proxy-Authenticate"}, 81 | {Refresh, "Refresh"}, 82 | {RetryAfter, "Retry-After"}, 83 | {Server, "Server"}, 84 | {SetCookie, "Set-Cookie"}, 85 | {Trailer, "Trailer"}, 86 | {Vary, "Vary"}, 87 | {WWWAuthenticate, "WWW-Authenticate"} 88 | }; 89 | 90 | QString headerName(Http::Header header) { 91 | for(int i = 0; i < HEADER_COUNT; i++) { 92 | if(headerNameMap[i].header == header) { 93 | return headerNameMap[i].headerName; 94 | } 95 | } 96 | return ""; 97 | } 98 | 99 | } // namespace Http 100 | 101 | } // namespace QtWebServer 102 | -------------------------------------------------------------------------------- /http/httpheaders.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Http { 33 | 34 | /** 35 | * @brief The Header enum 36 | */ 37 | enum Header { 38 | // Request and response headers 39 | CacheControl, 40 | Connection, 41 | ContentLength, 42 | ContentMD5, 43 | ContentType, 44 | Date, 45 | Pragma, 46 | TransferEncoding, 47 | Via, 48 | Warning, 49 | 50 | // Request headers 51 | Accept, 52 | AcceptCharset, 53 | AcceptEncoding, 54 | AcceptLanguage, 55 | Authorization, 56 | Cookie, 57 | Expect, 58 | From, 59 | Host, 60 | IfMatch, 61 | IfModifiedSince, 62 | IfNoneMatch, 63 | IfRange, 64 | IfUnmodifiedSince, 65 | MaxForwards, 66 | ProxyAuthorization, 67 | Range, 68 | Referer, 69 | TE, 70 | Upgrade, 71 | UserAgent, 72 | 73 | // Response headers 74 | AcceptRanges, 75 | Age, 76 | Allow, 77 | ContentEncoding, 78 | ContentLanguage, 79 | ContentLocation, 80 | ContentDisposition, 81 | ContentRange, 82 | ContentSecurityPolicy, 83 | ETag, 84 | Expires, 85 | LastModified, 86 | Link, 87 | Location, 88 | P3P, 89 | ProxyAuthenticate, 90 | Refresh, 91 | RetryAfter, 92 | Server, 93 | SetCookie, 94 | Trailer, 95 | Vary, 96 | WWWAuthenticate 97 | }; 98 | 99 | typedef struct { 100 | Header header; 101 | const char* headerName; 102 | } HeaderNamePair; 103 | 104 | #define HEADER_COUNT 54 105 | 106 | extern HeaderNamePair headerNameMap[HEADER_COUNT]; 107 | 108 | QString headerName(Http::Header header); 109 | 110 | } // namespace Http 111 | 112 | } // namespace QtWebServer 113 | 114 | -------------------------------------------------------------------------------- /http/httpiodeviceresource.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "httpiodeviceresource.h" 26 | 27 | namespace QtWebServer { 28 | 29 | namespace Http { 30 | 31 | IODeviceResource::IODeviceResource(QString uniqueIdentifier, 32 | QIODevice *ioDevice, 33 | QObject *parent) : 34 | Resource(uniqueIdentifier, parent), 35 | _ioDevice(ioDevice) { 36 | if(_ioDevice) { 37 | _ioDevice->setParent(this); 38 | } 39 | 40 | setContentType("text/plain"); 41 | } 42 | 43 | IODeviceResource::~IODeviceResource() { 44 | } 45 | 46 | void IODeviceResource::deliver(const Http::Request& request, Response& response) { 47 | if(!_ioDevice) { 48 | return; 49 | } 50 | 51 | if(request.method() == "get") { 52 | response.setHeader(Http::ContentType, contentType()); 53 | 54 | _ioDevice->open(QIODevice::ReadOnly); 55 | if(_ioDevice->isOpen()) { 56 | response.setBody(_ioDevice->readAll()); 57 | _ioDevice->close(); 58 | response.setStatusCode(Ok); 59 | } else { 60 | response.setBody(""); 61 | response.setStatusCode(Forbidden); 62 | } 63 | } 64 | } 65 | 66 | } // Http 67 | 68 | } // QtWebServer 69 | -------------------------------------------------------------------------------- /http/httpiodeviceresource.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "httpresource.h" 28 | 29 | // Qt includes 30 | #include 31 | 32 | namespace QtWebServer { 33 | 34 | namespace Http { 35 | 36 | /** 37 | * @class IODeviceResource 38 | * @author Jacob Dawid 39 | * Links a resource with an io device, for example a QFile. 40 | */ 41 | class IODeviceResource : 42 | public Resource { 43 | Q_OBJECT 44 | public: 45 | IODeviceResource(QString uniqueIdentifier, 46 | QIODevice *ioDevice, 47 | QObject *parent = 0); 48 | ~IODeviceResource(); 49 | 50 | virtual void deliver(const Request& request, Response& response); 51 | 52 | private: 53 | QIODevice *_ioDevice; 54 | }; 55 | 56 | } // Http 57 | 58 | } // QtWebServer 59 | -------------------------------------------------------------------------------- /http/httprequest.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "httprequest.h" 26 | #include "util/utilformurlcodec.h" 27 | 28 | // Qt includes 29 | #include 30 | 31 | namespace QtWebServer { 32 | 33 | namespace Http { 34 | 35 | Request::Request() 36 | : Logger("WebServer::Http::Request") { 37 | setDefaults(); 38 | } 39 | 40 | Request::Request(const QByteArray &rawRequest) 41 | : Logger("WebServer::Http::Request") { 42 | setDefaults(); 43 | deserialize(rawRequest); 44 | } 45 | 46 | bool Request::isValid() const { 47 | return _valid; 48 | } 49 | 50 | QString Request::method() const { 51 | return _method; 52 | } 53 | 54 | QString Request::uniqueResourceIdentifier() const { 55 | return _uniqueResourceIdentifier; 56 | } 57 | 58 | QString Request::version() const { 59 | return _version; 60 | } 61 | 62 | QMap Request::urlParameters() const { 63 | return _urlParameters; 64 | } 65 | 66 | QMap Request::headers() const { 67 | return _headers; 68 | } 69 | 70 | QString Request::header(Header header) const { 71 | return this->header(headerName(header)); 72 | } 73 | 74 | QString Request::header(QString headerName) const { 75 | return _headers.value(headerName); 76 | } 77 | 78 | QByteArray Request::body() const { 79 | return _body; 80 | } 81 | 82 | void Request::appendBodyData(QByteArray bodyData) { 83 | _body.append(bodyData); 84 | } 85 | 86 | bool Request::isComplete() const { 87 | if(_headers.contains(headerName(ContentLength))) { 88 | bool contentLengthValid = false; 89 | long long contentLength = _headers.value(headerName(ContentLength)).toLongLong(&contentLengthValid); 90 | if(contentLengthValid) { 91 | return _body.count() == contentLength; 92 | } 93 | } 94 | 95 | // TODO: Chunked transfer mode here. 96 | 97 | // If there is nothing indicating the content length 98 | // and no information about chunked transfer mode then 99 | // we have to assume the requesrespondt is complete 100 | return true; 101 | } 102 | 103 | QByteArray Request::takeLine(QByteArray& rawRequest) { 104 | // Lines in the HTTP protocol are defined to be separated by '\r\n' 105 | QByteArray line; 106 | int rawSize = rawRequest.size(); 107 | int rawPosition; 108 | 109 | // Watch out for the first occurrence of '\r' 110 | for(rawPosition = 0; rawPosition < rawSize - 1; rawPosition++) { 111 | if(rawRequest[rawPosition] == '\r' && rawRequest[rawPosition + 1] == '\n') { 112 | break; 113 | } 114 | } 115 | 116 | // If there is just two characters left, this must be EOF 117 | if(rawPosition != rawSize - 2) { 118 | // Get the line contents 119 | line = rawRequest.left(rawPosition); 120 | 121 | // Get the remaining data, skipping '\r\n' 122 | rawRequest = rawRequest.right(rawSize - line.count() - 2); 123 | } else { 124 | // EOF 125 | rawRequest = ""; 126 | line = rawRequest; 127 | } 128 | 129 | return line; 130 | } 131 | 132 | void Request::setDefaults() { 133 | _headers.clear(); 134 | _urlParameters.clear(); 135 | _valid = false; 136 | _method = ""; 137 | _uniqueResourceIdentifier = ""; 138 | _version = ""; 139 | _body = ""; 140 | } 141 | 142 | void Request::deserialize(QByteArray rawRequest) { 143 | // Read ahead the first line in the request 144 | QByteArray rawRequestLine = takeLine(rawRequest); 145 | QStringList requestLine = QString::fromUtf8(rawRequestLine) 146 | .split(QRegExp("\\s+")); 147 | 148 | if(requestLine.count() < 3) { 149 | // The request line has to contain three strings: The method 150 | // string, the request uri and the HTTP version. If we were 151 | // strict, we shouldn't even accept anything larger than four 152 | // strings, but we're permissive here. 153 | return; 154 | } 155 | 156 | _method = requestLine.at(0).toLower(); 157 | 158 | QStringList splittedURI = requestLine.at(1).split('?', QString::SkipEmptyParts); 159 | if(splittedURI.count() > 1) { 160 | _urlParameters = Util::FormUrlCodec::decodeFormUrl(splittedURI.at(1).toUtf8()); 161 | } 162 | 163 | _uniqueResourceIdentifier = splittedURI.at(0); 164 | 165 | _version = requestLine.at(2); 166 | 167 | QByteArray nextLine; 168 | while(!(nextLine = takeLine(rawRequest)).isEmpty()) { 169 | deserializeHeader(nextLine); 170 | } 171 | 172 | // By definition, all that follows after a \r\n\r\n is the body of the request. 173 | _body = QByteArray(rawRequest); 174 | _valid = true; 175 | } 176 | 177 | void Request::deserializeHeader(const QByteArray& rawHeader) { 178 | QString headerLine = QString::fromUtf8(rawHeader); 179 | int colonPosition; 180 | int headerLineLength = headerLine.count(); 181 | for(colonPosition = 0; colonPosition < headerLineLength; colonPosition++) { 182 | if(headerLine.at(colonPosition) == ':') { 183 | break; 184 | } 185 | } 186 | 187 | if(colonPosition == headerLineLength) { 188 | log(QString("Invalid header line found %1").arg(headerLine), Log::Warning); 189 | return; 190 | } 191 | 192 | QString headerName = headerLine.left(colonPosition); 193 | QString headerValue = headerLine.right(headerLineLength - colonPosition - 1).trimmed(); 194 | _headers.insert(headerName, headerValue); 195 | } 196 | 197 | } // namespace Http 198 | 199 | } // namespace QtWebServer 200 | -------------------------------------------------------------------------------- /http/httprequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "httpheaders.h" 28 | 29 | #include "misc/logger.h" 30 | 31 | // Qt includes 32 | #include 33 | #include 34 | 35 | namespace QtWebServer { 36 | 37 | namespace Http { 38 | 39 | /** 40 | * @class Request 41 | * @author Jacob Dawid 42 | * Basic HTTP request class. Parses a raw HTTP request and splits it into its 43 | * single components. 44 | */ 45 | class Request : 46 | public Logger { 47 | public: 48 | Request(); 49 | Request(const QByteArray& rawRequest); 50 | 51 | /** 52 | * This method is used to indicate whether a request could not be 53 | * interpreted correctly. You are supposed to check this first before 54 | * using any other methods. 55 | * @returns true, if the request has been valid, false otherwise. 56 | */ 57 | bool isValid() const; 58 | 59 | /** @returns the method for this request. */ 60 | QString method() const; 61 | 62 | /** @returns the URI for this request. */ 63 | QString uniqueResourceIdentifier() const; 64 | 65 | /** @returns the HTTP version for this request. */ 66 | QString version() const; 67 | 68 | /** @returns url parameters. */ 69 | QMap urlParameters() const; 70 | 71 | /** @returns a map of request headers (name and value). **/ 72 | QMap headers() const; 73 | 74 | QString header(Header header) const; 75 | QString header(QString headerName) const; 76 | 77 | /** @returns the body of the request. */ 78 | QByteArray body() const; 79 | 80 | void appendBodyData(QByteArray bodyData); 81 | 82 | /** 83 | * Determines whether the request is complete either based 84 | * on the content length or when all chunks have been transmitted 85 | */ 86 | bool isComplete() const; 87 | 88 | private: 89 | void setDefaults(); 90 | void deserialize(QByteArray rawRequest); 91 | void deserializeHeader(const QByteArray& rawHeader); 92 | QByteArray takeLine(QByteArray& rawRequest); 93 | 94 | QByteArray _body; 95 | QString _method; 96 | QString _uniqueResourceIdentifier; 97 | QString _version; 98 | bool _valid; 99 | QMap _urlParameters; 100 | QMap _headers; 101 | }; 102 | 103 | } 104 | 105 | } // namespace QtWebServer 106 | 107 | -------------------------------------------------------------------------------- /http/httpresource.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "httpresource.h" 26 | 27 | // Qt includes 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Http { 33 | 34 | Resource::Resource(QString uniqueIdentifier, 35 | QObject *parent) : 36 | QObject(parent) { 37 | _uniqueIdentifier = uniqueIdentifier; 38 | } 39 | 40 | bool Resource::match(QString uniqueIdentifier) { 41 | // Split both the unique identifier of this resource the one in question, 42 | // so we can compare those. 43 | QStringList splittedReferenceUri = this->uniqueIdentifier().split("/", QString::SkipEmptyParts); 44 | QStringList splittedRequestedUri = uniqueIdentifier.split("/", QString::SkipEmptyParts); 45 | 46 | int count = splittedRequestedUri.count(); 47 | 48 | // In case we have a different depth, the unique identifiers cannot match. 49 | if(splittedReferenceUri.count() != count) { 50 | return false; 51 | } 52 | 53 | // Compare each part of the passed unique identifier. 54 | for(int depth = 0; depth < count; depth++) { 55 | // In case we have a variable, we do not need an exact match. 56 | if(splittedReferenceUri.at(depth).startsWith("{") && splittedReferenceUri.at(depth).endsWith("}")) { 57 | continue; 58 | } 59 | 60 | // Otherwise, we expect the unique idenfier parts to match exactly. 61 | if(splittedReferenceUri.at(depth) != splittedRequestedUri.at(depth)) { 62 | return false; 63 | } 64 | } 65 | 66 | return true; 67 | } 68 | 69 | QMap Resource::uriParameters(QString uniqueIdentifier) { 70 | // Split both the unique identifier of this resource the one in question, 71 | // so we can compare those. 72 | QStringList splittedReferenceUri = this->uniqueIdentifier().split("/", QString::SkipEmptyParts); 73 | QStringList splittedRequestedUri = uniqueIdentifier.split("/", QString::SkipEmptyParts); 74 | 75 | // Create a parameter map. 76 | QMap uriParameterMap; 77 | 78 | int count = splittedRequestedUri.count(); 79 | 80 | // In case we have a different depth, the unique identifiers cannot match. 81 | if(splittedReferenceUri.count() != count) { 82 | return uriParameterMap; 83 | } 84 | 85 | // Compare each part of the passed unique identifier. 86 | for(int depth = 0; depth < count; depth++) { 87 | QString uriSegment = splittedReferenceUri.at(depth); 88 | if(uriSegment.startsWith("{") && uriSegment.endsWith("}")) { 89 | // Truncate the { and } 90 | uriSegment = uriSegment.mid(1, uriSegment.count() - 2); 91 | QString key = uriSegment; 92 | QString value = splittedRequestedUri.at(depth); 93 | uriParameterMap.insert(key, value); 94 | } 95 | } 96 | 97 | return uriParameterMap; 98 | } 99 | 100 | 101 | QString Resource::uniqueIdentifier() { 102 | return _uniqueIdentifier.r(); 103 | } 104 | 105 | void Resource::setUniqueIdentifier(QString uniqueIdentifer) { 106 | _uniqueIdentifier = uniqueIdentifer; 107 | } 108 | 109 | QString Resource::contentType() { 110 | return _contentType.r(); 111 | } 112 | 113 | void Resource::setContentType(QString contentType) { 114 | _contentType = contentType; 115 | } 116 | 117 | } // namespace Http 118 | 119 | } // namespace QtWebServer 120 | -------------------------------------------------------------------------------- /http/httpresource.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "misc/threadsafety.h" 28 | #include "httprequest.h" 29 | #include "httpresponse.h" 30 | 31 | // Qt includes 32 | #include 33 | #include 34 | 35 | namespace QtWebServer { 36 | 37 | namespace Http { 38 | 39 | /** 40 | * @class Resource 41 | * Basic class for a HTTP resource. A resource is an abstract concept of an 42 | * endpoint reachable by an unique resource identifier (URI, in short). 43 | * Within QtWebServer the HTTP resource defines the response behaviour, ie. 44 | * you are supposed to subclass this class and reimplement its virtual methods. 45 | */ 46 | class Resource : 47 | public QObject { 48 | Q_OBJECT 49 | public: 50 | Resource(QString uniqueIdentifier, 51 | QObject *parent = 0); 52 | 53 | /** 54 | * Resource matching method. The default implementation matches 55 | * the unique identifier against a template that allows variable uris. 56 | * 57 | * @attention: This method may be called from multiple threads. You are 58 | * not allowed to perform any operations that are not threadsafe. 59 | */ 60 | virtual bool match(QString uniqueIdentifier); 61 | 62 | /** 63 | * Parses the passed unique identifier and returns a map of uri parameters. 64 | * @param uniqueIdentifier The unique identifier to parse. 65 | * @returns a map of uri parameters parsed from the give identifier. 66 | */ 67 | QMap uriParameters(QString uniqueIdentifier); 68 | 69 | /** 70 | * The default uri matcher ignores uri parts embraced with "{" and "}", 71 | * so you can refer to them as uri paramters later. For example: 72 | * /service/{account}/{id} 73 | * will match 74 | * /service/user1/23 75 | * /service/user4/29 76 | * @returns the unique resource identifier for this resource. 77 | */ 78 | QString uniqueIdentifier(); 79 | 80 | /** 81 | * Sets the unique resource identifier for this resource. 82 | * @param uniqueIdentifer 83 | */ 84 | void setUniqueIdentifier(QString uniqueIdentifer); 85 | 86 | /** @returns the resource's content type. */ 87 | QString contentType(); 88 | 89 | /** Sets the content type. */ 90 | void setContentType(QString contentType); 91 | 92 | /** Defines the resource's response behaviour. */ 93 | virtual void deliver(const Http::Request& request, Http::Response& response) = 0; 94 | 95 | private: 96 | ThreadGuard _uniqueIdentifier; 97 | ThreadGuard _contentType; 98 | }; 99 | 100 | } // namespace Http 101 | 102 | } // namespace QtWebServer 103 | -------------------------------------------------------------------------------- /http/httpresponse.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Qt includes 25 | #include 26 | 27 | // Own includes 28 | #include "httpresponse.h" 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Http { 33 | 34 | Response::Response() 35 | : Logger("WebServer::Http::Response") { 36 | _statusCode = Http::Ok; 37 | _body = ""; 38 | } 39 | 40 | QByteArray Response::toByteArray() { 41 | QByteArray response = ""; 42 | 43 | // HTTP response header line. 44 | response += QString("HTTP/1.1 %1 %2\r\n") 45 | .arg(_statusCode) 46 | .arg(Http::reasonPhrase(_statusCode)) 47 | .toUtf8(); 48 | 49 | // Append HTTP headers. 50 | QStringList headerNames = _headers.keys(); 51 | foreach(QString headerName, headerNames) { 52 | response += QString("%1: %2\r\n") 53 | .arg(headerName) 54 | .arg(_headers.value(headerName)) 55 | .toUtf8(); 56 | } 57 | 58 | // Add empty line to mark the end of the header. 59 | response += "\r\n"; 60 | 61 | // Append the response body. 62 | response += _body; 63 | 64 | return response; 65 | } 66 | 67 | Http::StatusCode Response::statusCode() { 68 | return _statusCode; 69 | } 70 | 71 | void Response::setStatusCode(Http::StatusCode statusCode) { 72 | _statusCode = statusCode; 73 | } 74 | 75 | QByteArray Response::body() { 76 | return _body; 77 | } 78 | 79 | void Response::setBody(QByteArray body) { 80 | _body = body; 81 | } 82 | 83 | void Response::setHeader(Header header, QString headerValue) { 84 | setHeader(headerName(header), headerValue); 85 | } 86 | 87 | void Response::setHeader(QString headerName, QString headerValue) { 88 | _headers.insert(headerName, headerValue); 89 | } 90 | 91 | QString Response::header(Header header) const { 92 | return this->header(headerName(header)); 93 | } 94 | 95 | QString Response::header(QString headerName) const { 96 | return _headers.value(headerName); 97 | } 98 | 99 | } // namespace Http 100 | 101 | } // namespace QtWebServer 102 | -------------------------------------------------------------------------------- /http/httpresponse.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "httpheaders.h" 28 | #include "httpstatuscodes.h" 29 | 30 | #include "misc/logger.h" 31 | 32 | // Qt includes 33 | #include 34 | #include 35 | 36 | namespace QtWebServer { 37 | 38 | namespace Http { 39 | /** 40 | * @brief The Response class 41 | * @author Jacob Dawid 42 | * @date 23.11.2013 43 | */ 44 | class Response : public Logger { 45 | public: 46 | /** 47 | * @brief Constructor. 48 | */ 49 | Response(); 50 | 51 | /** 52 | * @brief Converts the response into a byte array. The resulting character 53 | * encoding is determined by the characterEncoding attribute. 54 | * @returns The resulting byte array. 55 | */ 56 | QByteArray toByteArray(); 57 | 58 | /** 59 | * @returns The status code of this response. 60 | */ 61 | Http::StatusCode statusCode(); 62 | 63 | /** 64 | * @brief Sets the status code for this response. The reason phrase will be 65 | * added automatically. 66 | * @param statusCode A HTTP status code. 67 | */ 68 | void setStatusCode(Http::StatusCode statusCode); 69 | 70 | /** 71 | * @returns The response body part. 72 | */ 73 | QByteArray body(); 74 | 75 | /** 76 | * @brief Sets the response body, ie. the actual document transmitted. 77 | * @param body An HTTP response body. 78 | */ 79 | void setBody(QByteArray body); 80 | 81 | /** 82 | * Set header value. 83 | * @param header The HTTP header to be set. 84 | * @param headerValue The HTTP header's value. 85 | */ 86 | void setHeader(Header header, QString headerValue); 87 | 88 | /** 89 | * Set header value. 90 | * @param headerName The HTTP header to be set. 91 | * @param headerValue The HTTP header's value. 92 | */ 93 | void setHeader(QString headerName, QString headerValue); 94 | 95 | /** @returns the value of the specified header. */ 96 | QString header(Header header) const; 97 | 98 | /** @returns the value of the specified header. */ 99 | QString header(QString headerName) const; 100 | 101 | private: 102 | Http::StatusCode _statusCode; 103 | QMap _headers; 104 | QByteArray _body; 105 | }; 106 | 107 | } // Http 108 | 109 | } // namespace QtWebServer 110 | -------------------------------------------------------------------------------- /http/httpstatuscodes.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "httpstatuscodes.h" 26 | 27 | namespace QtWebServer { 28 | 29 | namespace Http { 30 | 31 | ReasonPhrasePair reasonPhrasePairMap[STATUS_CODE_COUNT] = { 32 | {Continue, "Continue"}, 33 | {SwitchingProtocols, "Switching Protocols"}, 34 | 35 | {Ok, "Ok"}, 36 | {Created, "Created"}, 37 | {Accepted, "Accepted"}, 38 | {NonAuthoritativeInformation, "Non-Authoritative Information"}, 39 | {NoContent, "No Content"}, 40 | {ResetContent, "Reset Content"}, 41 | {PartialContent, "Partial Content"}, 42 | 43 | {MultipleChoices, "Multiple Choices"}, 44 | {MovedPermanently, "Moved Permanently"}, 45 | {Found, "Found"}, 46 | {SeeOther, "See Other"}, 47 | {NotModified, "Not Modified"}, 48 | {UseProxy, "Use Proxy"}, 49 | {Unused, "Unused"}, 50 | {TemporaryRedirect, "Temporary Redirect"}, 51 | 52 | {BadRequest, "Bad Request"}, 53 | {Unauthorized, "Unauthorized"}, 54 | {PaymentRequired, "Payment Required"}, 55 | {Forbidden, "Forbidden"}, 56 | {NotFound, "Not Found"}, 57 | {MethodNotAllowed, "Method Not Allowed"}, 58 | {NotAcceptable, "Not Acceptable"}, 59 | {ProxyAuthenticationRequired, "Proxy Authentication Required"}, 60 | {RequestTimeout, "Request Time-out"}, 61 | {Conflict, "Conflict"}, 62 | {Gone, "Gone"}, 63 | {LengthRequired, "Length Required"}, 64 | {PreconditionFailed, "Precondition Failed"}, 65 | {RequestEntityTooLarge, "Request Entity Too Large"}, 66 | {RequestURITooLong, "Request-URI Too Long"}, 67 | {UnsupportedMediaType, "Unsupported Media Type"}, 68 | {RequestedRangeNotSatisfiable, "Requested range not satisfiable"}, 69 | {ExpectationFailed, "Expectation Failed"}, 70 | 71 | {InternalServerError, "Internal Server Error"}, 72 | {NotImplemented, "Not Implemented"}, 73 | {BadGateway, "Bad Gateway"}, 74 | {ServiceUnavailable, "Service Unavailable"}, 75 | {GatewayTimeout, "Gateway Time-out"}, 76 | {HTTPVersionNotSupported, "HTTP Version not supported"} 77 | }; 78 | 79 | QString reasonPhrase(Http::StatusCode statusCode) { 80 | for(int i = 0; i < STATUS_CODE_COUNT; i++) { 81 | if(reasonPhrasePairMap[i].statusCode == statusCode) { 82 | return reasonPhrasePairMap[i].reasonPhrase; 83 | } 84 | } 85 | return ""; 86 | } 87 | 88 | } // namespace Http 89 | 90 | } // namespace QtWebServer 91 | -------------------------------------------------------------------------------- /http/httpstatuscodes.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Http { 33 | 34 | /** 35 | * @brief The StatusCode enum 36 | */ 37 | enum StatusCode { 38 | Continue = 100, 39 | SwitchingProtocols = 101, 40 | 41 | Ok = 200, 42 | Created = 201, 43 | Accepted = 202, 44 | NonAuthoritativeInformation = 203, 45 | NoContent = 204, 46 | ResetContent = 205, 47 | PartialContent = 206, 48 | 49 | MultipleChoices = 300, 50 | MovedPermanently = 301, 51 | Found = 302, 52 | SeeOther = 303, 53 | NotModified = 304, 54 | UseProxy = 305, 55 | Unused = 306, 56 | TemporaryRedirect = 307, 57 | 58 | BadRequest = 400, 59 | Unauthorized = 401, 60 | PaymentRequired = 402, 61 | Forbidden = 403, 62 | NotFound = 404, 63 | MethodNotAllowed = 405, 64 | NotAcceptable = 406, 65 | ProxyAuthenticationRequired = 407, 66 | RequestTimeout = 408, 67 | Conflict = 409, 68 | Gone = 410, 69 | LengthRequired = 411, 70 | PreconditionFailed = 412, 71 | RequestEntityTooLarge = 413, 72 | RequestURITooLong = 414, 73 | UnsupportedMediaType = 415, 74 | RequestedRangeNotSatisfiable= 416, 75 | ExpectationFailed = 417, 76 | 77 | InternalServerError = 500, 78 | NotImplemented = 501, 79 | BadGateway = 502, 80 | ServiceUnavailable = 503, 81 | GatewayTimeout = 504, 82 | HTTPVersionNotSupported = 505 83 | }; 84 | 85 | /** 86 | * @brief ReasonPhrasePair 87 | */ 88 | typedef struct { 89 | StatusCode statusCode; 90 | const char* reasonPhrase; 91 | } ReasonPhrasePair; 92 | 93 | #define STATUS_CODE_COUNT 41 94 | 95 | /** 96 | * @brief reasonPhrasePairMap 97 | */ 98 | extern ReasonPhrasePair reasonPhrasePairMap[STATUS_CODE_COUNT]; 99 | 100 | /** 101 | * @brief reasonPhrase 102 | * @param statusCode 103 | * @return 104 | */ 105 | QString reasonPhrase(Http::StatusCode statusCode); 106 | 107 | } // namespace Http 108 | 109 | } // namespace QtWebServer 110 | 111 | -------------------------------------------------------------------------------- /http/httpwebengine.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "httpwebengine.h" 26 | #include "httprequest.h" 27 | #include "httpresponse.h" 28 | 29 | // Qt includes 30 | #include 31 | #include 32 | #include 33 | 34 | namespace QtWebServer { 35 | 36 | namespace Http { 37 | 38 | WebEngine::WebEngine(QObject *parent) : 39 | QObject(parent), 40 | Responder(), 41 | _notFoundPage(Q_NULLPTR) { 42 | } 43 | 44 | void WebEngine::respond(QSslSocket* sslSocket) { 45 | // Probe if the client awaits an SSL handshake first before reading any 46 | // data. 47 | if(probeAwaitsSslHandshake(sslSocket)) { 48 | // Do not change the following line for security reasons 49 | sslSocket->setProtocol(QSsl::TlsV1_2OrLater); 50 | sslSocket->startServerEncryption(); 51 | return; 52 | } 53 | 54 | // Acquire the socket so we remember it if we should receive more data for 55 | // this request later. 56 | Http::Request httpRequest = acquireSocket(sslSocket); 57 | 58 | // Check if the request is valid and complete. 59 | if(httpRequest.isValid() && httpRequest.isComplete()) { 60 | // Create a response object. 61 | Http::Response httpResponse; 62 | 63 | // Match the unique resource identifier on a resource. 64 | Resource *resource = matchResource(httpRequest.uniqueResourceIdentifier()); 65 | if(resource != 0) { 66 | // If we found a resource, let it deliver the response. 67 | resource->deliver(httpRequest, httpResponse); 68 | } else { 69 | // Otherwise generate a 404. 70 | if (_notFoundPage) { 71 | _notFoundPage->deliver(httpRequest, httpResponse); 72 | } else { 73 | // if the 404 page was not set, generate simple HTML response 74 | httpResponse.setBody(QByteArray("

404 Not found

")); 75 | httpResponse.setHeader(ContentType, "text/html"); 76 | } 77 | httpResponse.setStatusCode(NotFound); 78 | } 79 | 80 | // Write the complete response to the socket. 81 | writeToSocket(sslSocket, httpResponse.toByteArray()); 82 | 83 | // This is kind of weird, but seems to perform a disconnect in 84 | // opposition to close. 85 | sslSocket->disconnectFromHost(); 86 | 87 | // We're done with this request, so release the corresponding socket. 88 | releaseSocket(sslSocket); 89 | } 90 | } 91 | 92 | Http::Request WebEngine::acquireSocket(QSslSocket *sslSocket) { 93 | // The list of pending requests may be accessed from multiple server 94 | // threads, so we have to make sure to lock properly. 95 | MutexLocker mutexLocker(_pendingRequestsMutex); Q_UNUSED(mutexLocker); 96 | 97 | Http::Request httpRequest; 98 | 99 | // Check if we have acquired that socket already. 100 | if(_pendingRequests.contains(sslSocket)) { 101 | // Get the current request in progress. 102 | httpRequest = _pendingRequests.value(sslSocket); 103 | 104 | // Append the data from the socket. 105 | httpRequest.appendBodyData(sslSocket->readAll()); 106 | 107 | // Save back the request in case there is more data to come. 108 | _pendingRequests.insert(sslSocket, httpRequest); 109 | } else { 110 | // Create a completely new request object. 111 | httpRequest = Http::Request(sslSocket->readAll()); 112 | 113 | // Save it in the list of pending requests. 114 | _pendingRequests.insert(sslSocket, httpRequest); 115 | } 116 | return httpRequest; 117 | } 118 | 119 | void WebEngine::releaseSocket(QSslSocket *sslSocket) { 120 | // The list of pending requests may be accessed from multiple server 121 | // threads, so we have to make sure to lock properly. 122 | MutexLocker mutexLocker(_pendingRequestsMutex); Q_UNUSED(mutexLocker); 123 | 124 | // Remove all requests concerning this socket. 125 | _pendingRequests.remove(sslSocket); 126 | } 127 | 128 | void WebEngine::addResource(Resource *resource) { 129 | // The list of pending requests may be accessed from multiple server 130 | // and other threads, so we have to make sure to lock properly. 131 | MutexLocker mutexLocker(_resourcesMutex); Q_UNUSED(mutexLocker); 132 | if(resource == 0) { 133 | return; 134 | } 135 | 136 | resource->setParent(this); 137 | _resources.insert(resource); 138 | } 139 | 140 | void WebEngine::addNotFoundPage(Resource *resource) 141 | { 142 | _notFoundPage = resource; 143 | } 144 | 145 | bool WebEngine::probeAwaitsSslHandshake(QSslSocket *sslSocket) { 146 | // If the connection is already encrypted a handshake doesn't make 147 | // sense 148 | if(sslSocket->isEncrypted()) { 149 | return false; 150 | } 151 | 152 | // Since there is no way to unambigously tell that the data coming 153 | // from a client is unencrypted or not, we try to peek the data and 154 | // see whether we can successfully initiate an SSL handshake. 155 | // If that also fails, the request is probably broken anyways. 156 | QByteArray peekBytes = sslSocket->peek(32768); 157 | Http::Request request(peekBytes); 158 | 159 | // If the data is garbage, it is likely to be encrypted 160 | return !request.isValid(); 161 | } 162 | 163 | Resource *WebEngine::matchResource(QString uniqueResourceIdentifier) { 164 | // The list of pending requests may be accessed from multiple server 165 | // and other threads, so we have to make sure to lock properly. 166 | MutexLocker mutexLocker(_resourcesMutex); Q_UNUSED(mutexLocker); 167 | 168 | foreach(Resource *resource, _resources) { 169 | if(resource->match(uniqueResourceIdentifier)) { 170 | return resource; 171 | } 172 | } 173 | 174 | return 0; 175 | } 176 | 177 | QByteArray WebEngine::readFromSocket(QSslSocket *sslSocket) { 178 | return sslSocket->readAll(); 179 | } 180 | 181 | void WebEngine::writeToSocket(QSslSocket *sslSocket, QByteArray raw) { 182 | int bytesWritten = 0; 183 | int bytesRemaining = 0; 184 | do { 185 | bytesWritten = sslSocket->write(raw); 186 | if(bytesWritten == -1) { 187 | break; 188 | } 189 | raw = raw.right(raw.count() - bytesWritten); 190 | bytesRemaining = raw.count(); 191 | } while(bytesRemaining > 0); 192 | } 193 | 194 | } // namespace Http 195 | 196 | } // namespace QtWebServer 197 | -------------------------------------------------------------------------------- /http/httpwebengine.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "httpresource.h" 28 | #include "tcp/tcpresponder.h" 29 | #include "misc/threadsafety.h" 30 | 31 | // Qt includes 32 | #include 33 | #include 34 | #include 35 | 36 | namespace QtWebServer { 37 | 38 | namespace Http { 39 | 40 | /** 41 | * @class WebEngine 42 | * @author Jacob Dawid 43 | * Web engine that reads and writes data to sockets and manages resources. 44 | */ 45 | class WebEngine : 46 | public QObject, 47 | public Tcp::Responder { 48 | Q_OBJECT 49 | public: 50 | WebEngine(QObject *parent = 0); 51 | 52 | /** 53 | * Reads available data from sockets and responds properly. 54 | * @param sslSocket The socket that shall be responded to. 55 | */ 56 | void respond(QSslSocket *sslSocket); 57 | 58 | /** 59 | * Registers a new resource. 60 | * @param resource The resource to be registered. 61 | */ 62 | void addResource(Resource *resource); 63 | 64 | /** 65 | * Registers error page themplate 66 | * @param resource The resource to be registered. 67 | */ 68 | void addNotFoundPage(Resource *resource); 69 | 70 | private: 71 | /** 72 | * Acquires a socket and keeps it in an internal list for pending reponses, 73 | * if the list does not already contain it. This can be required due to 74 | * several reasons, for example if not all data has been read from the 75 | * socket yet. 76 | * @param sslSocket The socket that shall be kept acquired. 77 | * @returns the actual request. 78 | */ 79 | Http::Request acquireSocket(QSslSocket *sslSocket); 80 | 81 | /** Releases a socket from the internal list. */ 82 | void releaseSocket(QSslSocket *sslSocket); 83 | 84 | /** 85 | * Peeks (ie. reads, but does not remove data from the read buffer) the 86 | * incoming data and tries to determine heuristically, whether the socket 87 | * awaits an SSL handshake. 88 | * @param sslSocket The socket to probe. 89 | * @returns true, when the socket seems to await an SSL handshake. 90 | */ 91 | bool probeAwaitsSslHandshake(QSslSocket *sslSocket); 92 | 93 | /** 94 | * Tries to match a resource from the passed unique resource identifier. 95 | * @param uniqueResourceIdentifier The identifier that shall be matched. 96 | * @returns the first occurrence of a matched resource. 97 | */ 98 | Resource *matchResource(QString uniqueResourceIdentifier); 99 | 100 | /** 101 | * Reads all available data from a socket. 102 | * @param sslSocket The socket to read from. 103 | * @returns the data that has been read. 104 | */ 105 | QByteArray readFromSocket(QSslSocket *sslSocket); 106 | 107 | /** 108 | * Writes all data to the given socket. 109 | * @param sslSocket The socket to write to. 110 | * @param raw The data that shall be written. 111 | */ 112 | void writeToSocket(QSslSocket *sslSocket, QByteArray raw); 113 | 114 | QMap _pendingRequests; 115 | QSet _resources; 116 | 117 | QMutex _pendingRequestsMutex; 118 | QMutex _resourcesMutex; 119 | Resource* _notFoundPage; 120 | }; 121 | 122 | } 123 | 124 | } // namespace QtWebServer 125 | -------------------------------------------------------------------------------- /misc/log.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "log.h" 26 | 27 | // Standard includes 28 | #include 29 | 30 | #include 31 | #include 32 | #include 33 | 34 | namespace QtWebServer { 35 | 36 | QtWebServer::Log* QtWebServer::Log::_instance; 37 | 38 | Log* Log::instance() { 39 | if(!_instance) { 40 | _instance = new Log(); 41 | } 42 | return _instance; 43 | } 44 | 45 | Log::LoggingMode Log::loggingMode() { 46 | return _loggingMode.r(); 47 | } 48 | 49 | void Log::setLoggingMode(Log::LoggingMode loggingMode) { 50 | _loggingMode = loggingMode; 51 | } 52 | 53 | void Log::setLoggingFile(QString logfile) 54 | { 55 | QFile file(logfile); 56 | 57 | if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) 58 | { 59 | qDebug() << "Can`t log to file " << logfile; 60 | exit(EXIT_FAILURE); 61 | } 62 | _logFile = logfile; 63 | } 64 | 65 | void Log::log(QString name, QString message, EntryType entryType) { 66 | if(loggingMode() == LoggingModeNone) { 67 | return; 68 | } 69 | 70 | QString logMessage; 71 | 72 | switch (entryType) { 73 | case Verbose: 74 | logMessage = "V: ["+name+"] "+message; 75 | break; 76 | case Information: 77 | logMessage = "I: ["+name+"] "+message; 78 | break; 79 | case Warning: 80 | logMessage = "W: ["+name+"] "+message; 81 | break; 82 | case Error: 83 | logMessage = "E: ["+name+"] "+message; 84 | break; 85 | } 86 | 87 | if(loggingMode() == LoggingModeConsole) 88 | { 89 | std::cout << logMessage.toStdString() << std::endl; 90 | } 91 | 92 | if(loggingMode() == LoggingToDebug) 93 | { 94 | qDebug() << logMessage; 95 | } 96 | 97 | if(loggingMode() == LoggingToFile) 98 | { 99 | QFile logFile(_logFile); 100 | if(logFile.open(QIODevice::ReadWrite)) 101 | { 102 | QTextStream stream(&logFile); 103 | stream << QDateTime::currentDateTime().toString() << " " << logMessage << endl; 104 | logFile.close(); 105 | } 106 | else 107 | { 108 | qDebug() << "Can`t log to file " << _logFile; 109 | exit(EXIT_FAILURE); 110 | } 111 | } 112 | } 113 | 114 | Log::Log() { 115 | _loggingMode = LoggingModeConsole; 116 | } 117 | 118 | } // namespace QtWebServer 119 | -------------------------------------------------------------------------------- /misc/log.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "misc/threadsafety.h" 28 | 29 | // Qt includes 30 | #include 31 | 32 | namespace QtWebServer { 33 | 34 | class Logger; 35 | class Log { 36 | friend class Logger; 37 | public: 38 | enum LoggingMode { 39 | LoggingModeNone, 40 | LoggingModeConsole, 41 | LoggingToDebug, 42 | LoggingToFile 43 | }; 44 | 45 | enum EntryType { 46 | Verbose = 0, 47 | Information = 1, 48 | Warning = 2, 49 | Error = 3 50 | }; 51 | 52 | static Log* instance(); 53 | 54 | LoggingMode loggingMode(); 55 | void setLoggingMode(LoggingMode loggingMode); 56 | void setLoggingFile(QString logfile); 57 | 58 | protected: 59 | void log(QString name, QString message, EntryType entryType); 60 | 61 | private: 62 | Log(); 63 | 64 | ThreadGuard _loggingMode; 65 | 66 | static Log* _instance; 67 | QString _logFile; 68 | }; 69 | 70 | } // namespace QtWebServer 71 | -------------------------------------------------------------------------------- /misc/logger.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "logger.h" 26 | 27 | namespace QtWebServer { 28 | 29 | Logger::Logger(QString name) { 30 | _name = name; 31 | } 32 | 33 | Logger::~Logger() { 34 | } 35 | 36 | void Logger::log(QString message, Log::EntryType entryType) { 37 | Log::instance()->log(_name, message, entryType); 38 | } 39 | 40 | } // namespace QtWebServer 41 | -------------------------------------------------------------------------------- /misc/logger.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "log.h" 28 | 29 | // Qt includes 30 | #include 31 | 32 | namespace QtWebServer { 33 | 34 | class Logger { 35 | public: 36 | Logger(QString name); 37 | virtual ~Logger(); 38 | 39 | void log(QString message, Log::EntryType entryType = Log::Verbose); 40 | 41 | private: 42 | QString _name; 43 | }; 44 | 45 | } // namespace QtWebServer 46 | 47 | -------------------------------------------------------------------------------- /misc/threadsafety.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | 29 | namespace QtWebServer { 30 | 31 | class MutexLocker { 32 | public: 33 | MutexLocker(QMutex& m) : _m(m) { _m.lock(); } 34 | ~MutexLocker() { _m.unlock(); } 35 | 36 | private: 37 | QMutex& _m; 38 | }; 39 | 40 | template 41 | class ThreadGuard { 42 | public: 43 | ThreadGuard() { 44 | _mutex = new QMutex(); 45 | } 46 | 47 | ~ThreadGuard() { 48 | delete _mutex; 49 | } 50 | 51 | void set(const T& other) { 52 | MutexLocker m(*_mutex); Q_UNUSED(m); 53 | _r = other; 54 | } 55 | 56 | T r() const { 57 | MutexLocker m(*_mutex); Q_UNUSED(m); 58 | return _r; 59 | } 60 | 61 | const ThreadGuard& operator=(const T& other) { 62 | set(other); 63 | return *this; 64 | } 65 | 66 | private: 67 | ThreadGuard(const ThreadGuard&) {} 68 | 69 | T _r; 70 | 71 | // There is a reason we are holding a pointer instead of a reference: 72 | // Sometimes const getter methods would lock the mutex to retrieve the 73 | // guarded value. Strictly speaking, this would also alter the object, 74 | // so retrieving a value would also mean getters would lose their constness. 75 | // While correct, this behaviour doesn't make sense, so we keep a pointer 76 | // here as a workaround. 77 | QMutex *_mutex; 78 | }; 79 | 80 | } // namespace QtWebServer 81 | -------------------------------------------------------------------------------- /qtwebserver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jacob3141/qtwebserver/9cb1d0898bf0f3a3ca8f460b036183d49730ecf3/qtwebserver.png -------------------------------------------------------------------------------- /qtwebserver.pri: -------------------------------------------------------------------------------- 1 | QT += core network xml sql 2 | 3 | INCLUDEPATH += \ 4 | $$PWD 5 | 6 | LIBS += \ 7 | -L../qtwebserver -lqtwebserver 8 | -------------------------------------------------------------------------------- /qtwebserver.pro: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2010-2015 Jacob Dawid 3 | # 4 | # This file is part of QtWebServer. 5 | # 6 | # QtWebServer is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Affero General Public License as 8 | # published by the Free Software Foundation, either version 3 of the 9 | # License, or (at your option) any later version. 10 | # 11 | # QtWebServer is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Affero General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public 17 | # License along with QtWebServer. 18 | # If not, see . 19 | # 20 | # It is possible to obtain a commercial license of QtWebServer. 21 | # Please contact Jacob Dawid 22 | # 23 | 24 | TEMPLATE = lib 25 | 26 | QT += core network xml sql gui 27 | 28 | CONFIG += staticlib 29 | 30 | SOURCES += \ 31 | http/httprequest.cpp \ 32 | http/httpstatuscodes.cpp \ 33 | http/httpwebengine.cpp \ 34 | tcp/tcpmultithreadedserver.cpp \ 35 | tcp/tcpserverthread.cpp \ 36 | misc/log.cpp \ 37 | misc/logger.cpp \ 38 | http/httpresource.cpp \ 39 | http/httpiodeviceresource.cpp \ 40 | sql/sqlconnectionpool.cpp \ 41 | html/htmldocument.cpp \ 42 | util/utilassetsresource.cpp \ 43 | http/httpresponse.cpp \ 44 | http/httpheaders.cpp \ 45 | util/utildataurlcodec.cpp \ 46 | util/utilformurlcodec.cpp \ 47 | css/cssdocument.cpp \ 48 | css/cssruleset.cpp \ 49 | weblayout.cpp 50 | 51 | HEADERS += \ 52 | http/httprequest.h \ 53 | http/httpstatuscodes.h \ 54 | http/httpwebengine.h \ 55 | tcp/tcpserverthread.h \ 56 | tcp/tcpmultithreadedserver.h \ 57 | tcp/tcpresponder.h \ 58 | misc/threadsafety.h \ 59 | misc/logger.h \ 60 | misc/log.h \ 61 | http/httpresource.h \ 62 | http/httpiodeviceresource.h \ 63 | sql/sqlconnectionpool.h \ 64 | html/htmldocument.h \ 65 | util/utilassetsresource.h \ 66 | http/httpresponse.h \ 67 | http/httpheaders.h \ 68 | util/utildataurlcodec.h \ 69 | util/utilformurlcodec.h \ 70 | css/cssdocument.h \ 71 | css/cssruleset.h \ 72 | webwidget.h \ 73 | weblayout.h 74 | 75 | RESOURCES += 76 | 77 | OTHER_FILES += \ 78 | LICENSE \ 79 | README.md 80 | 81 | -------------------------------------------------------------------------------- /sql/sqlconnectionpool.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "sqlconnectionpool.h" 26 | 27 | // Qt includes 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Sql { 33 | 34 | ConnectionPool::ConnectionPool(QObject *parent) : 35 | QObject(parent) { 36 | QStringList drivers = QSqlDatabase::drivers(); 37 | 38 | _count = 32; 39 | 40 | _open = false; 41 | _hostName = "localhost"; 42 | _port = 3306; 43 | _driverName = drivers.count() ? drivers.at(0) : ""; 44 | _connectOptions = ""; 45 | 46 | _databaseName = ""; 47 | _userName = ""; 48 | _password = ""; 49 | } 50 | 51 | ConnectionPool::~ConnectionPool() { 52 | } 53 | 54 | ConnectionPool& ConnectionPool::instance() { 55 | static ConnectionPool _instance; 56 | return _instance; 57 | } 58 | 59 | void ConnectionPool::resize(int count) { 60 | _count = count; 61 | } 62 | 63 | int ConnectionPool::count() { 64 | return _count.r(); 65 | } 66 | 67 | bool ConnectionPool::open() { 68 | close(); 69 | int c = count(); 70 | for(int i = 0; i < c; i++) { 71 | QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), QString("sql%1").arg(i)); 72 | db.setHostName(hostName()); 73 | db.setPort(port()); 74 | db.setConnectOptions(connectOptions()); 75 | db.setDatabaseName(databaseName()); 76 | db.setUserName(userName()); 77 | db.setPassword(password()); 78 | 79 | if(!db.open()) { 80 | close(); 81 | return false; 82 | } 83 | } 84 | reset(); 85 | _open = true; 86 | return true; 87 | } 88 | 89 | bool ConnectionPool::open(const QString& user, const QString& password) { 90 | _userName = user; 91 | _password = password; 92 | return open(); 93 | } 94 | 95 | bool ConnectionPool::isOpen() { 96 | return _open.r(); 97 | } 98 | 99 | void ConnectionPool::close() { 100 | QStringList connectionNames = QSqlDatabase::connectionNames(); 101 | foreach(QString connectionName, connectionNames) { 102 | QSqlDatabase::removeDatabase(connectionName); 103 | } 104 | _open = false; 105 | } 106 | 107 | QString ConnectionPool::hostName() const { 108 | return _hostName.r(); 109 | } 110 | 111 | int ConnectionPool::port() const { 112 | return _port.r(); 113 | } 114 | 115 | QString ConnectionPool::driverName() const { 116 | return _driverName.r(); 117 | } 118 | 119 | QString ConnectionPool::connectOptions() const { 120 | return _connectOptions.r(); 121 | } 122 | 123 | QString ConnectionPool::databaseName() const { 124 | return _databaseName.r(); 125 | } 126 | 127 | QString ConnectionPool::userName() const { 128 | return _userName.r(); 129 | } 130 | 131 | QString ConnectionPool::password() const { 132 | return _password.r(); 133 | } 134 | 135 | QSqlQuery ConnectionPool::exec(const QString& query) { 136 | QSqlDatabase db = QSqlDatabase::database(nextConnectionName()); 137 | return db.exec(query); 138 | } 139 | 140 | void ConnectionPool::setHostName(QString hostName) { 141 | _hostName = hostName; 142 | } 143 | 144 | void ConnectionPool::setPort(int port) { 145 | _port = port; 146 | } 147 | 148 | void ConnectionPool::setDriverName(QString driverName) { 149 | _driverName = driverName; 150 | } 151 | 152 | void ConnectionPool::setConnectOptions(QString connectOptions) { 153 | _connectOptions = connectOptions; 154 | } 155 | 156 | void ConnectionPool::setDatabaseName(QString databaseName) { 157 | _databaseName = databaseName; 158 | } 159 | 160 | void ConnectionPool::setUserName(QString userName) { 161 | _userName = userName; 162 | } 163 | 164 | void ConnectionPool::setPassword(QString password) { 165 | _password = password; 166 | } 167 | 168 | void ConnectionPool::reset() { 169 | _nextConnectionNameMutex.lock(); 170 | _next = 0; 171 | _nextConnectionNameMutex.unlock(); 172 | } 173 | 174 | QString ConnectionPool::nextConnectionName() { 175 | _nextConnectionNameMutex.lock(); 176 | _next++; 177 | if(_next >= count()) { 178 | _next = 0; 179 | } 180 | QString connectionName = QString("sql%1").arg(_next); 181 | _nextConnectionNameMutex.unlock(); 182 | return connectionName; 183 | } 184 | 185 | } // namespace Sql 186 | 187 | } // namespace QtWebServer 188 | -------------------------------------------------------------------------------- /sql/sqlconnectionpool.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "misc/threadsafety.h" 28 | 29 | // Qt includes 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | namespace QtWebServer { 36 | 37 | namespace Sql { 38 | 39 | /** 40 | * @class ConnectionPool 41 | * @author Jacob Dawid 42 | * Connection pooling. 43 | */ 44 | class ConnectionPool : 45 | public QObject { 46 | Q_OBJECT 47 | public: 48 | /** Singleton. */ 49 | static ConnectionPool &instance(); 50 | ~ConnectionPool(); 51 | 52 | /** 53 | * Resizes the connection pool. 54 | * @attention For this to take effect you have to close and reopen the 55 | * connection pool. 56 | * @param count The number of simultaneous connections. 57 | */ 58 | void resize(int count); 59 | 60 | /** @returns the number of available simultaneous connections. */ 61 | int count(); 62 | 63 | /** 64 | * Opens the connection pool. 65 | * @returns true, when the operation was successful. 66 | */ 67 | bool open(); 68 | 69 | /** 70 | * Opens the connection pool and saves the username and password. 71 | * @param user The database username to be used. 72 | * @param password The password for the database user. 73 | * @returns true, when the operation was successful. 74 | */ 75 | bool open(const QString& user, const QString& password); 76 | 77 | /** @returns true, when the pool is currently open. */ 78 | bool isOpen(); 79 | 80 | /** Closes the connection pool. */ 81 | void close(); 82 | 83 | /** @returns the host name. */ 84 | QString hostName() const; 85 | 86 | /** @returns the port. */ 87 | int port() const; 88 | 89 | /** @returns the database driver's name. */ 90 | QString driverName() const; 91 | 92 | /** @returns the database connect options. */ 93 | QString connectOptions() const; 94 | 95 | /** @returns the database name. */ 96 | QString databaseName() const; 97 | 98 | /** @returns the database username. */ 99 | QString userName() const; 100 | 101 | /** @returns the database user's password. */ 102 | QString password() const; 103 | 104 | /** 105 | * Executes the query and returns a query object. 106 | * @param query The SQL query to be executed. 107 | * @returns the according QSqlQuery object. 108 | */ 109 | QSqlQuery exec(const QString& query = QString()); 110 | 111 | /** Sets the database host name. */ 112 | void setHostName(QString hostName); 113 | 114 | /** Sets the port. */ 115 | void setPort(int port); 116 | 117 | /** Sets the database driver name. */ 118 | void setDriverName(QString driverName); 119 | 120 | /** Sets the database connect options. */ 121 | void setConnectOptions(QString connectOptions); 122 | 123 | /** Sets the database name. */ 124 | void setDatabaseName(QString databaseName); 125 | 126 | /** Sets the database user name. */ 127 | void setUserName(QString userName); 128 | 129 | /** Sets the database user's password. */ 130 | void setPassword(QString password); 131 | 132 | private: 133 | explicit ConnectionPool(QObject *parent = 0); 134 | 135 | void reset(); 136 | QString nextConnectionName(); 137 | 138 | ThreadGuard _open; 139 | 140 | ThreadGuard _hostName; 141 | ThreadGuard _port; 142 | ThreadGuard _driverName; 143 | ThreadGuard _connectOptions; 144 | 145 | ThreadGuard _databaseName; 146 | ThreadGuard _userName; 147 | ThreadGuard _password; 148 | 149 | ThreadGuard _count; 150 | QMutex _nextConnectionNameMutex; 151 | int _next; 152 | }; 153 | 154 | } // namespace Sql 155 | 156 | } // namespace QtWebServer 157 | -------------------------------------------------------------------------------- /tcp/tcpmultithreadedserver.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Qt includes 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | // Own includes 31 | #include "tcpmultithreadedserver.h" 32 | #include "tcpserverthread.h" 33 | 34 | namespace QtWebServer { 35 | 36 | namespace Tcp { 37 | 38 | MultithreadedServer::MultithreadedServer() 39 | : QTcpServer(), 40 | Logger("WebServer::WebService") { 41 | setDefaultSslConfiguration(); 42 | _serverTimeoutSeconds = 60; 43 | } 44 | 45 | MultithreadedServer::~MultithreadedServer() { 46 | close(); 47 | } 48 | 49 | bool MultithreadedServer::close() { 50 | if(isListening()) { 51 | QTcpServer::close(); 52 | 53 | // Mark all active threads for deletion if already running 54 | foreach(ServerThread* networkServiceThread, _serverThreads) { 55 | if(networkServiceThread) { 56 | networkServiceThread->deleteLater(); 57 | } 58 | } 59 | _serverThreads.clear(); 60 | } 61 | return true; 62 | } 63 | 64 | bool MultithreadedServer::listen(const QHostAddress &address, 65 | quint16 port, 66 | int numberOfThreads) { 67 | if(isListening()) { 68 | return false; 69 | } 70 | 71 | // Create the specified number of threads and store them in a vector 72 | int thread = numberOfThreads; 73 | while(thread > 0) { 74 | ServerThread* networkServiceThread = new ServerThread(*this); 75 | networkServiceThread->start(); 76 | _serverThreads.append(networkServiceThread); 77 | thread--; 78 | } 79 | 80 | _nextRequestDelegatedTo = 0; 81 | 82 | // Listen 83 | return QTcpServer::listen(address, port); 84 | } 85 | 86 | int MultithreadedServer::numberOfThreads() { 87 | return _serverThreads.size(); 88 | } 89 | 90 | int MultithreadedServer::serverTimeoutSeconds() { 91 | return _serverTimeoutSeconds.r(); 92 | } 93 | 94 | void MultithreadedServer::setServerTimeoutSeconds(int seconds) { 95 | _serverTimeoutSeconds = seconds; 96 | } 97 | 98 | Responder *MultithreadedServer::responder() { 99 | return _responder.r(); 100 | } 101 | 102 | void MultithreadedServer::setResponder(Responder *responder) { 103 | _responder = responder; 104 | } 105 | 106 | void MultithreadedServer::setSslConfiguration(QSslConfiguration sslConfiguration) { 107 | _sslConfiguration = sslConfiguration; 108 | } 109 | 110 | QSslConfiguration MultithreadedServer::sslConfiguration() const { 111 | return _sslConfiguration.r(); 112 | } 113 | 114 | void MultithreadedServer::incomingConnection(qintptr socketDescriptor) { 115 | ServerThread* serverThread = 0; 116 | ServerThread::NetworkServiceThreadState state; 117 | 118 | QTimer timer; 119 | timer.start(serverTimeoutSeconds() * 1000); 120 | 121 | do { 122 | serverThread = _serverThreads[_nextRequestDelegatedTo]; 123 | state = serverThread->state(); 124 | 125 | _nextRequestDelegatedTo++; 126 | if(_nextRequestDelegatedTo >= _serverThreads.size()) { 127 | _nextRequestDelegatedTo = 0; 128 | } 129 | 130 | if(state == ServerThread::NetworkServiceThreadStateBusy && 131 | timer.remainingTime() <= 0) { 132 | // Abort on server timeout 133 | return; 134 | } 135 | } while(state == ServerThread::NetworkServiceThreadStateBusy); 136 | 137 | // Use invokeMethod here to decouple threads 138 | QMetaObject::invokeMethod(serverThread, "handleNewConnection", Q_ARG(int, socketDescriptor)); 139 | } 140 | 141 | void MultithreadedServer::setDefaultSslConfiguration() { 142 | // Set a default SSL configuration just to have it running out of the 143 | // box. Only for development purposes, never distribute an application 144 | // that relies on SSL with the default configuration set. You can 145 | // generate your own key and self-signed certificate: 146 | // 147 | // $ openssl req -x509 -newkey rsa:2048 -keyout server.key -nodes -days 365 -out server.crt 148 | 149 | QSslConfiguration sslConfiguration; 150 | QByteArray defaultKey = 151 | "-----BEGIN PRIVATE KEY-----\n" 152 | "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQdRrom1g/MsJh\n" 153 | "bfwVBZH+oxuGeIBO3jeNWs2bjpDmjtEtMz66LfFVrjuggt0UeNFb1Ve3tYIVq4Wj\n" 154 | "gmHYUOB44KCzVqJrd1mZdDKukdvoalJyh5f5/kqLdNGzrfjl5fmtK4jy76xM0oV4\n" 155 | "aZlj8eC4+odrS9HLHfBylDIeSXPWtThFw02IGiQALbtW8cqHSOXhucPAwiNFELVd\n" 156 | "jjFLa0buQSWq3WSZnroLwOXxfd2dtIoDIn319wTRFPAHWQDqlIuvefYvNzel65yY\n" 157 | "ZwoomIOrcxfN7IczLxkryD1uZpr4u2aWpHpz+mB7WXhPW82H6qT205e25iDbiZUQ\n" 158 | "+2UJWBHBAgMBAAECggEBAKF7Fe066ZGLcKio2q4uMnpfP+NbVYnC+qW1wbDPL9Bq\n" 159 | "sf+hwuXW0SzeW7JrrXc+YHATRHA7WxoOVOflCIbZoAoDeHl0kz1Mp0wIh3pT41aX\n" 160 | "hmbSQxiVtIlzZT8bdcQh8tgC8YO/xml8a4hrxTd3F+4zpNOpWEtQVgNsaaasn9+h\n" 161 | "/I/8uQ6oYkNISbnrs7u2fkFAw2/RbyZ6E2Dr9fMiDVUSa5ppFFHjfkgzbGA56Mtg\n" 162 | "0DdpxWMhICVMwlTI23zmjIAssyJG6xfCQfll9XbsiPAx9/uwAMIFPaUaWBzEUmhh\n" 163 | "L+/7hESQ7DGIfKxUqtiyvT53EuupxUxkcr0useZY5UECgYEA6wis5xcEo4eBk5o4\n" 164 | "IYcdZ93LrgwKtWj6e50sVs4NgCgsDWbH99IhNIxwQnCJ02O/aacbFV0d+jB9Jh+M\n" 165 | "NKTmqDxoe+EY2WJ+sR/YZ9VZwoHFwqubL1BzroX8FBN363tjicfFA+o3bSb4OXDC\n" 166 | "PINFzSLH8cLhFOo3UFiZf9I9ZZcCgYEA4w2FDGzhnpZPToiT/nwf55Ze2lJsPWlP\n" 167 | "8XydHoIWDIbUd1LnxBnoGZF1pefexoIy8zesGBfjHC7t6tC/4zy2oqECiP6ESACN\n" 168 | "8yhSDG+iegTU59LOk+blserR52c2vNGOR7RFbAyZeg3XXwlvQOpaquIP6tc7vkv1\n" 169 | "FijDcWm3nmcCgYAUAu0Vz/PpKIRz2NGmqSZrzYqmCwhuYb3SAJPh4DFuE/2MNpAY\n" 170 | "HaAOJVb5kTNq+Dc3+65mp0MCJlbBhDYf1Vp+QIZ05bmD6Mr4sclvLc8yrHH2HT5d\n" 171 | "TPBMj8PiwbWYKy1ScdvodWy6snK4EU24cUTkLm3vu7QGX9rN0H1hULlBiQKBgQC5\n" 172 | "rgW/ao98HJoQtFqrBCEnR+6cBkmkUypgZzMqjuGvLtg0GOWWlkUcG7uliKDDoBhA\n" 173 | "lKe1MFu3YZ2JqVszXyRQjPHAzLurEmEDmFa4+tZZiPf/+YKcq3fubwVngx3dflYn\n" 174 | "x4H6YbdlfEpD2zhTUxQAqUyxFYEzF3T/wShL6FOUQwKBgA2qSGUvxHcyWw8jnQ2g\n" 175 | "BbwtU75LCvTrSuIQ8DJIVt5+W9iseNi+q51w6hTAUleJ+4X7RDrSisQucbDAY+Fg\n" 176 | "Tyz0YVk4+WR0G7ZYAjLJBe7KpzpDZ4mI8yhfYBMhH+Rtkzk96ECezEve8L3llUqD\n" 177 | "s7+8TR6cFYhHQQH3DQ5BKdt0\n" 178 | "-----END PRIVATE KEY-----"; 179 | 180 | QByteArray defaultCertificate = 181 | "-----BEGIN CERTIFICATE-----\n" 182 | "MIIDhzCCAm+gAwIBAgIJAP9LmloP2P0tMA0GCSqGSIb3DQEBCwUAMFoxCzAJBgNV\n" 183 | "BAYTAkRFMRMwEQYDVQQIDApTb21lLVN0YXRlMSAwHgYDVQQKDBdRdFdlYlNlcnZl\n" 184 | "ciBEZXZlbG9wbWVudDEUMBIGA1UEAwwLRGV2ZWxvcG1lbnQwHhcNMTUwNDIxMDYw\n" 185 | "MTE4WhcNNDUwNDEzMDYwMTE4WjBaMQswCQYDVQQGEwJERTETMBEGA1UECAwKU29t\n" 186 | "ZS1TdGF0ZTEgMB4GA1UECgwXUXRXZWJTZXJ2ZXIgRGV2ZWxvcG1lbnQxFDASBgNV\n" 187 | "BAMMC0RldmVsb3BtZW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n" 188 | "0HUa6JtYPzLCYW38FQWR/qMbhniATt43jVrNm46Q5o7RLTM+ui3xVa47oILdFHjR\n" 189 | "W9VXt7WCFauFo4Jh2FDgeOCgs1aia3dZmXQyrpHb6GpScoeX+f5Ki3TRs6345eX5\n" 190 | "rSuI8u+sTNKFeGmZY/HguPqHa0vRyx3wcpQyHklz1rU4RcNNiBokAC27VvHKh0jl\n" 191 | "4bnDwMIjRRC1XY4xS2tG7kElqt1kmZ66C8Dl8X3dnbSKAyJ99fcE0RTwB1kA6pSL\n" 192 | "r3n2Lzc3peucmGcKKJiDq3MXzeyHMy8ZK8g9bmaa+LtmlqR6c/pge1l4T1vNh+qk\n" 193 | "9tOXtuYg24mVEPtlCVgRwQIDAQABo1AwTjAdBgNVHQ4EFgQUm4DLVsXhMy8J7Us4\n" 194 | "QoTdTgVS9CEwHwYDVR0jBBgwFoAUm4DLVsXhMy8J7Us4QoTdTgVS9CEwDAYDVR0T\n" 195 | "BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAmxPOPLbq0EBBWrboNfGtD1OTnchy\n" 196 | "kBlhrSG+2gLNS3lfiphOZ+qtUGNTgewAk+nR5sraw4uFG8+6oQmNFS35zlbzWhgC\n" 197 | "dveQaT4CNtXCpAevRCbhhuDxzU0W0Dtenf3xFBC2wUWbAwxGZuklyA5ohl9+1By7\n" 198 | "YG5dPYYsgoeQl9t5yg5orh39kcrrz/exNlPH71qZO6QrPLlaRs0q4S4Yj33hgm/1\n" 199 | "XAILf9ZtcTElTRhSHC81bZz2HG84nP39WJCe4hH081cdkAMm7W2fzPTzHUWWRW34\n" 200 | "PMB0Ipp7R7CrztyxyaaDo1S3ozEpqvVT0KI65dWLt8ZsggcKxP6P5aeCBQ==\n" 201 | "-----END CERTIFICATE-----"; 202 | 203 | QSslKey sslKey(defaultKey, QSsl::Rsa); 204 | sslConfiguration.setPrivateKey(sslKey); 205 | 206 | QSslCertificate sslCertificate(defaultCertificate); 207 | sslConfiguration.setLocalCertificate(sslCertificate); 208 | 209 | sslConfiguration.setProtocol(QSsl::AnyProtocol); 210 | setSslConfiguration(sslConfiguration); 211 | } 212 | 213 | } // namespace Tcp 214 | 215 | } // namespace QtWebServer 216 | -------------------------------------------------------------------------------- /tcp/tcpmultithreadedserver.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "tcpresponder.h" 28 | 29 | #include "misc/logger.h" 30 | #include "misc/threadsafety.h" 31 | 32 | // Qt includes 33 | #include 34 | #include 35 | #include 36 | 37 | namespace QtWebServer { 38 | 39 | namespace Tcp { 40 | 41 | class ServerThread; 42 | 43 | /** 44 | * @brief The WebService class 45 | * @author Jacob Dawid 46 | * @date 23.11.2013 47 | */ 48 | class MultithreadedServer : public QTcpServer, public Logger { 49 | Q_OBJECT 50 | public: 51 | /** @brief WebService */ 52 | MultithreadedServer(); 53 | 54 | /** @brief ~WebService */ 55 | virtual ~MultithreadedServer(); 56 | 57 | /** Closes the server immediately. */ 58 | bool close(); 59 | 60 | /** 61 | * Listens to the given address and port. 62 | * @param address The server address. 63 | * @param port The server port. 64 | * @param numberOfThreads The number of threads this server is using. 65 | * @returns true, if the server is listening. 66 | */ 67 | bool listen(const QHostAddress &address = QHostAddress::Any, 68 | quint16 port = 0, 69 | int numberOfThreads = 4); 70 | 71 | /** Sets the number of threads this server owns. */ 72 | int numberOfThreads(); 73 | 74 | /** @returns the server timeout in seconds. */ 75 | int serverTimeoutSeconds(); 76 | 77 | /** 78 | * Sets the server timeout in seconds. If the server is not able 79 | * to serve the cliend in the given amount of time (ie. all threads 80 | * are busy for the given amount of seconds) it will simply ignore 81 | * incoming connections. 82 | */ 83 | void setServerTimeoutSeconds(int seconds); 84 | 85 | /** @returns the responder for this server. */ 86 | Responder *responder(); 87 | 88 | /** Sets the responder for this server. */ 89 | void setResponder(Responder *responder); 90 | 91 | void setSslConfiguration(QSslConfiguration sslConfiguration); 92 | QSslConfiguration sslConfiguration() const; 93 | 94 | protected: 95 | /** 96 | * @brief incomingConnection 97 | * @param handle 98 | */ 99 | void incomingConnection(qintptr socketDescriptor); 100 | 101 | private: 102 | void setDefaultSslConfiguration(); 103 | 104 | ThreadGuard _responder; 105 | ThreadGuard _serverTimeoutSeconds; 106 | 107 | // Scheduler 108 | int _nextRequestDelegatedTo; 109 | QVector _serverThreads; 110 | 111 | ThreadGuard _sslConfiguration; 112 | }; 113 | 114 | } // namespace Tcp 115 | 116 | } // namespace QtWebServer 117 | 118 | -------------------------------------------------------------------------------- /tcp/tcpresponder.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | 29 | namespace QtWebServer { 30 | 31 | namespace Tcp { 32 | 33 | class Responder { 34 | public: 35 | virtual void respond(QSslSocket* sslSocket) = 0; 36 | }; 37 | 38 | } // namespace Tcp 39 | 40 | } // namespace QtWebServer 41 | 42 | -------------------------------------------------------------------------------- /tcp/tcpserverthread.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Qt includes 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | // Own includes 31 | #include "tcpserverthread.h" 32 | 33 | namespace QtWebServer { 34 | 35 | namespace Tcp { 36 | 37 | ServerThread::ServerThread(MultithreadedServer &multithreadedServer) : 38 | QThread(0), 39 | Logger(QString("WebServer:NetworkServiceThread (%1)").arg((long)this)), 40 | _multithreadedServer(multithreadedServer) { 41 | _networkServiceThreadState = NetworkServiceThreadStateIdle; 42 | } 43 | 44 | ServerThread::~ServerThread() { 45 | } 46 | 47 | ServerThread::NetworkServiceThreadState ServerThread::state() { 48 | return _networkServiceThreadState.r(); 49 | } 50 | 51 | void ServerThread::setState(ServerThread::NetworkServiceThreadState state) { 52 | _networkServiceThreadState = state; 53 | emit stateChanged(state); 54 | } 55 | 56 | void ServerThread::handleNewConnection(int socketHandle) { 57 | setState(NetworkServiceThreadStateBusy); 58 | 59 | QSslSocket* sslSocket = new QSslSocket(this); 60 | connect(sslSocket, SIGNAL(readyRead()), this, SLOT(clientDataAvailable())); 61 | connect(sslSocket, SIGNAL(disconnected()), this, SLOT(clientClosedConnection())); 62 | 63 | // Error/informational signals 64 | connect(sslSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); 65 | connect(sslSocket, SIGNAL(sslErrors(QList)), this, SLOT(sslErrors(QList))); 66 | connect(sslSocket, SIGNAL(modeChanged(QSslSocket::SslMode)), this, SLOT(modeChanged(QSslSocket::SslMode))); 67 | connect(sslSocket, SIGNAL(encrypted()), this, SLOT(encrypted())); 68 | connect(sslSocket, SIGNAL(encryptedBytesWritten(qint64)), this, SLOT(encryptedBytesWritten(qint64))); 69 | 70 | sslSocket->setSocketDescriptor(socketHandle); 71 | sslSocket->setSslConfiguration(_multithreadedServer.sslConfiguration()); 72 | 73 | setState(NetworkServiceThreadStateIdle); 74 | } 75 | 76 | 77 | void ServerThread::clientDataAvailable() { 78 | setState(NetworkServiceThreadStateBusy); 79 | 80 | QSslSocket* sslSocket = (QSslSocket*)sender(); 81 | 82 | Responder *responder = _multithreadedServer.responder(); 83 | if(responder) { 84 | responder->respond(sslSocket); 85 | } 86 | 87 | setState(NetworkServiceThreadStateIdle); 88 | } 89 | 90 | void ServerThread::clientClosedConnection() { 91 | setState(NetworkServiceThreadStateBusy); 92 | 93 | QSslSocket* sslSocket = (QSslSocket*)sender(); 94 | 95 | sslSocket->close(); 96 | sslSocket->deleteLater(); 97 | 98 | setState(NetworkServiceThreadStateIdle); 99 | } 100 | 101 | void ServerThread::error(QAbstractSocket::SocketError error) { 102 | QSslSocket* sslSocket = dynamic_cast(sender()); 103 | if(sslSocket) { 104 | log(sslSocket->errorString(), Log::Error); 105 | } 106 | 107 | QString errorString = "Unknown error"; 108 | switch(error) { 109 | case QAbstractSocket::ConnectionRefusedError: 110 | errorString = "The connection was refused by the peer (or timed out)."; 111 | break; 112 | case QAbstractSocket::RemoteHostClosedError: 113 | errorString = "The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent."; 114 | break; 115 | case QAbstractSocket::HostNotFoundError: 116 | errorString = "The host address was not found."; 117 | break; 118 | case QAbstractSocket::SocketAccessError: 119 | errorString = "The socket operation failed because the application lacked the required privileges."; 120 | break; 121 | case QAbstractSocket::SocketResourceError: 122 | errorString = "The local system ran out of resources (e.g., too many sockets)."; 123 | break; 124 | case QAbstractSocket::SocketTimeoutError: 125 | errorString = "The socket operation timed out."; 126 | break; 127 | case QAbstractSocket::DatagramTooLargeError: 128 | errorString = "The datagram was larger than the operating system's limit (which can be as low as 8192 bytes)."; 129 | break; 130 | case QAbstractSocket::NetworkError: 131 | errorString = "An error occurred with the network (e.g., the network cable was accidentally plugged out)."; 132 | break; 133 | case QAbstractSocket::AddressInUseError: 134 | errorString = "The address specified to QAbstractSocket::bind() is already in use and was set to be exclusive."; 135 | break; 136 | case QAbstractSocket::SocketAddressNotAvailableError: 137 | errorString = "The address specified to QAbstractSocket::bind() does not belong to the host."; 138 | break; 139 | case QAbstractSocket::UnsupportedSocketOperationError: 140 | errorString = "The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support)."; 141 | break; 142 | case QAbstractSocket::UnfinishedSocketOperationError: 143 | errorString = "Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background)."; 144 | break; 145 | case QAbstractSocket::ProxyAuthenticationRequiredError: 146 | errorString = "The socket is using a proxy, and the proxy requires authentication."; 147 | break; 148 | case QAbstractSocket::SslHandshakeFailedError: 149 | errorString = "The SSL/TLS handshake failed, so the connection was closed."; 150 | break; 151 | case QAbstractSocket::ProxyConnectionRefusedError: 152 | errorString = "Could not contact the proxy server because the connection to that server was denied."; 153 | break; 154 | case QAbstractSocket::ProxyConnectionClosedError: 155 | errorString = "The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)."; 156 | break; 157 | case QAbstractSocket::ProxyConnectionTimeoutError: 158 | errorString = "The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase."; 159 | break; 160 | case QAbstractSocket::ProxyNotFoundError: 161 | errorString = "The proxy address set with setProxy() (or the application proxy) was not found."; 162 | break; 163 | case QAbstractSocket::ProxyProtocolError: 164 | errorString = "The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood."; 165 | break; 166 | case QAbstractSocket::OperationError: 167 | errorString = "An operation was attempted while the socket was in a state that did not permit it."; 168 | break; 169 | case QAbstractSocket::SslInternalError: 170 | errorString = "The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library."; 171 | break; 172 | case QAbstractSocket::SslInvalidUserDataError: 173 | errorString = "Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library."; 174 | break; 175 | case QAbstractSocket::TemporaryError: 176 | errorString = "A temporary error occurred (e.g., operation would block and socket is non-blocking)."; 177 | break; 178 | default: 179 | case QAbstractSocket::UnknownSocketError: 180 | errorString = "An unidentified error occurred."; 181 | break; 182 | } 183 | 184 | log(QString("Socket error: %1 (%2)").arg(errorString).arg((int)error)); 185 | } 186 | 187 | void ServerThread::sslErrors(QList errors) { 188 | foreach(QSslError error, errors) { 189 | log(error.errorString(), Log::Error); 190 | } 191 | } 192 | 193 | void ServerThread::modeChanged(QSslSocket::SslMode mode) { 194 | switch (mode) { 195 | case QSslSocket::UnencryptedMode: 196 | log("SSL socket mode changed to unencrypted mode."); 197 | break; 198 | case QSslSocket::SslClientMode: 199 | log("SSL socket mode changed to client mode."); 200 | break; 201 | case QSslSocket::SslServerMode: 202 | log("SSL socket mode changed to server mode."); 203 | break; 204 | } 205 | } 206 | 207 | void ServerThread::encrypted() { 208 | log("SSL Socket entered encrypted state."); 209 | } 210 | 211 | void ServerThread::encryptedBytesWritten(qint64 bytes) { 212 | log(QString("Encrypted bytes written: %1").arg(bytes)); 213 | } 214 | 215 | } // namespace Tcp 216 | 217 | } // namespace QtWebServer 218 | -------------------------------------------------------------------------------- /tcp/tcpserverthread.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "tcpmultithreadedserver.h" 28 | 29 | #include "misc/logger.h" 30 | #include "misc/threadsafety.h" 31 | 32 | // Qt includes 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | namespace QtWebServer { 39 | 40 | namespace Tcp { 41 | 42 | /** 43 | * @brief The NetworkServiceThread class 44 | * @author Jacob Dawid 45 | * @date 23.11.2013 46 | */ 47 | class ServerThread : 48 | public QThread, 49 | public Logger { 50 | friend class MultithreadedServer; 51 | Q_OBJECT 52 | public: 53 | /** 54 | * @brief The NetworkServiceThreadState enum 55 | */ 56 | enum NetworkServiceThreadState { 57 | NetworkServiceThreadStateIdle, /** Thread is idle and waiting to process the next client. */ 58 | NetworkServiceThreadStateBusy /** Thread is busy. */ 59 | }; 60 | 61 | virtual ~ServerThread(); 62 | 63 | /** 64 | * @brief NetworkServiceThreadState 65 | * @return 66 | */ 67 | NetworkServiceThreadState state(); 68 | 69 | private slots: 70 | /** Handles a new incoming connection. */ 71 | void handleNewConnection(int socketHandle); 72 | 73 | /** Handles data from a client. */ 74 | void clientDataAvailable(); 75 | 76 | /** Handles a client that has closed the connection. */ 77 | void clientClosedConnection(); 78 | 79 | 80 | /** Handles socket error messages. */ 81 | void error(QAbstractSocket::SocketError error); 82 | 83 | /** Handles SSL error messages. */ 84 | void sslErrors(QList errors); 85 | 86 | /** Handles SSL mode changed. */ 87 | void modeChanged(QSslSocket::SslMode mode); 88 | 89 | /** Handles an SSL socket's encrypted signal. */ 90 | void encrypted(); 91 | 92 | /** Handles the information when encrypted bytes have been written. */ 93 | void encryptedBytesWritten(qint64 bytes); 94 | 95 | signals: 96 | /** Will be emitted whenever the state of this thread changes. */ 97 | void stateChanged(NetworkServiceThreadState state); 98 | 99 | private: 100 | ServerThread(MultithreadedServer& multithreadedServer); 101 | 102 | /** 103 | * @brief setNetworkServiceThreadState 104 | * @param state 105 | */ 106 | void setState(NetworkServiceThreadState state); 107 | 108 | MultithreadedServer& _multithreadedServer; 109 | ThreadGuard _networkServiceThreadState; 110 | }; 111 | 112 | } // namespace Tcp 113 | 114 | } // namespace QtWebServer 115 | 116 | -------------------------------------------------------------------------------- /util/utilassetsresource.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "utilassetsresource.h" 26 | 27 | // Qt includes 28 | #include 29 | #include 30 | 31 | namespace QtWebServer { 32 | 33 | namespace Util { 34 | 35 | AssetsResource::AssetsResource(QObject *parent) : 36 | Http::Resource("/asset/{id}", parent) { 37 | } 38 | 39 | AssetsResource::~AssetsResource() { 40 | } 41 | 42 | void AssetsResource::insertAsset(QString id, QString assetPath) { 43 | _assetsPathMap.insert(id, assetPath); 44 | } 45 | 46 | void AssetsResource::removeAsset(QString id) { 47 | _assetsPathMap.remove(id); 48 | } 49 | 50 | void AssetsResource::deliver(const Http::Request& request, 51 | Http::Response& response) { 52 | QString id = uriParameters(request.uniqueResourceIdentifier()).value("id"); 53 | 54 | if(_assetsPathMap.contains(id)) { 55 | QFile assetFile(_assetsPathMap.value(id)); 56 | assetFile.open(QFile::ReadOnly); 57 | if(assetFile.isOpen()) { 58 | QFileInfo fileInfo(assetFile); 59 | response.setStatusCode(Http::Ok); 60 | response.setHeader(Http::ContentType, _mimeDatabase.mimeTypeForFile(fileInfo).name()); 61 | response.setBody(assetFile.readAll()); 62 | assetFile.close(); 63 | } else { 64 | response.setStatusCode(Http::Forbidden); 65 | response.setHeader(Http::ContentType, "text/plain"); 66 | } 67 | } else { 68 | response.setStatusCode(Http::NotFound); 69 | response.setHeader(Http::ContentType, "text/plain"); 70 | } 71 | } 72 | 73 | } // namespace Util 74 | 75 | } // namespace QtWebServer 76 | -------------------------------------------------------------------------------- /util/utilassetsresource.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Own includes 27 | #include "http/httpresource.h" 28 | 29 | // Qt includes 30 | #include 31 | #include 32 | 33 | namespace QtWebServer { 34 | 35 | namespace Util { 36 | 37 | /** 38 | * Default controller for delivering assets such as images or other 39 | * files. For best performance, the asset path should be contained in 40 | * a resource file if possible as this avoids expensive disk I/O operations. 41 | * The mimetype is automatically detected. Assets will be made available 42 | * under the unique resource identifier "/asset/{id}", e.g. if you have 43 | * added an asset with an id of "logoimage", you can access it via 44 | * "/asset/logoimage". 45 | */ 46 | class AssetsResource : 47 | public Http::Resource { 48 | Q_OBJECT 49 | public: 50 | AssetsResource(QObject *parent = 0); 51 | ~AssetsResource(); 52 | 53 | /** 54 | * Inserts a new asset that will be made available at "/asset/{id}". 55 | * @param id The id value. Must be unique. 56 | * @param assetPath The physical path to the asset. 57 | */ 58 | void insertAsset(QString id, QString assetPath); 59 | 60 | /** 61 | * Removes an asset. 62 | * @param id The asset's id. 63 | */ 64 | void removeAsset(QString id); 65 | 66 | protected: 67 | void deliver(const Http::Request& request, 68 | Http::Response& response); 69 | private: 70 | QMap _assetsPathMap; 71 | QMimeDatabase _mimeDatabase; 72 | }; 73 | 74 | } // namespace Util 75 | 76 | } // namespace QtWebServer 77 | -------------------------------------------------------------------------------- /util/utildataurlcodec.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "utildataurlcodec.h" 26 | 27 | // Qt includes 28 | #include 29 | #include 30 | #include 31 | 32 | namespace QtWebServer { 33 | 34 | namespace Util { 35 | 36 | DataUrlCodec::DataUrlCodec() { 37 | } 38 | 39 | DataUrlCodec::~DataUrlCodec() { 40 | } 41 | 42 | QByteArray DataUrlCodec::encodeDataUrl(DataUrlContents dataUrlContents) { 43 | if(dataUrlContents.data.isEmpty()) { 44 | return QByteArray(); 45 | } 46 | 47 | if(dataUrlContents.mimeTypeName.isEmpty()) { 48 | QMimeDatabase mimeDatabase; 49 | QMimeType mimeType = mimeDatabase.mimeTypeForData(dataUrlContents.data); 50 | dataUrlContents.mimeTypeName = mimeType.name(); 51 | } 52 | 53 | QString encodingParamter; 54 | QByteArray encodedData; 55 | if(dataUrlContents.base64Encoded) { 56 | encodingParamter = ";base64"; 57 | encodedData = dataUrlContents.data.toBase64(); 58 | } else { 59 | encodingParamter = ""; 60 | encodedData = dataUrlContents.data.toPercentEncoding(); 61 | } 62 | 63 | QString charsetString; 64 | if(dataUrlContents.charset.toLower() == "utf-8") { 65 | charsetString = ";charset=utf-8"; 66 | } else { 67 | charsetString = ""; 68 | } 69 | 70 | QString dataUrlString = QString("data:%1%2%3,%4") 71 | .arg(dataUrlContents.mimeTypeName) 72 | .arg(charsetString) 73 | .arg(encodingParamter) 74 | .arg(QString::fromUtf8(encodedData)); 75 | 76 | if(dataUrlContents.charset.toLower() == "utf-8") { 77 | return dataUrlString.toUtf8(); 78 | } else { 79 | return dataUrlString.toLatin1(); 80 | } 81 | } 82 | 83 | DataUrlCodec::DataUrlContents DataUrlCodec::decodeDataUrl(QByteArray dataUrl) { 84 | DataUrlContents dataUrlContents; 85 | 86 | if(!dataUrl.startsWith("data:")) { 87 | return dataUrlContents; 88 | } 89 | 90 | // Remove the data: prefix by removing the first five characters 91 | dataUrl = dataUrl.right(dataUrl.count() - 5); 92 | 93 | // Split at comma to separate the preamble from the actual data 94 | // data:image/png;charset=utf-8;base64, 95 | QList dataUrlParts = dataUrl.split(','); 96 | 97 | // If there is no separation between preamle and data, the url is 98 | // invalid 99 | if(dataUrlParts.count() < 2) { 100 | return dataUrlContents; 101 | } 102 | 103 | // Split into data info and data 104 | QByteArray dataInfo = dataUrlParts[0]; 105 | dataUrlContents.data = dataUrlParts[1]; 106 | 107 | // Interpret the single preamble parts 108 | QList dataInfoParts = dataInfo.split(';'); 109 | foreach(QByteArray dataInfoPart, dataInfoParts) { 110 | if(dataInfoPart == "base64") { 111 | dataUrlContents.base64Encoded = true; 112 | } else 113 | if(dataInfoPart.startsWith("charset=")) { 114 | dataInfoPart = dataInfoPart.right(dataInfoPart.count() - 8); 115 | dataUrlContents.charset = QString::fromUtf8(dataInfoPart.toLower()); 116 | } else { 117 | dataUrlContents.mimeTypeName = QString::fromUtf8(dataInfoPart); 118 | } 119 | } 120 | 121 | // Decode data depending on whether it has been base64 or percent encoded 122 | if(dataUrlContents.base64Encoded) { 123 | dataUrlContents.data = QByteArray::fromBase64(dataUrlContents.data); 124 | } else { 125 | dataUrlContents.data = QByteArray::fromPercentEncoding(dataUrlContents.data); 126 | } 127 | 128 | return dataUrlContents; 129 | } 130 | 131 | QByteArray DataUrlCodec::dataUrlFromImage(QImage image, 132 | const char *format, 133 | int quality) { 134 | DataUrlContents dataUrlContents; 135 | QBuffer buffer(&dataUrlContents.data); 136 | buffer.open(QIODevice::WriteOnly); 137 | if(buffer.isOpen()) { 138 | image.save(&buffer, format, quality); 139 | buffer.close(); 140 | } 141 | 142 | return encodeDataUrl(dataUrlContents); 143 | } 144 | 145 | QImage DataUrlCodec::imageFromDataUrl(QByteArray dataUrl) { 146 | DataUrlContents dataUrlContents = decodeDataUrl(dataUrl); 147 | 148 | if(!dataUrlContents.mimeTypeName.startsWith("image/")) { 149 | return QImage(); 150 | } 151 | 152 | return QImage::fromData(dataUrlContents.data); 153 | } 154 | 155 | QByteArray DataUrlCodec::dataUrlFromPixmap(QPixmap pixmap, 156 | const char* format, 157 | int quality) { 158 | DataUrlContents dataUrlContents; 159 | QBuffer buffer(&dataUrlContents.data); 160 | buffer.open(QIODevice::WriteOnly); 161 | if(buffer.isOpen()) { 162 | pixmap.save(&buffer, format, quality); 163 | buffer.close(); 164 | } 165 | 166 | return encodeDataUrl(dataUrlContents); 167 | } 168 | 169 | QPixmap DataUrlCodec::pixmapFromDataUrl(QByteArray dataUrl) { 170 | DataUrlContents dataUrlContents = decodeDataUrl(dataUrl); 171 | 172 | if(!dataUrlContents.mimeTypeName.startsWith("image/")) { 173 | return QPixmap(); 174 | } 175 | 176 | QPixmap pixmap; 177 | pixmap.loadFromData(dataUrlContents.data); 178 | return pixmap; 179 | } 180 | 181 | } // Util 182 | 183 | } // QtWebServer 184 | -------------------------------------------------------------------------------- /util/utildataurlcodec.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | namespace QtWebServer { 34 | 35 | namespace Util { 36 | 37 | class DataUrlCodec { 38 | public: 39 | struct DataUrlContents { 40 | DataUrlContents() { 41 | data = ""; 42 | mimeTypeName = ""; 43 | charset = ""; 44 | base64Encoded = false; 45 | } 46 | 47 | QByteArray data; 48 | QString mimeTypeName; 49 | QString charset; 50 | bool base64Encoded; 51 | }; 52 | 53 | /** 54 | * Takes the provided data and creates a data URL. 55 | * When no mime type has been provided, it will try to guess 56 | * the mimetype from the provided data. 57 | * @returns the UTF-8 encoded data URL. 58 | */ 59 | static QByteArray encodeDataUrl(DataUrlContents dataUrlContents); 60 | 61 | /** 62 | * Decodes the data from the provided data url. 63 | * @param dataUrl The data url that should be decoded. 64 | * @returns the decoded data. 65 | */ 66 | static DataUrlContents decodeDataUrl(QByteArray dataUrl); 67 | 68 | /** 69 | * Convenience method to encode an image to a data url. 70 | * @param image The image that shall be encoded. 71 | * @param format The format, @see QImage::save() for more info. 72 | * @param quality Compression quality, @see QImage::save() for more info. 73 | * @returns the encoded image data url. 74 | */ 75 | static QByteArray dataUrlFromImage(QImage image, 76 | const char* format = 0, 77 | int quality = -1); 78 | 79 | /** 80 | * Reads an image from the data url. 81 | * @param dataUrl The data url to read from. 82 | * @returns the image. 83 | */ 84 | static QImage imageFromDataUrl(QByteArray dataUrl); 85 | 86 | /** 87 | * Convenience method to encode a pixmap to a data url. 88 | * @param image The pixmap that shall be encoded. 89 | * @param format The format, @see QPixmap::save() for more info. 90 | * @param quality Compression quality, @see QPixmap::save() for more info. 91 | * @returns the encoded pixmap data url. 92 | */ 93 | static QByteArray dataUrlFromPixmap(QPixmap pixmap, 94 | const char* format = 0, 95 | int quality = -1); 96 | 97 | /** 98 | * Reads a pixmap from the data url. 99 | * @param dataUrl The data url to read from. 100 | * @returns the pixmap. 101 | */ 102 | static QPixmap pixmapFromDataUrl(QByteArray dataUrl); 103 | 104 | private: 105 | DataUrlCodec(); 106 | ~DataUrlCodec(); 107 | }; 108 | 109 | } // namespace Util 110 | 111 | } // namespace QtWebServer 112 | -------------------------------------------------------------------------------- /util/utilformurlcodec.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | // Own includes 25 | #include "utilformurlcodec.h" 26 | 27 | // Qt includes 28 | #include 29 | 30 | namespace QtWebServer { 31 | 32 | namespace Util { 33 | 34 | FormUrlCodec::FormUrlCodec() { 35 | } 36 | 37 | FormUrlCodec::~FormUrlCodec() { 38 | } 39 | 40 | QByteArray FormUrlCodec::encodeFormUrl(QMap formData) { 41 | QByteArray formUrl; 42 | QStringList keys = formData.keys(); 43 | foreach(QString key, keys) { 44 | if(!formUrl.isEmpty()) { 45 | formUrl.append('&'); 46 | } 47 | formUrl.append(QString("%1=%2") 48 | .arg(key) 49 | .arg(QString::fromUtf8(formData.value(key).toPercentEncoding())).toUtf8()); 50 | } 51 | return formUrl; 52 | } 53 | 54 | QMap FormUrlCodec::decodeFormUrl(QByteArray formUrl) { 55 | QMap formData; 56 | QList formFields = formUrl.split('&'); 57 | foreach(QByteArray formField, formFields) { 58 | QList nameValue = formField.split('='); 59 | if(nameValue.count() >= 2) { 60 | QString fieldName = QString::fromUtf8(nameValue.at(0)); 61 | QByteArray fieldValue = QByteArray::fromPercentEncoding(nameValue.at(1)); 62 | formData.insert(fieldName, fieldValue); 63 | } 64 | } 65 | return formData; 66 | } 67 | 68 | } // namespace Util 69 | 70 | } // namespace QtWebServer 71 | -------------------------------------------------------------------------------- /util/utilformurlcodec.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | #include 30 | 31 | namespace QtWebServer { 32 | 33 | namespace Util { 34 | 35 | class FormUrlCodec { 36 | public: 37 | /** Encodes the form data into an URL. */ 38 | static QByteArray encodeFormUrl(QMap formData); 39 | 40 | /** Decodes the form data from an URL. */ 41 | static QMap decodeFormUrl(QByteArray formUrl); 42 | 43 | private: 44 | FormUrlCodec(); 45 | ~FormUrlCodec(); 46 | }; 47 | 48 | } // namespace Util 49 | 50 | } // namespace QtWebServer 51 | -------------------------------------------------------------------------------- /weblayout.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #include "weblayout.h" 25 | 26 | #include "html/htmldocument.h" 27 | 28 | namespace QtWebServer { 29 | 30 | WebLayout::WebLayout() { 31 | } 32 | 33 | void WebLayout::addCss(QString resourcePath) { 34 | _cssResources << resourcePath; 35 | } 36 | 37 | void WebLayout::addJs(QString resourcePath) { 38 | _jsResources << resourcePath; 39 | } 40 | 41 | void WebLayout::addWebWidget(WebWidget* webWidget) { 42 | _webWidgets << webWidget; 43 | } 44 | 45 | QString WebLayout::renderHtml(const Http::Request& request) { 46 | Html::Document document; 47 | document.setTitle(title()); 48 | 49 | foreach(QString resource, _cssResources) { 50 | QDomElement linkNode = document.createElement("link"); 51 | linkNode.setAttribute("href", resource); 52 | linkNode.setAttribute("rel", "stylesheet"); 53 | linkNode.setAttribute("type", "text/css"); 54 | document.head().appendChild(linkNode); 55 | } 56 | 57 | foreach(QString resource, _jsResources) { 58 | QDomElement scriptNode = document.createElement("script"); 59 | scriptNode.setAttribute("src", resource); 60 | scriptNode.setAttribute("type", "text/javascript"); 61 | 62 | // We have to put in this hack because self-closing script 63 | // tags are not allowed in HTML 64 | QDomText dummyText = document.createTextNode(""); 65 | scriptNode.appendChild(dummyText); 66 | 67 | document.body().appendChild(scriptNode); 68 | } 69 | 70 | foreach(WebWidget *webWidget, _webWidgets) { 71 | document.appendHtml( 72 | document.body(), 73 | webWidget->renderHtml(request) 74 | ); 75 | } 76 | 77 | return document.toString(); 78 | } 79 | 80 | void WebLayout::setTitle(QString title) { 81 | _title = title; 82 | } 83 | 84 | QString WebLayout::title() { 85 | return _title; 86 | } 87 | 88 | } // namespace QtWebServer 89 | -------------------------------------------------------------------------------- /weblayout.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | 30 | // QtWebServer includes 31 | #include "http/httprequest.h" 32 | #include "html/htmldocument.h" 33 | 34 | // Own includes 35 | #include "webwidget.h" 36 | 37 | namespace QtWebServer { 38 | class WebLayout { 39 | public: 40 | WebLayout(); 41 | 42 | void addCss(QString resourcePath); 43 | void addJs(QString resourcePath); 44 | void addWebWidget(WebWidget* webWidget); 45 | 46 | virtual QString renderHtml(const Http::Request& request); 47 | 48 | void setTitle(QString title); 49 | QString title(); 50 | 51 | protected: 52 | QString _title; 53 | QStringList _cssResources; 54 | QStringList _jsResources; 55 | QList _webWidgets; 56 | }; 57 | 58 | } // namespace QtWebServer 59 | -------------------------------------------------------------------------------- /webwidget.h: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2010-2015 Jacob Dawid 3 | // 4 | // This file is part of QtWebServer. 5 | // 6 | // QtWebServer is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU Affero General Public License as 8 | // published by the Free Software Foundation, either version 3 of the 9 | // License, or (at your option) any later version. 10 | // 11 | // QtWebServer is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU Affero General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU Affero General Public 17 | // License along with QtWebServer. 18 | // If not, see . 19 | // 20 | // It is possible to obtain a commercial license of QtWebServer. 21 | // Please contact Jacob Dawid 22 | // 23 | 24 | #pragma once 25 | 26 | // Qt includes 27 | #include 28 | #include 29 | 30 | // Own includes 31 | #include "http/httprequest.h" 32 | 33 | namespace QtWebServer { 34 | 35 | class WebWidget : 36 | public QObject { 37 | Q_OBJECT 38 | public: 39 | WebWidget(QObject *parent = 0) : QObject(parent) {} 40 | virtual ~WebWidget() {} 41 | 42 | virtual QString renderHtml(const Http::Request& request) = 0; 43 | }; 44 | 45 | } // namespace QtWebServer 46 | --------------------------------------------------------------------------------