Browse Source

first public release

master
Ivan Polyakov 2 years ago
commit
be62c187b6
  1. 11
      .clang-format
  2. 19
      .clangd
  3. 83
      .drone.yml
  4. 6
      .editorconfig
  5. 47
      .gitignore
  6. 674
      COPYING
  7. 92
      Makefile
  8. 35
      README.md
  9. 174
      c/app.c
  10. 102
      c/keyval.c
  11. 94
      c/query.c
  12. 91
      c/request.c
  13. 106
      c/response.c
  14. 19
      c/route.c
  15. 87
      c/url.c
  16. 16
      c/utils.c
  17. 9
      c/utils.h
  18. 48
      config.mk
  19. 19
      cxx/KeyVal.cxx
  20. 36
      cxx/Response.cxx
  21. 46
      cxx/Route.cxx
  22. 1
      docs/.gitignore
  23. 2693
      docs/Doxyfile
  24. 65
      docs/src/development.dox
  25. 40
      docs/src/get_started.dox
  26. 11
      docs/src/index.dox
  27. 22
      examples/Makefile
  28. 20
      examples/README.md
  29. 56
      examples/c/example.c
  30. 54
      examples/c/minimal.c
  31. 52
      examples/cxx/example.cxx
  32. 41
      examples/cxx/minimal.cxx
  33. 11
      examples/example-site.nginx.conf
  34. 21
      examples/fastcgi_params
  35. 65
      include/App.hxx
  36. 102
      include/KeyVal.hxx
  37. 65
      include/Query.hxx
  38. 111
      include/Request.hxx
  39. 132
      include/Response.hxx
  40. 139
      include/Route.hxx
  41. 78
      include/Url.hxx
  42. 67
      include/app.h
  43. 92
      include/keyval.h
  44. 42
      include/query.h
  45. 15
      include/rapida.h
  46. 13
      include/rapida.hxx
  47. 72
      include/request.h
  48. 124
      include/response.h
  49. 54
      include/route.h
  50. 72
      include/url.h
  51. 26
      tests/app.cxx
  52. 44
      tests/keyval.cxx
  53. 80
      tests/query.cxx
  54. 5
      tests/tests.cxx
  55. 11
      tests/tests.hxx
  56. 59
      tests/url.cxx

11
.clang-format

@ -0,0 +1,11 @@
ColumnLimit: 80
---
Language: Cpp
BasedOnStyle: webkit
UseTab: Never
IndentWidth: 4
PointerAlignment: Right
SpaceAfterCStyleCast: true

19
.clangd

@ -0,0 +1,19 @@
CompileFlags:
Add: [-Wall, -pedantic, -I../include, -DEXTENSIONS_INJA,
-DDIST_PATH="/var/www/html"]
---
# Specific C sources
If:
PathMatch: [.*\.c, .*\.h]
CompileFlags:
Add: [-std=gnu99]
---
# Fragment specific to C++ source files
If:
PathExclude: [.*\.c, .*\.h]
CompileFlags:
Add: [-std=c++17, `pkg-config --cflags catch2`]

83
.drone.yml

@ -0,0 +1,83 @@
kind: pipeline
type: docker
name: development
when:
event: [ push ]
branch: [ dev ]
trigger:
branch:
- dev
steps:
- name: build
image: gcc:11-bullseye
commands:
- apt update -y
- apt install -y libfcgi-dev libfcgi-bin doxygen
- make all DEBUG=1
- make docs
#- name: tests
# image: gcc:11-bullseye
# commands:
# - apt update -y
# - apt install -y libfcgi-dev libfcgi-bin catch2
# - make -j1 run_tests
# - ./run_tests
- name: deploy-docs
image: drillster/drone-rsync
settings:
hosts:
from_secret: deploy_docs_hosts
user:
from_secret: deploy_docs_user
key:
from_secret: deploy_docs_ssh_key
target:
from_secret: deploy_docs_dev_target
source: docs/dist/html/
---
kind: pipeline
type: docker
name: production
when:
event: [ push ]
branch: [ master ]
trigger:
branch:
- master
steps:
- name: build
image: gcc:11-bullseye
commands:
- apt update -y
- apt install -y libfcgi-dev libfcgi-bin doxygen
- make all DEBUG=1
- make docs
#- name: tests
# image: gcc:11-bullseye
# commands:
# - apt update -y
# - apt install -y libfcgi-dev libfcgi-bin catch2
# - make -j1 run_tests
# - ./run_tests
- name: deploy-docs
image: drillster/drone-rsync
settings:
hosts:
from_secret: deploy_docs_hosts
user:
from_secret: deploy_docs_user
key:
from_secret: deploy_docs_ssh_key
target:
from_secret: deploy_docs_target
source: docs/dist/html/

6
.editorconfig

@ -0,0 +1,6 @@
[*.{c*,h*}]
indent_style = space
indent_size = 4
end_of_line = lf
trim_trailing_whitespace = true
max_line_length = 80

47
.gitignore vendored

@ -0,0 +1,47 @@
# ---> C++
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Debug symbols
*.dSYM
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so*
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
run_tests
# Editors
*~
.idea
.vs
.vscode
# Dist
*.tar*
rapida-*.*

674
COPYING

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

92
Makefile

@ -0,0 +1,92 @@
include config.mk
CXXSRC := $(shell find cxx -type f -name '*.cxx')
CSRC += $(shell find c -type f -name '*.c')
CXXOBJ := $(CXXSRC:.cxx=.o)
COBJ := $(CSRC:.c=.o)
#target C and C++ libraries
all: librapida.a librapida.so librapidaxx.a librapidaxx.so
#target Distribution
dist: all
mkdir -p rapida-$(VERSION)/lib
cp -rf README.md COPYING include rapida-$(VERSION)
mv librapida.so librapida.so.$(VERSION)
mv librapidaxx.so librapidaxx.so.$(VERSION)
cp -f *.a *.so* rapida-$(VERSION)/lib
tar cf rapida-$(VERSION).tar rapida-$(VERSION)
gzip rapida-$(VERSION).tar
rm -rf rapida-$(VERSION)
install: all
mv librapida.so librapida.so.$(VERSION)
mv librapidaxx.so librapidaxx.so.$(VERSION)
install librapida.a $(PREFIX)/lib
install librapidaxx.a $(PREFIX)/lib
install librapida.so.$(VERSION) $(PREFIX)/lib
install librapidaxx.so.$(VERSION) $(PREFIX)/lib
ln -s $(PREFIX)/lib/librapida.so.$(VERSION) $(PREFIX)/lib/librapida.so
ln -s $(PREFIX)/lib/librapidaxx.so.$(VERSION) $(PREFIX)/lib/librapidaxx.so
mkdir -p $(PREFIX)/include/rapida
cp -f include/* $(PREFIX)/include/rapida
uninstall:
rm -f $(PREFIX)/lib/librapida.a
rm -f $(PREFIX)/lib/librapidaxx.a
rm -f $(PREFIX)/lib/librapida.so*
rm -f $(PREFIX)/lib/librapidaxx.so*
rm -rf $(PREFIX)/include/rapida
#target Shared C library
librapida.so: $(COBJ)
$(CC) -shared $^ -o $@ $(LDFLAGS)
#target Shared C++ library
librapidaxx.so: $(COBJ) $(CXXOBJ)
$(CXX) -shared $^ -o $@ $(LDFLAGS)
#target Static C library
librapida.a: $(COBJ)
ar rvs $@ $^
#target Static C++ library
librapidaxx.a: $(COBJ) $(CXXOBJ)
ar rvs $@ $^
c/%.o: c/%.c
$(CC) $(CFLAGS) -fPIC $< -c -o $@
cxx/%.o: cxx/%.cxx
$(CXX) $(CXXFLAGS) $(CXXSTD) -fPIC $< -c -o $@
#target Tests runner
run_tests: tests/*.cxx librapidaxx.a
$(CXX) $(CXXFLAGS) -std=c++17 `pkg-config --cflags catch2` $^ -o $@ $(LDFLAGS)
#target Clear project from generated files
clean:
rm -f **/*.o *.a *.so* run_tests
#target Clear project from generated and distribution files
distclean: clean
rm -f *.tar*
#target Generate documentation
docs:
cd $@ && VERSION=$(VERSION) doxygen
#target Format code
format:
clang-format -Werror -i $(CSRC) $(CXXSRC)
clang-format -Werror -i examples/*.c*
clang-format -Werror -i tests/*.c* tests/*.h*
#target Show this help
help:
@echo "$$(tput bold)Usage:$$(tput sgr0)\nmake <target> [flags...] [args...]\n"
@echo "$$(tput bold)Targets:$$(tput sgr0)";echo;sed -ne"/^#target /{h;s/.*//;:d" -e"H;n;s/^#target //;td" -e"s/:.*//;G;s/\\n#target /---/;s/\\n/ /g;p;}" ${MAKEFILE_LIST}|awk -F --- -v n=$$(tput cols) -v i=29 -v a="$$(tput setaf 6)" -v z="$$(tput sgr0)" '{printf"%s%*s%s ",a,-i,$$1,z;m=split($$2,w," ");l=n-i;for(j=1;j<=m;j++){l-=length(w[j])+1;if(l<= 0){l=n-i-length(w[j])-1;printf"\n%*s ",-i," ";}printf"%s ",w[j];}printf"\n";}'
@echo "\n$$(tput bold)Flags (All values other than '0' are true):$$(tput sgr0)";echo;sed -ne"/^#flag /{h;s/.*//;:d" -e"H;n;s/^#flag //;td" -e"s/:.*//;G;s/\\n#flag /---/;s/\\n/ /g;p;}" ${MAKEFILE_LIST}|awk -F --- -v n=$$(tput cols) -v i=29 -v a="$$(tput setaf 6)" -v z="$$(tput sgr0)" '{printf"%s%*s%s ",a,-i,$$1,z;m=split($$2,w," ");l=n-i;for(j=1;j<=m;j++){l-=length(w[j])+1;if(l<= 0){l=n-i-length(w[j])-1;printf"\n%*s ",-i," ";}printf"%s ",w[j];}printf"\n";}'
@echo "\n$$(tput bold)Arguments:$$(tput sgr0)";echo;sed -ne"/^#arg /{h;s/.*//;:d" -e"H;n;s/^#arg //;td" -e"s/:.*//;G;s/\\n#arg /---/;s/\\n/ /g;p;}" ${MAKEFILE_LIST}|awk -F --- -v n=$$(tput cols) -v i=29 -v a="$$(tput setaf 6)" -v z="$$(tput sgr0)" '{printf"%s%*s%s ",a,-i,$$1,z;m=split($$2,w," ");l=n-i;for(j=1;j<=m;j++){l-=length(w[j])+1;if(l<= 0){l=n-i-length(w[j])-1;printf"\n%*s ",-i," ";}printf"%s ",w[j];}printf"\n";}'
.PHONY: help clean distclean docs format

35
README.md

@ -0,0 +1,35 @@
Rapida
======
[![Build Status](http://drone.vilor.one/api/badges/Rapida/rapida/status.svg)](http://drone.vilor.one/Rapida/rapida)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
Rapida is the C and C++ web framework based on FastCGI protocol.
Dependencies
------------
* libfcgi
* doxygen (to make docs)
* catch2 (to run tests)
Extensions
----------
* [inja](https://github.com/pantor/inja) (template rendering,
requires [nlohmann/json](https://github.com/nlohmann/json))
Building
--------
You need:
* GNU Make
* C compiler with C99 support
* C++ compiler with C++98 and C++17 support
Run `make help` to see targets, flags and arguments.
Examples
--------
See [examples](examples).
License
-------
GPLv3 or later. See full text in the [COPYING](COPYING) file
or in GNU website: https://www.gnu.org/licenses/gpl-3.0-standalone.html

174
c/app.c

@ -0,0 +1,174 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "app.h"
#include <stdlib.h>
#include <string.h>
#ifdef MT_ENABLED
#include <pthread.h>
#endif /* MT_ENABLED */
/*!
* \brief Listens new requests by FastCGI protocol.
* \param app Pointer to current App instance.
* \return Always returns NULL.
*/
static void *listen_requests(void *app);
/*!
* Handle accepted request.
* \param app Application instance.
* \param req FastCGI request.
*/
static void handle_request(rpd_app *app, FCGX_Request *fcgx_req);
/*!
* \brief Selects a route handler based on requested path.
* \param app Application instance.
* \param req Request.
* \return Pointer to route handler.
*/
static rpd_route *routes_fabric(rpd_app *app, rpd_req *req);
int rpd_app_create(rpd_app *app, const char *sock_path)
{
app->running = app->sock_id = app->routes_len = 0;
app->routes = NULL;
app->sock_path = strdup(sock_path);
if (!app->sock_path)
return 1;
FCGX_Init();
return 0;
}
int rpd_app_start(rpd_app *app)
{
if ((app->sock_id = FCGX_OpenSocket(app->sock_path, 10)) < 0) {
return 1;
}
#ifdef MT_ENABLED
pthread_t threads[NTHREADS];
for (int i = 0; i < NTHREADS; i++) {
pthread_create(&threads[i], 0, listen_requests, (void *) app);
pthread_join(threads[i], 0);
}
#else
listen_requests((void *) app);
#endif
return 0;
}
int rpd_app_add_route(rpd_app *app, const char *path, rpd_route_cb cb,
void *userdata)
{
rpd_route route;
if (rpd_route_init(&route, path, cb, userdata))
return 1;
app->routes = (rpd_route *) realloc(app->routes, sizeof(rpd_route) * (app->routes_len + 1));
if (!app->routes)
return 2;
app->routes[app->routes_len++] = route;
return 0;
}
static void *listen_requests(void *userdata)
{
rpd_app *app = (rpd_app *) userdata;
FCGX_Request req;
if (FCGX_InitRequest(&req, app->sock_id, 0)) {
return 0;
}
app->running = 1;
while (app->running) {
#ifdef MT_ENABLED
static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&accept_mutex);
#endif
int rc = FCGX_Accept_r(&req);
#ifdef MT_ENABLED
pthread_mutex_unlock(&accept_mutex);
#endif
if (rc < 0) {
break;
}
#ifdef MT_ENABLED
static pthread_mutex_t handle_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&handle_mutex);
#endif
handle_request(app, &req);
#ifdef MT_ENABLED
pthread_mutex_unlock(&handle_mutex);
#endif
FCGX_Finish_r(&req);
}
return 0;
}
static void handle_request(rpd_app *app, FCGX_Request *fcgx_req)
{
rpd_req req;
rpd_res res;
rpd_req_parse(&req, fcgx_req);
rpd_res_init(&res, fcgx_req);
// get route and process request
rpd_route *route = routes_fabric(app, &req);
if (!route) {
return;
}
route->cb(&req, &res, route->userdata);
rpd_res_send(&res);
rpd_req_cleanup(&req);
rpd_res_cleanup(&res);
}
static rpd_route *routes_fabric(rpd_app *app, rpd_req *req)
{
const rpd_url *req_path, *route_path = 0;
req_path = &req->path;
for (int i = 0; i < app->routes_len; i++) {
route_path = &app->routes[i].path;
if (req_path->parts_len != route_path->parts_len)
continue;
int match = 1;
for (int j = 0; j < route_path->parts_len && match; j++) {
int cur_part_is_dyn = route_path->parts[i][0] == ':';
if (!cur_part_is_dyn && strcmp(req_path->parts[i], route_path->parts[i])) {
match = 0;
}
}
if (!match)
continue;
rpd_keyval_init(&req->params, 0);
rpd_url_params_parse_keys(&req->params, route_path);
rpd_url_params_parse_vals(&req->params, req_path, route_path);
return &app->routes[i];
}
return NULL;
}

102
c/keyval.c

@ -0,0 +1,102 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "keyval.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*!
* \brief Reallocate key-value storage with new capacity.
*
* \param keyval Key-value storage.
* \param capacity New capacity.
*
* \return Status code.
*/
static int rpd_keyval_realloc(rpd_keyval *keyval, int capacity);
int rpd_keyval_init(rpd_keyval *keyval, int capacity)
{
keyval->size = keyval->capacity = 0;
if (capacity == 0) {
keyval->items = NULL;
return 0;
}
keyval->items = (rpd_keyval_item *) malloc(sizeof(rpd_keyval_item) * capacity);
if (!keyval->items) {
return 1;
}
keyval->capacity = capacity;
return 0;
}
int rpd_keyval_insert(rpd_keyval *keyval, const char *key, const char *value)
{
if (!key || !value)
return 1;
if (keyval->size == keyval->capacity) {
int tmp = keyval->capacity == 0 ? 10 : keyval->capacity * 2;
if ((tmp = rpd_keyval_realloc(keyval, tmp)))
return tmp;
}
rpd_keyval_item *item = rpd_keyval_find(keyval, key);
if (item) {
free(item->key);
item->key = NULL;
if (item->val) {
free(item->val);
item->val = NULL;
}
} else {
item = &keyval->items[keyval->size];
keyval->size++;
}
item->key = strdup(key);
item->val = strdup(value);
return item->key && item->val ? 0 : 2;
}
rpd_keyval_item *rpd_keyval_find(const rpd_keyval *keyval, const char *key)
{
int i = 0;
while (i < keyval->size) {
if (!strcmp(keyval->items[i].key, key)) {
return keyval->items + i;
}
i++;
}
return NULL;
}
void rpd_keyval_cleanup(rpd_keyval *keyval)
{
if (keyval->items) {
int i = 0;
while (i < keyval->size) {
rpd_keyval_item *item = keyval->items + i;
free(item->key);
if (item->val) {
free(item->val);
}
i++;
}
}
keyval->size = 0;
}
static int rpd_keyval_realloc(rpd_keyval *keyval, int capacity)
{
keyval->items = realloc(keyval->items, sizeof(rpd_keyval_item) * capacity);
if (!keyval->items) {
return 1;
}
keyval->capacity = capacity;
return 0;
}

94
c/query.c

@ -0,0 +1,94 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "query.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int rpd_query_parse(rpd_keyval *dest, const char *src)
{
int len = count_char_entries(src, '=');
if (!len) {
if (dest->items) {
free(dest->items);
}
dest->items = NULL;
dest->capacity = 0;
dest->size = 0;
return 0;
}
char *query = strdup(src);
if (!query)
return 1;
dest->items = realloc(dest->items, sizeof(rpd_keyval_item *) * len);
if (!dest->items)
return 2;
dest->capacity = len;
char *tokens = query, *p = query;
int i = 0;
while ((p = strsep(&tokens, "&\n")) && i < len) {
char *param, *val;
if (*p == '=')
continue;
param = strtok(p, "=");
val = strtok(NULL, "=");
if (param) {
dest->items[i].key = strdup(param);
dest->items[i].val = val ? strdup(val) : NULL;
i++;
}
}
dest->size = i;
dest->capacity = i;
free(query);
return 0;
}
char *rpd_query_str(const rpd_keyval *query)
{
size_t len = 0;
rpd_keyval_item *item;
for (int i = 0; i < query->size; i++) {
item = &query->items[i];
if (!item->key || !item->val)
continue;
len += strlen(item->key) + strlen(item->val);
}
/* len + number of key-val delimeters + terminating char */
size_t size = len + (query->size - 1) + 1;
if (size <= 0)
return NULL;
char *buff = (char *) malloc(sizeof(char) * size);
if (!buff)
return NULL;
buff[size - 1] = '\0';
size_t offset = 0;
for (int i = 0; i < query->size; i++) {
item = &query->items[i];
if (!item->key || !item->val)
continue;
offset += sprintf(buff + offset, "%s=%s", item->key, item->val);
if (i + 1 < query->size) {
buff[offset] = '&';
offset++;
}
}
if (buff[offset - 1] == '&') {
buff[offset - 1] = '\0';
}
return buff;
}

91
c/request.c

@ -0,0 +1,91 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "request.h"
#include <stdlib.h>
#include <string.h>
static int rpd_req_read_body(char **dest, FCGX_Request *req);
enum rpd_req_methods rpd_req_smethod(const char *method)
{
if (!strcmp(method, "GET"))
return GET;
else if (!strcmp(method, "HEAD"))
return HEAD;
else if (!strcmp(method, "POST"))
return POST;
else if (!strcmp(method, "PUT"))
return PUT;
else if (!strcmp(method, "PATCH"))
return PATCH;
else if (!strcmp(method, "DELETE"))
return DELETE;
else if (!strcmp(method, "CONNECT"))
return CONNECT;
else if (!strcmp(method, "OPTIONS"))
return OPTIONS;
else if (!strcmp(method, "TRACE"))
return TRACE;
return UNKNOWN;
}
int rpd_req_parse(rpd_req *dest, FCGX_Request *req)
{
rpd_query_parse(&dest->query, FCGX_GetParam("QUERY_STRING", req->envp));
dest->method = rpd_req_smethod(FCGX_GetParam("REQUEST_METHOD", req->envp));
rpd_url_parse(&dest->path, FCGX_GetParam("DOCUMENT_URI", req->envp));
dest->auth = FCGX_GetParam("HTTP_AUTHORIZATION", req->envp);
dest->cookie = FCGX_GetParam("HTTP_COOKIE", req->envp);
rpd_keyval_init(&dest->params, 0);
if (dest->method != GET) {
if (rpd_req_read_body(&dest->body, req)) {
return 2;
}
} else {
dest->body = NULL;
}
return 0;
}
static int rpd_req_read_body(char **dest, FCGX_Request *req)
{
char *clen = FCGX_GetParam("CONTENT_LENGTH", req->envp);
if (!clen)
return 1;
size_t len = atoll(clen);
*dest = (char *) malloc(sizeof(char) * (len + 1));
if (!*dest)
return 2;
*dest[len] = '\0';
FCGX_GetStr(*dest, len, req->in);
return 0;
}
void rpd_req_cleanup(rpd_req *req)
{
rpd_keyval_cleanup(&req->params);
if (req->body) {
free(req->body);
req->body = NULL;
}
if (req->query.size) {
rpd_keyval_cleanup(&req->query);
}
if (req->params.size) {
for (int i = 0; i < req->params.size; i++) {
rpd_keyval_item *item = req->params.items + i;
free(item->val);
item->val = NULL;
}
}
}

106
c/response.c

@ -0,0 +1,106 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "response.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static size_t calc_res_buff_sz(const rpd_res *res);
void rpd_res_init(rpd_res *dest, FCGX_Request *req)
{
dest->out = req->out;
dest->status = rpd_res_st_ok;
dest->location = dest->content_type = NULL;
dest->body = NULL;
rpd_keyval_init(&dest->cookie, 0);
}
int rpd_res_send(rpd_res *res)
{
size_t size = calc_res_buff_sz(res);
char *buff = (char *) malloc(sizeof(char) * size);
if (!buff) {
return 1;
}
/* header */
char *ptr = buff;
ptr += sprintf(ptr, "Status: %d\r\n", res->status);
if (res->content_type) {
ptr += sprintf(ptr, "Content-Type: %s\r\n", res->content_type);
}
if (res->location) {
ptr += sprintf(ptr, "Location: %s\r\n", res->location);
}
memcpy(ptr, "\r\n", 2);
ptr += 2;
/* body */
if (res->body) {
int bodylen = strlen(res->body);
memcpy(ptr, res->body, bodylen);
ptr += bodylen;
}
FCGX_PutS(buff, res->out);
free(buff);
return 0;
}
static size_t calc_res_buff_sz(const rpd_res *res)
{
size_t size = res->body ? strlen(res->body) + 2 : 0;
size += strlen("Status: \r\n") + 3;
if (res->location) {
size += strlen("Location: \r\n") + strlen(res->location);
}
if (res->content_type) {
size += strlen("Content-Type: \r\n") + strlen(res->content_type);
}
if (res->cookie.size) {
size += strlen("Set-Cookie: \r\n") * res->cookie.size;
for (int i = 0; i < res->cookie.size; i++) {
rpd_keyval_item *item = res->cookie.items + i;
size += strlen(item->key) + strlen(item->val);
}
}
size += 2;
return size;
}
void rpd_res_cleanup(rpd_res *res)
{
res->status = rpd_res_st_ok;
if (res->location) {
free(res->location);
res->location = NULL;
}
if (res->content_type) {
free(res->content_type);
res->content_type = NULL;
}
if (res->body) {
free(res->body);
res->body = NULL;
}
if (res->cookie.capacity) {
rpd_keyval_cleanup(&res->cookie);
}
}

19
c/route.c

@ -0,0 +1,19 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "route.h"
int rpd_route_init(rpd_route *dest, const char *path, rpd_route_cb cb,
void *userdata)
{
rpd_url url;
if (rpd_url_parse(&url, path)) {
return 1;
}
dest->path = url;
dest->cb = cb;
dest->userdata = userdata;
return 0;
}

87
c/url.c

@ -0,0 +1,87 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "../include/url.h"
#include "utils.h"
#include <stdlib.h>
#include <string.h>
int rpd_url_parse(rpd_url *dest, const char *src)
{
const char *del = "/";
int i = count_char_entries(src, del[0]);
if (!i) {
dest->parts_len = 0;
return 0;
}
dest->parts = (char **) malloc(sizeof(char **) * i);
if (!dest->parts) {
dest->parts_len = 0;
return 2;
}
i = 0;
char *tmp, *token;
tmp = strdup(src);
while ((token = strsep(&tmp, "/"))) {
if (!strlen(token))
continue;
dest->parts[i] = strdup(token);
i++;
}
free(tmp);
dest->parts_len = i;
return 0;
}
void rpd_url_cleanup(rpd_url *url)
{
int i = 0;
while (i < url->parts_len) {
free(url->parts[i]);
i++;
}
free(url->parts);
url->parts = NULL;
url->parts_len = 0;
}
int rpd_url_params_parse_keys(rpd_keyval *dest, const rpd_url *tpl)
{
int len = 0;
for (int i = 0; i < tpl->parts_len; i++) {
if (*tpl->parts[i] == ':') {
len++;
}
}
dest->items = malloc(sizeof(rpd_keyval_item) * len);
if (!dest->items)
return 1;
dest->size = 0;
dest->capacity = len;
for (int i = 0; i < tpl->parts_len; i++) {
if (*tpl->parts[i] == ':') {
dest->items[dest->size].key = strdup(tpl->parts[i] + 1);
dest->size++;
}
}
return 0;
}
int rpd_url_params_parse_vals(rpd_keyval *dest, const rpd_url *url, const rpd_url *tpl)
{
int i = 0, j = 0;
while (i < tpl->parts_len) {
if (*tpl->parts[i] == ':') {
dest->items[j++].val = strdup(url->parts[i]);
}
i++;
}
return 0;
}

16
c/utils.c

@ -0,0 +1,16 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "utils.h"
int count_char_entries(const char *str, char ch)
{
int cnt = 0;
while (*str) {
if (*str == ch) {
cnt++;
}
str++;
}
return cnt;
}

9
c/utils.h

@ -0,0 +1,9 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_UTILS_H_ENTRY
#define RAPIDA_UTILS_H_ENTRY
int count_char_entries(const char *str, char ch);
#endif /* RAPIDA_UTILS_H_ENTRY */

48
config.mk

@ -0,0 +1,48 @@
VERSION=0.2.0
#arg Installation prefix
PREFIX=/usr/local
CC=gcc
CFLAGS=-std=gnu99 -pedantic -Iinclude
CXX=c++
CXXFLAGS=-pedantic -Iinclude
CXXSTD=-ansi
LDFLAGS=-lfcgi
#flag Debug mode
DEBUG ?= 0
ifneq ($(DEBUG), 0)
CFLAGS+=-Wall -g -DDEBUG_MODE
CXXFLAGS+=-Wall -g -DDEBUG_MODE
else
CFLAGS+=-O3
CXXFLAGS+=-O3
endif
#arg Additional CXX flags
ADD_CXXFLAGS =
ifdef ADD_CXXFLAGS
CXXFLAGS+=$(ADD_CXXFLAGS)
endif
#flag Enable inja extension
EXTENSIONS_INJA ?= 0
#arg Dist path. Needed only if inja is enabled.
DIST_PATH = /var/www/html
ifneq ($(EXTENSIONS_INJA), 0)
CXXFLAGS+=-DEXTENSIONS_INJA -DDIST_PATH=\"$(DIST_PATH)\"
CXXSTD=-std=c++17
endif
#flag Multithread support
MT_ENABLED ?= 0
#arg Number of threads. 8 by default.
NTHREADS = 8
ifneq ($(MT_ENABLED), 0)
CXXFLAGS+=-DMT_ENABLED -DNTHREADS=$(NTHREADS)
CFLAGS+=-DMT_ENABLED -DNTHREADS=$(NTHREADS)
LDFLAGS+=-lpthread
endif

19
cxx/KeyVal.cxx

@ -0,0 +1,19 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "KeyVal.hxx"
#include <stdlib.h>
using namespace rpd;
KeyVal::KeyVal()
: _keyval((rpd_keyval *) malloc(sizeof(rpd_keyval)))
{
rpd_keyval_init(_keyval, 0);
}
KeyVal::KeyVal(int capacity)
: _keyval((rpd_keyval *) malloc(sizeof(rpd_keyval)))
{
rpd_keyval_init(_keyval, capacity);
}

36
cxx/Response.cxx

@ -0,0 +1,36 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "Response.hxx"
#ifdef EXTENSIONS_INJA
#include <inja/inja.hpp>
#endif
using namespace rpd;
#ifdef EXTENSIONS_INJA
void Response::render(const char *path, nlohmann::json data)
{
inja::Environment env;
inja::Template tpl;
try {
std::string tplpath = DIST_PATH;
tplpath += path;
tpl = env.parse_template(tplpath);
} catch (inja::FileError &e) {
std::cerr << e.what() << std::endl;
return;
}
try {
std::string result = env.render(tpl, data);
body(result.c_str());
} catch (inja::RenderError &e) {
std::cerr << e.what() << std::endl;
status(internal_server_error);
return;
}
}
#endif

46
cxx/Route.cxx

@ -0,0 +1,46 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "Route.hxx"
#include <stdio.h>
using namespace rpd;
void Route::handle_request(rpd_req *req, rpd_res *res, void *userdata)
{
Route *route = static_cast<Route *>(userdata);
const Request reqxx = req;
Response resxx = res;
switch (req->method) {
case GET:
route->handle_get(reqxx, resxx);
break;
case HEAD:
route->handle_head(reqxx, resxx);
break;
case POST:
route->handle_post(req, resxx);
break;
case PUT:
route->handle_put(req, resxx);
break;
case PATCH:
route->handle_patch(req, resxx);
break;
case DELETE:
route->handle_delete(req, resxx);
break;
case CONNECT:
route->handle_connect(req, resxx);
break;
case OPTIONS:
route->handle_options(req, resxx);
break;
case TRACE:
route->handle_trace(req, resxx);
break;
case UNKNOWN:
break;
}
}

1
docs/.gitignore vendored

@ -0,0 +1 @@
dist

2693
docs/Doxyfile

File diff suppressed because it is too large Load Diff

65
docs/src/development.dox

@ -0,0 +1,65 @@
/**
\page development Development
Overview
--------
We use:
- Catch2 library for writing tests.
\warning We are currently on version 2.
- Doxygen to generate documentation.
- clangd for hints.
- clang-format for code formatting.
- GNU Make to build the project.
You can see the targets, flags and arguments by runnig `make help`.
Code style
----------
We are using a WebKit-based coding style with some differences,
see `.clang-format` at the project root.
Please use the _clang-format_ to keep code style.
Also you can automatically run formatting with `make format`.
Licensing rules
---------------
Add an SPDX license notice to top of every file you create.
Notice format:
```
/* SPDX-License-Identifier: <SPDX License Expression> */
```
If you edit exist file, add your copyright info.
Copyright notice format:
```
/* Copyright <YEAR> <AUTHOR> */
```
Writing tests
-------------
For writing tests we are using the
[Catch2](https://github.com/catchorg/Catch2) library.
Read it's
[tutorial](https://github.com/catchorg/Catch2/blob/devel/docs/tutorial.md#top)
to be aware.
Tests placed at the `tests` directory of the project root and can be built
by ranning `make run_tests`. `run_tests` executable will be built.
Writing docs
------------
All code of this project should be documented,
for docs generation we are use [Doxygen](http://doxygen.nl).
See Doxygen documentation and existing code to see an examples.
Rules:
- Documentation pages like this placed in `docs/src`.
- Use Qt-style documentation.
*/

40
docs/src/get_started.dox

@ -0,0 +1,40 @@
/**
\page get_started Get Started
Installation
------------
Run the following commands:
```sh
git clone http://git.vilor.one/rapida/rapida && cd rapida
make install
```
This will create the shared and static libraries
and install them on your system.
C example:
----------
\include minimal.c
C++ example:
------------
\include minimal.cxx
More examples you can find at http://git.vilor.one/rapida/rapida/examples
Building
--------
If you have installed Rapida on your system, just link it to your program.
- **rapida** for C apps.
- **rapidaxx** for C++.
For example:
```sh
gcc myapp.c -lrapida # link C library
g++ myapp.cxx -lrapidaxx # link C++ library
```
*/

11
docs/src/index.dox

@ -0,0 +1,11 @@
/**
\mainpage Rapida Manual
Rapida is the fast web framework written in C and C++.
Table of contents:
1. \subpage get_started
2. \subpage development
*/

22
examples/Makefile

@ -0,0 +1,22 @@
include ../config.mk
CXXSRC := $(shell find cxx -type f -name '*.cxx')
CXXBINS := $(CXXSRC:.cxx=)
CSRC := $(shell find c -type f -name '*.c')
CBINS := $(CSRC:.c=)
all: $(CBINS) $(CXXBINS)
%: %.c ../librapida.a
$(CC) $(CFLAGS) -I../include $^ -o $@ $(LDFLAGS)
%: %.cxx ../librapidaxx.a
$(CXX) $(CXXFLAGS) -std=c++11 -I../include $^ -o $@ $(LDFLAGS)
../librapida.a:
cd .. && make librapida.a
../librapidaxx.a:
cd .. && make librapidaxx.a
.PHONY: ../librapida.a ../librapidaxx.a

20
examples/README.md

@ -0,0 +1,20 @@
Examples
========
This example shows how to use a simple _rpd_ application with NGINX.
NGINX configuration
-------------------
In the location you want to process with rpd, provide the following lines:
```nginx
fastcgi_pass unix: /tmp/rpd.example.sock;
include fastcgi_params;
```
Where `/tmp/rpd.example.sock` is the UNIX socket you passed
to the rpd_app instance and fastcgi_params is the list
of variables that NGINX passes through the FastCGI protocol.
See examples:
* [example-site.nginx.conf](example-site.nginx.conf)
* [fastcgi_params](fastcgi_params)

56
examples/c/example.c

@ -0,0 +1,56 @@
#include "../../include/rapida.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void products_handler(rpd_req *req, rpd_res *res, void *userdata)
{
char *body = "<!DOCTYPE html>"
"<html>"
"<head><title>Product</title></head>"
"<body>"
"<h1>Product page</h1>"
"<pre>"
"Category: %s\n"
"Id: %s"
"</pre>"
"</body>"
"</html>";
rpd_keyval_item *cat = rpd_keyval_find(&req->params, "category");
rpd_keyval_item *id = rpd_keyval_find(&req->params, "id");
if (!cat || !id) {
res->status = rpd_res_st_internal_server_error;
return;
}
int bufflen = strlen(body) + strlen(cat->val) + strlen(id->val);
res->body = (char *) malloc(sizeof(char) * (bufflen + 1));
if (!res->body) {
res->status = rpd_res_st_internal_server_error;
return;
}
res->body[bufflen] = '\0';
sprintf(res->body, body, cat->val, id->val);
res->status = rpd_res_st_ok;
/*
* place all values in heap, please,
* because after call handler
* `req` and `res` will be freed
*/
res->content_type = strdup("text/html");
}
int main()
{
rpd_app app;
rpd_app_create(&app, "/tmp/rapida.example.socket");
rpd_app_add_route(&app, "/products/:category/:id", &products_handler, NULL);
rpd_app_start(&app);
return 0;
}

54
examples/c/minimal.c

@ -0,0 +1,54 @@
#include "../../include/rapida.h"
#include <string.h> /* for strdup() */
#include <stdio.h>
/*
* \brief Process home page request.
*
* \param req Request.
* \param res Response.
* \param userdata Additional data that you can pass to this handler
* when adding a route.
*/
static void home_page_handler(rpd_req *req, rpd_res *res, void *userdata)
{
/* Check request method */
switch (req->method) {
case GET:
/* Process GET request */
res->status = rpd_res_st_ok;
/* Please allocate data on the heap,
* because after calling this handler
* Rapida will free it all.
*/
res->content_type = strdup("text/plain");
res->body = strdup("Hello World!");
break;
default:
/* Other request methods are not implemented,
* so set the appropriate response status.
*/
res->status = rpd_res_st_not_implemented;
break;
}
/*
* You don't have to do something like send a response.
* Rapida will do this after calling this handler.
*/
}
int main()
{
rpd_app app;
/* Initialize application. */
rpd_app_create(&app, "/tmp/webapp.socket");
/* Add home "/" page handler. */
rpd_app_add_route(&app, "/", &home_page_handler, NULL);
/* Run the application and return its status code. */
return rpd_app_start(&app);
}

52
examples/cxx/example.cxx

@ -0,0 +1,52 @@
#include "../../include/rapida.hxx"
#include <sstream>
class ProductRoute : public rpd::Route {
protected:
virtual void handle_get(const rpd::Request &req, rpd::Response &res) override
{
rpd::KeyVal params = req.params();
const char *cat = params["category"];
const char *id = params["id"];
std::string body = "<!DOCTYPE html>"
"<html>"
"<head><title>Product</title></head>"
"<body>"
"<h1>Product page</h1>"
"<pre>";
body += "Category: ";
body += cat;
body += "\n";
body += "Id: ";
body += id;
body += "</pre>"
"</body>"
"</html>\r\n";
handle_head(req, res);
res.body(body.c_str());
}
virtual void handle_head(const rpd::Request &req, rpd::Response &res) override
{
res.status(rpd_res_st_ok);
res.content_type("text/html");
}
};
int main()
{
rpd::App app("/tmp/rapida.example.socket");
/*
* `category` and `id` are dynamic parameters
* that can be found in the `params` field in `Route`.
*/
app.add_route("/products/:category/:id", new ProductRoute());
return app.start();
}

41
examples/cxx/minimal.cxx

@ -0,0 +1,41 @@
#include "../../include/rapida.hxx"
/*
* \brief Home page route handler.
*/
class Home : public rpd::Route {
protected:
/*
* \brief Handle GET request.
*
* \param req Request.
* \param res Response.
*/
virtual void handle_get(const rpd::Request &req, rpd::Response &res) override
{
handle_head(req, res);
/* Unlike the C interface,
* the C++ wrapper will call `strdup` for you
*/
res.body("Hello World!");
}
/*
* \brief Handle HEAD request.
*/
virtual void handle_head(const rpd::Request &req, rpd::Response &res) override
{
res.status(rpd_res_st_ok);
res.content_type("text/plain");
}
};
int main()
{
rpd::App app("/tmp/webapp.socket");
app.add_route("/", new Home());
return app.start();
}

11
examples/example-site.nginx.conf

@ -0,0 +1,11 @@
server
{
listen 80;
server_name localhost;
location / products
{
fastcgi_pass unix : / tmp / rapida.example.sock;
include fastcgi_params;
}
}

21
examples/fastcgi_params

@ -0,0 +1,21 @@
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REQUEST_SCHEME $scheme;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param GATEWAY_INTERFACE CGI / 1.1;
fastcgi_param SERVER_SOFTWARE nginx / $nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;

65
include/App.hxx

@ -0,0 +1,65 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_APP_HXX_ENTRY
#define RAPIDA_APP_HXX_ENTRY
#include "Request.hxx"
#include "Response.hxx"
#include "Route.hxx"
#include "app.h"
namespace rpd {
/*!
* \brief C++ wrapper for Rapida application.
*/
class App {
public:
/*!
* Creates an rpd app and initializes FastCGI.
* \brief Constructor
* \param socket_path UNIX Socket path.
*/
App(const char *const socket_path)
{
rpd_app_create(&app, socket_path);
}
/*!
* \brief Starts the requests handling loop.
*/
int start()
{
return rpd_app_start(&app);
}
/*!
* \brief Stops the requests handling loop.
*/
void stop()
{
app.running = false;
}
/*!
* \brief Adds handler for the path.
*
* \param path Enpoint.
* \param route Route handler.
*/
void add_route(const char *const path, Route *route)
{
rpd_app_add_route(&app, path, &Route::handle_request, route);
}
/*!
* \brief Destructor.
*/
virtual ~App() { }
private:
rpd_app app; //< Composition with C implementation.
};
}
#endif // RAPIDA_APP_HXX_ENTRY

102
include/KeyVal.hxx

@ -0,0 +1,102 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_KEYVAL_HXX_ENTRY
#define RAPIDA_KEYVAL_HXX_ENTRY
#include "keyval.h"
namespace rpd {
/*!
* \brief C++ wrapper of the key-value pairs storage.
*/
class KeyVal {
public:
/*!
* \brief Default constructor.
*
* Create storage without initial allocation.
*/
KeyVal();
/*!
* \brief Constructor.
*
* \param capacity Initial capacity of this storage.
*/
KeyVal(int capacity);
/*!
* \brief Constructor
*
* \param keyval Base key-value storage (C implementation).
*/
KeyVal(rpd_keyval *keyval)
{
_keyval = keyval;
}
/*!
* \brief Returns real key-value storage.
*
* \return C key-value storage.
*/
rpd_keyval *keyval() const
{
return _keyval;
}
/*!
* \brief Get key-value pairs array.
*
* \return Key-value pairs.
*/
rpd_keyval_item *items() const
{
return _keyval->items;
}
/*!
* \brief Get number of key-value pairs in this storage.
*
* \return Number of entries.
*/
int size() const
{
return _keyval->size;
}
/*!
* \brief Get capacity of this storage (allocated memory);
*
* \return Allocated memory.
*/
int capacity() const
{
return _keyval->capacity;
}
/*!
* \brief Get value of key-value pair by it's key.
*
* \return Value or NULL.
*/
const char *operator[](const char *key)
{
return rpd_keyval_find(_keyval, key)->val;
}
/*!
* \brief Destructor.
*/
virtual ~KeyVal()
{
rpd_keyval_cleanup(_keyval);
}
private:
rpd_keyval *_keyval; //< Composition with C implementation.
};
}
#endif // RAPIDA_KEYVAL_HXX_ENTRY

65
include/Query.hxx

@ -0,0 +1,65 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_QUERY_HXX_ENTRY
#define RAPIDA_QUERY_HXX_ENTRY
#include "KeyVal.hxx"
#include "query.h"
namespace rpd {
/*!
* \brief Query storage in key-value format.
*/
class Query : public KeyVal {
public:
/*!
* \brief Default constructor.
*
* Just calls parent default costructor.
*/
Query()
: KeyVal()
{}
/*!
* \brief Constructor.
*
* \param keyval Key-value storage to base on it.
*
* Just calls parent constructor with base key-value storage.
*/
Query(rpd_keyval *keyval)
: KeyVal(keyval)
{}
/*!
* \brief Parse query string into the key-val pairs.
*
* \param query Query string.
*
* \return Status code. 0 is success.
*/
int parse(const char *query)
{
return rpd_query_parse(keyval(), query);
}
/*!
* \brief Convert key-val pairs to query string.
*
* \return Query string.
*/
char *c_str() const
{
return rpd_query_str(keyval());
}
/*!
* \brief Destructor.
*/
virtual ~Query() { }
};
}
#endif // RAPIDA_QUERY_HXX_ENTRY

111
include/Request.hxx

@ -0,0 +1,111 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_REQUEST_HXX_ENTRY
#define RAPIDA_REQUEST_HXX_ENTRY
#include "Query.hxx"
#include "request.h"
namespace rpd {
/*!
* \brief C++ request wrapper.
*/
class Request {
public:
/*!
* \brief Constructor.
*
* Creates C++ wrapper from original C request.
*
* \param req C request implementation.
*/
Request(rpd_req *req)
{
this->req = req;
}
/*!
* \brief Gets request method.
*
* \return Request method.
*/
rpd_req_methods method() const
{
return req->method;
}
/*!
* \brief Gets requested URL.
*
* \return Request URL.
*/
const rpd_url *path() const
{
return &req->path;
}
/*!
* \brief Gets query parameters.
*
* \return Query parameters.
*/
Query query() const
{
return &req->query;
}
/*!
* \brief Gets URL parameters.
*
* If you specify route like <b>/some/:dynamic/route</b>,
* middle route segment can be accesed by the _dynamic_ key.
*
* \return URL parameters as key-value pairs.
*/
KeyVal params() const
{
return &req->params;
}
/*!
* \brief Gets authorization string.
*
* \return Authorization string.
*/
const char *authorization() const
{
return req->auth;
}
/*!
* \brief Gets cookie string.
*
* \return Cookie string.
*/
const char *cookie() const
{
return req->cookie;
};
/*!
* \brief Gets request body content.
*
* \return Body content.
*/
const char *body() const
{
return req->body;
}
/*!
* \brief Destructor.
*/
virtual ~Request() { }
private:
rpd_req *req; //< Composition with C implementation.
};
}
#endif // RAPIDA_REQUEST_HXX_ENTRY

132
include/Response.hxx

@ -0,0 +1,132 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_RESPONSE_HXX_ENTRY
#define RAPIDA_RESPONSE_HXX_ENTRY
#include "response.h"
#include <stdlib.h>
#include <string.h>
#ifdef EXTENSIONS_INJA
#include <nlohmann/json.hpp>
#endif
namespace rpd {
/*!
* \brief C++ response wrapper.
*/
class Response {
public:
/*!
* \brief Constructor.
*
* Creates C++ wrapper from original C response.
*
* \param res C response implementation.
*/
Response(rpd_res *res)
{
this->res = res;
}
/*!
* \brief Sets response status code.
*
* See rpd_res_statuses enumeration.
*
* \param status Status code.
*/
void status(rpd_res_statuses status)
{
res->status = status;
}
/*!
* \brief Sets response status code.
*
* Sets numbered status code.
* May be useful when needed status code is
* unavailable in rpd_res_status.
*
* If not, please, use enumeration.
*
* \param status Status code.
*/
void status(long status)
{
res->status = static_cast<rpd_res_statuses>(status);
}
/*!
* \brief Sets _location_ response field.
*
* \param location Location URL.
*/
void location(const char *location)
{
if (res->location)
free(res->location);
res->location = strdup(location);
}
/*!
* \brief Sets _Content-Type_ response field.
*
* \param content_type Response content type.
*/
void content_type(const char *content_type)
{
if (res->content_type)
free(res->content_type);
res->content_type = strdup(content_type);
}
/*!
* \brief Sets cookie field.
*
* Adds new cookie field to key-value storage.
* If you need to set cookie parameters such as lifetime,
* place it to val.
*
* \param key Cookie field key.
* \param val Cookie field value.
*/
void cookie(const char *key, const char *val)
{
rpd_keyval_insert(&res->cookie, key, val);
}
/*!
* \brief Sets response body.
*
* \param body Response body.
*/
void body(const char *body)
{
if (res->body)
free(res->body);
res->body = strdup(body);
}
#ifdef EXTENSIONS_INJA
/*!
* \brief Render data to HTML template.
* \param path Path to HTML template relative to dist location.
* \param data Template data to interpolate.
* \param out FastCGI output stream.
*/
void render(const char *path, nlohmann::json data);
#endif
/*!
* \brief Destructor.
*/
virtual ~Response() { }
private:
rpd_res *res; //< Composition with C implementation.
};
}
#endif // RAPIDA_RESPONSE_HXX_ENTRY

139
include/Route.hxx

@ -0,0 +1,139 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_ROUTE_HXX_ENTRY
#define RAPIDA_ROUTE_HXX_ENTRY
#include "Request.hxx"
#include "Response.hxx"
namespace rpd {
/*!
* \brief Base class for routes.
*/
class Route {
public:
/*!
* \brief Default constructor.
*
* Creates a new route to handle roquests.
*/
Route() { }
/*!
* \brief Client request handler.
*
* Reads the request method and calls handler for this method.
* \see handle_get for GET requests.
* \see handle_post for POST requests.
* \see handle_put for PUT requests.
* etc.
*
* \note This method will be automatically called.
* You don't need to use it.
*
* \param req Request instance.
* \param res Response instance.
* \param route C rpd_route instance.
*/
static void handle_request(rpd_req *req, rpd_res *res, void *route);
/*!
* \brief Destructor.
*/
virtual ~Route() { }
protected:
/*!
* \brief GET request handler.
*
* Derived class should override this method.
*
* \param req Request.
* \param res Response.
*/
virtual void handle_get(const Request &req, Response &res) = 0;
/*!
* \brief HEAD request handler.
*
* Derived class should override this method.
*
* \param req Request.
* \param res Response.
*/
virtual void handle_head(const Request &req, Response &res) = 0;
/*!
* \brief POST request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_post(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
/*!
* \brief PUT request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_put(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
/*!
* \brief DELETE request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_delete(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
/*!
* \brief CONNECT request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_connect(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
/*!
* \brief OPTIONS request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_options(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
/*!
* \brief TRACE request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_trace(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
/*!
* \brief PATCH request handler.
* \param req Request.
* \param res Response.
*/
virtual void handle_patch(const Request &req, Response &res)
{
res.status(rpd_res_st_not_implemented);
}
};
}
#endif // RAPIDA_ROUTE_HXX_ENTRY

78
include/Url.hxx

@ -0,0 +1,78 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_URL_HXX_ENTRY
#define RAPIDA_URL_HXX_ENTRY
#include "url.h"
namespace rpd {
/*!
* \brief C++ URL wrapper.
*/
class Url {
public:
/*!
* \brief Default constructor.
*
* Initializes URL with null values.
*/
Url()
{
url.parts = NULL;
url.parts_len = 0;
}
/*!
* \brief Constructor.
*/
Url(const char *url) { parse(url); }
/*!
* \brief Parse URL.
*
* \param url URL.
*
* \return Status code. A non-zero value is an error.
*/
int parse(const char *url)
{
return rpd_url_parse(&this->url, url);
}
/*!
* \brief Get number of URL parts.
*
* \return Number of URL parts.
*/
int length() const
{
return url.parts_len;
}
/*!
* \brief Get URL part at index.
*
* \param idx Index of the URL part.
*
* \return URL part.
*/
const char *operator[](int idx)
{
return url.parts[idx];
}
/*!
* \brief Destructor.
*/
virtual ~Url()
{
rpd_url_cleanup(&url);
}
private:
rpd_url url; //< Composition with C implementation.
};
}
#endif // RAPIDA_URL_HXX_ENTRY

67
include/app.h

@ -0,0 +1,67 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file app.h
* \brief Rapida application
*/
#ifndef RAPIDA_APP_H_ENTRY
#define RAPIDA_APP_H_ENTRY
#include "route.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Rapida application main struct.
*/
typedef struct {
int running; /**< Application will be running while this flag is true. */
const char *sock_path; /**< Application UNIX Socket path. */
int sock_id; /**< Application UNIX Socket id. */
int routes_len; /**< Length of the rpd_app::routes array. */
rpd_route *routes; /**< Array of the active routes. */
} rpd_app;
/*!
* \brief Creates Rapida application.
*
* \param app Pointer to application instance.
* \param sock_path UNIX Socket path.
*
* \return Status. 0 is success.
*/
int rpd_app_create(rpd_app *app, const char *sock_path);
/*!
* \brief Starts Rapida main loop.
* \param app Application instance.
*
* \return Status. 0 is success.
*/
int rpd_app_start(rpd_app *app);
/*!
* \brief Adds route to application.
*
* It's better to add routes before application start,
* because rpd_app::routes when you add new route
* rpd_app::routes will be reallocated.
*
* \param app Application instance.
* \param path Path to handle.
* \param cb Handling callback.
* \param userdata Additional data to pass to cb.
*
* \return Status. 0 is success.
*/
int rpd_app_add_route(rpd_app *app, const char *path, rpd_route_cb cb,
void *userdata);
#ifdef __cplusplus
}
#endif
#endif // RAPIDA_APP_H_ENTRY

92
include/keyval.h

@ -0,0 +1,92 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file keyval.h
* \brief Simple key-value struct based on an array
* to store query strings, dynamic parameters, etc.
*/
#ifndef RAPIDA_KEYVAL_H_ENTRY
#define RAPIDA_KEYVAL_H_ENTRY
#include "unistd.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Key-value pair.
*/
typedef struct {
char *key; /**< Key */
char *val; /**< Value */
} rpd_keyval_item;
/*!
* \brief Key-value pairs storage.
*/
typedef struct {
rpd_keyval_item *items; /**< Key-value pairs array. */
int size; /**< Number of elements in rpd_keyval::items. */
int capacity; /**< Current capacity (allocated memory). */
} rpd_keyval;
/*!
* \brief Initialize the rpd_keyval instance.
*
* \param keyval Key-value storage instance.
* \param capacity Initial capacity of the keyval storage.
* Set it to 0 if you don't need initial allocation.
*
* \return Status code.
*/
int rpd_keyval_init(rpd_keyval *keyval, int capacity);
/*!
* \brief Insert new key-value pair into the storage.
*
* If size of the storage is equal to it's capacity, this function firstly
* will reallocate rpd_keyval::items.
*
* \param keyval Key-value storage.
* \param key New pair key.
* \param value New pair value.
*
* \return Status code.
* `0`: Success.
* `1`: Out of memory when reallocate rpd_keyval::items to new capacity.
* `2`: Failed to duplicate rpd_keyval_insert::key or rpd_keyval_insert::value.
*/
int rpd_keyval_insert(rpd_keyval *keyval, const char *key, const char *value);
/*!
* \brief Finds key-value pair by it's key.
*
* \param keyval Key-value storage instance.
* \param key Key to search.
*
* \return Found item or NULL.
*/
rpd_keyval_item *rpd_keyval_find(const rpd_keyval *keyval, const char *key);
/*!
* \brief Free key-val pairs and reset.
*
* This function don't will free rpd_keyval::items memory,
* so capacity will be saved.
* And also this function doesn't free keyval itself.
* You can do it manually.
*
* :note: This is done so that you can use keyval in stack,
* also it minimize system calls to allocate memory.
*
* \param keyval Key-value storage.
*/
void rpd_keyval_cleanup(rpd_keyval *keyval);
#ifdef __cplusplus
}
#endif
#endif /* RAPIDA_KEYVAL_H_ENTRY */

42
include/query.h

@ -0,0 +1,42 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file query.h
* \brief Query string processing.
*/
#ifndef RAPIDA_QUERY_H_ENTRY
#define RAPIDA_QUERY_H_ENTRY
#include "keyval.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Parses a query string.
*
* Parses a query string like `param=val&param1=val1` into an rpd_query struct.
*
* \param dest The rpd_keyval instance to write the parsed query.
* \param query The source query string to parse.
*
* \return Status code. A non-zero value is an error.
*/
int rpd_query_parse(rpd_keyval *dest, const char *query);
/*!
* \brief Creates query string from query instance.
*
* \param query Query instance.
*
* \return Query string.
*/
char *rpd_query_str(const rpd_keyval *query);
#ifdef __cplusplus
}
#endif
#endif /* RAPIDA_QUERY_H_ENTRY */

15
include/rapida.h

@ -0,0 +1,15 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file rapida.h
* \brief Common C interface header of the Rapida.
*/
#ifndef RAPIDA_H_ENTRY
#define RAPIDA_H_ENTRY
#include "app.h"
#include "query.h"
#include "url.h"
#endif /* RAPIDA_H_ENTRY */

13
include/rapida.hxx

@ -0,0 +1,13 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/// \file rapida.hxx C++ interface header of the Rapida.
#ifndef RAPIDA_HXX_ENTRY
#define RAPIDA_HXX_ENTRY
#include "App.hxx"
#include "Request.hxx"
#include "Response.hxx"
#include "Route.hxx"
#endif // RAPIDA_HXX_ENTRY

72
include/request.h

@ -0,0 +1,72 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file request.h
* \brief Request.
*/
#ifndef RAPIDA_REQUEST_H_ENTRY
#define RAPIDA_REQUEST_H_ENTRY
#include "query.h"
#include "url.h"
#include <fcgiapp.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Request method types.
*/
enum rpd_req_methods {
UNKNOWN = 0,
GET,
HEAD,
POST,
PUT,
DELETE,
CONNECT,
OPTIONS,
TRACE,
PATCH
};
/*!
* \brief Request struct.
*/
typedef struct {
enum rpd_req_methods method; /**< Request method. */
char *auth; /**< Authorization field. */
char *cookie; /**< Cookie field. */
char *body; /**< Body field. */
rpd_url path; /**< Requested URL. */
rpd_keyval query; /**< Query. */
rpd_keyval params; /**< Dynamic parameters. */
} rpd_req;
int rpd_req_parse(rpd_req *dest, FCGX_Request *req);
/*!
* \brief Parser string request method to enumeration value.
*
* \param method Request method string.
*
* \return Request method.
*/
enum rpd_req_methods rpd_req_smethod(const char *method);
/*!
* \brief Cleans request data.
*
* Request instance will not be freed, only it's data.
*
* \param req Request instance.
*/
void rpd_req_cleanup(rpd_req *req);
#ifdef __cplusplus
}
#endif
#endif /* RAPIDA_REQUEST_H_ENTRY */

124
include/response.h

@ -0,0 +1,124 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file response.h
* \brief Response.
*/
#ifndef RAPIDA_RESPONSE_H_ENTRY
#define RAPIDA_RESPONSE_H_ENTRY
#include "keyval.h"
#include <fcgiapp.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Response statuses.
*/
enum rpd_res_statuses {
rpd_res_st_continue = 100,
rpd_res_st_switching_protocols = 101,
/*! Experimental, check browser compatibility */
rpd_res_st_early_hints = 103,
rpd_res_st_ok = 200,
rpd_res_st_created = 201,
rpd_res_st_accepted = 202,
rpd_res_st_non_authoritative_info = 203,
rpd_res_st_no_content = 204,
rpd_res_st_reset_content = 205,
rpd_res_st_partial_content = 206,
rpd_res_st_multiple_choices = 300,
rpd_res_st_moved_permanently = 301,
rpd_res_st_found = 302,
rpd_res_st_see_other = 303,
rpd_res_st_not_modified = 304,
rpd_res_st_temp_redirect = 307,
rpd_res_st_perm_redirect = 308,
rpd_res_st_bad_request = 400,
rpd_res_st_unauthorized = 401,
rpd_res_st_payment_required = 402,
rpd_res_st_forbidden = 403,
rpd_res_st_not_found = 404,
rpd_res_st_method_not_allowed = 405,
rpd_res_st_not_acceptable = 406,
rpd_res_st_proxy_auth_required = 407,
rpd_res_st_req_timeout = 408,
rpd_res_st_conflict = 409,
rpd_res_st_gone = 410,
rpd_res_st_length_required = 411,
rpd_res_st_precondition_failed = 412,
rpd_res_st_payload_too_large = 413,
rpd_res_st_uri_too_long = 414,
rpd_res_st_unsupported_media_type = 415,
rpd_res_st_range_not_satisfiable = 416,
rpd_res_st_expectation_failed = 417,
rpd_res_st_i_am_teapot = 418,
rpd_res_st_unprocessable_entity = 422,
rpd_res_st_too_early = 425,
rpd_res_st_upgrade_required = 426,
rpd_res_st_precondition_required = 428,
rpd_res_st_too_many_requests = 429,
rpd_res_st_request_header_fields_too_large = 431,
rpd_res_st_unavailable_for_legal_reasons = 451,
rpd_res_st_internal_server_error = 500,
rpd_res_st_not_implemented = 501,
rpd_res_st_bad_gateway = 502,
rpd_res_st_service_unavailable = 503,
rpd_res_st_gateway_timeout = 504,
rpd_res_st_http_ver_not_supported = 505,
rpd_res_st_variant_also_negotiates = 506,
rpd_res_st_insufficient_storage = 507,
rpd_res_st_loop_detected = 508,
rpd_res_st_not_extended = 510,
rpd_res_st_network_auth_required = 511
};
/*!
* \brief Response data wich will be sent to client.
*/
typedef struct {
enum rpd_res_statuses status; /**< Response status code. */
FCGX_Stream *out; /**< Output stream. */
char *location; /**< Location field. */
char *content_type; /**< Content type. */
char *body; /**< Response body. */
rpd_keyval cookie; /**< Set-Cookie fields. */
} rpd_res;
/*!
* \brief Initialize response data from FastCGI request.
*
* \param dest Response instance.
* \param req FastCGI request.
*/
void rpd_res_init(rpd_res *dest, FCGX_Request *req);
/*!
* \brief Sends response to client.
* \param res Response instance.
*/
int rpd_res_send(rpd_res *res);
/*!
* \brief Cleans response instance.
*
* This function will not frees response instance,
* only it's data.
*
* \param res Response instance to cleanup.
*/
void rpd_res_cleanup(rpd_res *res);
#ifdef __cplusplus
}
#endif
#endif /* RAPIDA_RESPONSE_H_ENTRY */

54
include/route.h

@ -0,0 +1,54 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file route.h
* \brief Route handler.
*/
#ifndef RAPIDA_ROUTE_H_ENTRY
#define RAPIDA_ROUTE_H_ENTRY
#include "request.h"
#include "response.h"
#include "url.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief Request handling callback type.
*
* \param req Resquest.
* \param res Response.
* \param userdata User data.
*/
typedef void (*rpd_route_cb)(rpd_req *req, rpd_res *res, void *userdata);
/*!
* \brief Route struct.
*/
typedef struct {
rpd_url path; /**< Route path. */
rpd_route_cb cb; /**< Callback. */
void *userdata; /**< User data */
} rpd_route;
/*!
* \brief Fills route instance.
*
* \param dest Route instance.
* \param path Route path.
* \param cb Handling callback.
* \param userdata Additional callback data.
*
* \return Status. 0 is success.
*/
int rpd_route_init(rpd_route *dest, const char *path, rpd_route_cb cb,
void *userdata);
#ifdef __cplusplus
}
#endif
#endif /* RAPIDA_ROUTE_H_ENTRY */

72
include/url.h

@ -0,0 +1,72 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
/*!
* \file url.h
* \brief Processing URLs.
*/
#ifndef RAPIDA_URL_H_ENTRY
#define RAPIDA_URL_H_ENTRY
#include "keyval.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \brief URL.
*/
typedef struct {
/*! An array of URL parts. */
char **parts;
int parts_len; /**< The length of rpd_url::parts. */
} rpd_url;
/*!
* \brief Parses URL.
*
* If your rpd_url instance was already filled, first free it **fields**.
* rpd_url_parse::src will be dupblicated using the `strdup`,
* so you can free source string.
*
* \param dest rpd_url instance where parsed data will be placed.
* \param src Source URL string.
*
* \return Status code. A non-zero value is an error.
*/
int rpd_url_parse(rpd_url *dest, const char *src);
/*!
* \brief Cleanup URL instance.
*
* \param url URL instance.
*/
void rpd_url_cleanup(rpd_url *url);
/*!
* \brief Parse dynamic parameters keys into key-value pairs.
*
* \param dest Key-value storage instance.
* \param tpl URL with dynamic parameters identifiers.
*
* \return Status. 0 is success.
*/
int rpd_url_params_parse_keys(rpd_keyval *dest, const rpd_url *tpl);
/*!
* \brief Parse dynamic parameters values into key-value pairs.
*
* \param dest Key-value storage with parsed keys.
* \param url URL.
* \param tpl URL with dynamic parameters identifiers.
*
* \return Status. 0 is success.
*/
int rpd_url_params_parse_vals(rpd_keyval *dest, const rpd_url *url, const rpd_url *tpl);
#ifdef __cplusplus
}
#endif
#endif /* RAPIDA_URL_H_ENTRY */

26
tests/app.cxx

@ -0,0 +1,26 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "app.h"
#include "tests.hxx"
using namespace rpd;
TEST_CASE("Application")
{
rpd_app app;
int res = rpd_app_create(&app, "/tmp/rapida.test.socket");
SECTION("App creation")
{
REQUIRE(res == 0);
}
SECTION("Adding route")
{
auto handle = [](rpd_req *req, rpd_res *res, void *userdata) {};
REQUIRE(rpd_app_add_route(&app, "/", handle, NULL) == 0);
REQUIRE(app.routes_len == 1);
REQUIRE(app.routes != NULL);
}
}

44
tests/keyval.cxx

@ -0,0 +1,44 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "keyval.h"
#include "tests.hxx"
using namespace rpd;
TEST_CASE("Key-value storage")
{
rpd_keyval keyval;
rpd_keyval_init(&keyval, 10);
SECTION("Initializing")
{
rpd_keyval_init(&keyval, 10);
REQUIRE(keyval.size == 0);
REQUIRE(keyval.capacity == 10);
}
SECTION("Inserting")
{
REQUIRE(rpd_keyval_insert(&keyval, "key", "val") == 0);
REQUIRE(keyval.size == 1);
REQUIRE(std::string(keyval.items[0].key) == "key");
REQUIRE(std::string(keyval.items[0].val) == "val");
}
SECTION("Search")
{
int sz = keyval.size;
REQUIRE(rpd_keyval_insert(&keyval, "key1", "val") == 0);
REQUIRE(keyval.size == sz + 1);
rpd_keyval_item *item = rpd_keyval_find(&keyval, "key1");
REQUIRE(item != NULL);
REQUIRE(std::string(item->val) == "val");
}
SECTION("Cleanup")
{
rpd_keyval_cleanup(&keyval);
REQUIRE(keyval.size == 0);
}
}

80
tests/query.cxx

@ -0,0 +1,80 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "tests.hxx"
using namespace rpd;
TEST_CASE("Query string parsing")
{
rpd_keyval query;
rpd_keyval_init(&query, 0);
SECTION("Query initialization")
{
rpd_keyval q;
rpd_keyval_init(&q, 0);
REQUIRE(q.capacity == 0);
REQUIRE(q.size == 0);
REQUIRE(q.items == NULL);
}
SECTION("param=val query should be parsed into key=param and val=val")
{
REQUIRE(rpd_query_parse(&query, "param=val") == 0);
REQUIRE(query.size == 1);
REQUIRE(std::string(query.items[0].key) == "param");
REQUIRE(std::string(query.items[0].val) == "val");
}
SECTION("Parameter with empty value should be NULL")
{
REQUIRE(rpd_query_parse(&query, "param=") == 0);
REQUIRE(query.size == 1);
REQUIRE(std::string(query.items[0].key) == "param");
REQUIRE(query.items[0].val == NULL);
}
SECTION("Empty parameter with value should be ignored")
{
REQUIRE(rpd_query_parse(&query, "=val") == 0);
REQUIRE(query.size == 0);
}
SECTION("Complex test with all situations")
{
REQUIRE(rpd_query_parse(&query, "param=val&param1=&=val2") == 0);
REQUIRE(query.size == 2);
REQUIRE(std::string(query.items[0].key) == "param");
REQUIRE(std::string(query.items[0].val) == "val");
REQUIRE(std::string(query.items[1].key) == "param1");
REQUIRE(query.items[1].val == NULL);
REQUIRE(std::string(rpd_query_str(&query)) == "param=val");
}
SECTION("C++ query wrapper initialization")
{
Query cxxquery;
REQUIRE(cxxquery.capacity() == 0);
REQUIRE(cxxquery.size() == 0);
REQUIRE(cxxquery.items() == NULL);
}
SECTION("Complex test with Query C++ wrapper")
{
Query cxxquery;
const char *qstr = "param=val&param1=&=val2";
REQUIRE(cxxquery.parse(qstr) == 0);
REQUIRE(cxxquery.size() == 2);
REQUIRE(std::string(cxxquery["param"]) == "val");
REQUIRE(cxxquery["param1"] == NULL);
}
rpd_keyval_cleanup(&query);
if (query.items) {
free(query.items);
}
}

5
tests/tests.cxx

@ -0,0 +1,5 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#define CATCH_CONFIG_MAIN
#include "tests.hxx"

11
tests/tests.hxx

@ -0,0 +1,11 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#ifndef RAPIDA_TESTS_HXX_ENTRY
#define RAPIDA_TESTS_HXX_ENTRY
#include "rapida.h"
#include "rapida.hxx"
#include <catch2/catch.hpp>
#endif // RAPIDA_TESTS_HXX_ENTRY

59
tests/url.cxx

@ -0,0 +1,59 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "Url.hxx"
#include "tests.hxx"
using namespace rpd;
TEST_CASE("URL processing")
{
rpd_url url { NULL, 0 };
SECTION("\"/some/route\" parsing")
{
REQUIRE(rpd_url_parse(&url, "/some/route") == 0);
REQUIRE(url.parts_len == 2);
REQUIRE(std::string(url.parts[0]) == "some");
REQUIRE(std::string(url.parts[1]) == "route");
}
SECTION("Invalid route without slashes should be ignored")
{
REQUIRE(rpd_url_parse(&url, "someroute") == 0);
REQUIRE(url.parts_len == 0);
}
SECTION("Empty part (\"//\") in the routes should be ignored")
{
REQUIRE(rpd_url_parse(&url, "/some//route/") == 0);
REQUIRE(url.parts_len == 2);
REQUIRE(std::string(url.parts[0]) == "some");
REQUIRE(std::string(url.parts[1]) == "route");
}
SECTION("Dynamic parameters should be saved")
{
REQUIRE(rpd_url_parse(&url, "/some/:param") == 0);
REQUIRE(url.parts_len == 2);
REQUIRE(std::string(url.parts[0]) == "some");
REQUIRE(std::string(url.parts[1]) == ":param");
}
SECTION("Test valid route using the C++ wrapper")
{
Url cxxurl;
REQUIRE(cxxurl.parse("/some/route") == 0);
REQUIRE(cxxurl.length() == 2);
REQUIRE(std::string(cxxurl[0]) == "some");
REQUIRE(std::string(cxxurl[1]) == "route");
}
SECTION("Cleaning")
{
rpd_url_parse(&url, "/some/route");
rpd_url_cleanup(&url);
REQUIRE(url.parts_len == 0);
REQUIRE(url.parts == 0);
}
}
Loading…
Cancel
Save