1
0
Fork 0
mirror of https://github.com/HackHerz/pusher synced 2025-12-06 10:20:19 +00:00

Compare commits

..

No commits in common. "master" and "v0.3" have entirely different histories.
master ... v0.3

23 changed files with 7953 additions and 929 deletions

View file

@ -1,39 +0,0 @@
{
"projectName": "pusher",
"projectOwner": "hackherz",
"files": [
"README.md"
],
"imageSize": 100,
"commit": false,
"contributors": [
{
"login": "nlohmann",
"name": "Niels Lohmann",
"avatar_url": "https://avatars2.githubusercontent.com/u/159488?v=4",
"profile": "http:/nlohmann.me",
"contributions": [
"code"
]
},
{
"login": "jamesterjim",
"name": "James Rose",
"avatar_url": "https://avatars1.githubusercontent.com/u/1824603?v=4",
"profile": "http://jameserose.co.uk",
"contributions": [
"doc"
]
},
{
"login": "HackHerz",
"name": "Daniel Stein",
"avatar_url": "https://avatars1.githubusercontent.com/u/2885148?v=4",
"profile": "https://hackherz.com/",
"contributions": [
"code",
"doc"
]
}
]
}

5
.gitignore vendored
View file

@ -1,4 +1,9 @@
pusher pusher
*~ *~
*.o *.o
*.txt
*.deb *.deb
*cmake*
*cpack*
CMake*
_CPack*

6
.gitmodules vendored
View file

@ -1,6 +0,0 @@
[submodule "src/pushnotifier-sdk-cpp"]
path = src/pushnotifier-sdk-cpp
url = https://github.com/HackHerz/pushnotifier-sdk-cpp
[submodule "src/simpleini"]
path = src/simpleini
url = https://github.com/brofield/simpleini

32
CMakeLists.txt Normal file
View file

@ -0,0 +1,32 @@
cmake_minimum_required(VERSION 2.8)
project(pusher CXX)
# C++11
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(pusher src/main.cpp
src/pushhandler.cpp
src/json/json.cc
src/simpleini/ConvertUTF.c)
# Libraries
target_link_libraries(pusher curl)
# Install
INSTALL_TARGETS("/bin" pusher)
# Debian package
set(CPACK_GENERATOR "DEB")
set(CPACK_DEBIAN_PACKAGE_NAME "pusher")
set(CPACK_PACKAGE_VERSION "0.3")
set(CPACK_DEBIAN_PACKAGE_VERSION "0.3")
execute_process(COMMAND dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libcurl3 (>= 7.37.1), libstdc++6 (>= 4.9.1), libgcc1 (1:4.9.1)")
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Daniel Stein <d.stein@hackherz.com>")
set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "push it to the limits.")
set(CPACK_DEBIAN_PACKAGE_SECTION "util")
include(CPack)

675
LICENSE
View file

@ -1,674 +1,13 @@
GNU GENERAL PUBLIC LICENSE Copyright (c) 2014 HackHerz
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
The GNU General Public License is a free, copyleft license for 2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
software and other kinds of works.
The licenses for most software and other practical works are designed 3) If you modify the source in any way, you have to remove the authors PushNotifier API-token and replace it with your own. It is the same for the package-name.
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 4) You have to make sure that the modified program doesn't break the PushNotifer API rules.
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 THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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 <http://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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

284
Makefile Normal file
View file

@ -0,0 +1,284 @@
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/hackherz/Dokumente/GitHub/pusher
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/hackherz/Dokumente/GitHub/pusher
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..."
/usr/bin/cmake -i .
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install
# Special rule for the target install
install/fast: preinstall/fast
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install/fast
# Special rule for the target install/local
install/local: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local
# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast
# Special rule for the target install/strip
install/strip: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip
# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast
# Special rule for the target list_install_components
list_install_components:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\""
.PHONY : list_install_components
# Special rule for the target list_install_components
list_install_components/fast: list_install_components
.PHONY : list_install_components/fast
# Special rule for the target package
package: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool..."
/usr/bin/cpack --config ./CPackConfig.cmake
.PHONY : package
# Special rule for the target package
package/fast: package
.PHONY : package/fast
# Special rule for the target package_source
package_source:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Run CPack packaging tool for source..."
/usr/bin/cpack --config ./CPackSourceConfig.cmake /home/hackherz/Dokumente/GitHub/pusher/CPackSourceConfig.cmake
.PHONY : package_source
# Special rule for the target package_source
package_source/fast: package_source
.PHONY : package_source/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /home/hackherz/Dokumente/GitHub/pusher/CMakeFiles /home/hackherz/Dokumente/GitHub/pusher/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /home/hackherz/Dokumente/GitHub/pusher/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named pusher
# Build rule for target.
pusher: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 pusher
.PHONY : pusher
# fast build rule for target.
pusher/fast:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/build
.PHONY : pusher/fast
src/json/json.o: src/json/json.cc.o
.PHONY : src/json/json.o
# target to build an object file
src/json/json.cc.o:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/json/json.cc.o
.PHONY : src/json/json.cc.o
src/json/json.i: src/json/json.cc.i
.PHONY : src/json/json.i
# target to preprocess a source file
src/json/json.cc.i:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/json/json.cc.i
.PHONY : src/json/json.cc.i
src/json/json.s: src/json/json.cc.s
.PHONY : src/json/json.s
# target to generate assembly for a file
src/json/json.cc.s:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/json/json.cc.s
.PHONY : src/json/json.cc.s
src/main.o: src/main.cpp.o
.PHONY : src/main.o
# target to build an object file
src/main.cpp.o:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/main.cpp.o
.PHONY : src/main.cpp.o
src/main.i: src/main.cpp.i
.PHONY : src/main.i
# target to preprocess a source file
src/main.cpp.i:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/main.cpp.i
.PHONY : src/main.cpp.i
src/main.s: src/main.cpp.s
.PHONY : src/main.s
# target to generate assembly for a file
src/main.cpp.s:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/main.cpp.s
.PHONY : src/main.cpp.s
src/pushhandler.o: src/pushhandler.cpp.o
.PHONY : src/pushhandler.o
# target to build an object file
src/pushhandler.cpp.o:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/pushhandler.cpp.o
.PHONY : src/pushhandler.cpp.o
src/pushhandler.i: src/pushhandler.cpp.i
.PHONY : src/pushhandler.i
# target to preprocess a source file
src/pushhandler.cpp.i:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/pushhandler.cpp.i
.PHONY : src/pushhandler.cpp.i
src/pushhandler.s: src/pushhandler.cpp.s
.PHONY : src/pushhandler.s
# target to generate assembly for a file
src/pushhandler.cpp.s:
$(MAKE) -f CMakeFiles/pusher.dir/build.make CMakeFiles/pusher.dir/src/pushhandler.cpp.s
.PHONY : src/pushhandler.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... edit_cache"
@echo "... install"
@echo "... install/local"
@echo "... install/strip"
@echo "... list_install_components"
@echo "... package"
@echo "... package_source"
@echo "... pusher"
@echo "... rebuild_cache"
@echo "... src/json/json.o"
@echo "... src/json/json.i"
@echo "... src/json/json.s"
@echo "... src/main.o"
@echo "... src/main.i"
@echo "... src/main.s"
@echo "... src/pushhandler.o"
@echo "... src/pushhandler.i"
@echo "... src/pushhandler.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system

View file

@ -1,5 +1,4 @@
![Logo](https://github.com/HackHerz/pusher/blob/master/pusher.png) ![Logo](http://hackherz.com/wp-content/uploads/2014/09/Pusher-UNIX.png)
[![All Contributors](https://img.shields.io/badge/all_contributors-3-orange.svg?style=flat-square)](#contributors)
# pusher # pusher
Send push-notifications to your phone from the command line. Uses [PushNotifier](http://pushnotifier.de/) to receive notifications. Send push-notifications to your phone from the command line. Uses [PushNotifier](http://pushnotifier.de/) to receive notifications.
@ -13,9 +12,12 @@ Send push-notifications to your phone from the command line. Uses [PushNotifier]
## Installation ## Installation
Make sure you have **libcurl4-openssl-dev** installed. ### Option 1: Debian package
You can download debian packages from [my website](http://hackherz.com/pusher#download).
### Option 2: From source
```bash ```bash
$ git clone --recursive https://github.com/HackHerz/pusher.git $ git clone https://github.com/HackHerz/pusher.git
$ cd pusher/ $ cd pusher/
$ make $ make
$ make install $ make install
@ -24,8 +26,6 @@ $ make install
## Usage ## Usage
If you want some real life use cases make sure to check out our [example section](https://github.com/HackHerz/pusher/tree/master/examples).
### Basic usage ### Basic usage
```bash ```bash
$ pusher -i 1 "Hello World" # Send Hello World to device-id 1 $ pusher -i 1 "Hello World" # Send Hello World to device-id 1
@ -71,18 +71,3 @@ pusher uses a few third party libraries.
- [json](https://github.com/nlohmann/json) by [Niels Lohmann](http://nlohmann.me/) - [json](https://github.com/nlohmann/json) by [Niels Lohmann](http://nlohmann.me/)
- [TCLAP](http://tclap.sourceforge.net/) - [TCLAP](http://tclap.sourceforge.net/)
- [simpleini](https://github.com/brofield/simpleini) by Brodie Thiesfield - [simpleini](https://github.com/brofield/simpleini) by Brodie Thiesfield
## Contributors
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
| [<img src="https://avatars2.githubusercontent.com/u/159488?v=4" width="100px;"/><br /><sub><b>Niels Lohmann</b></sub>](http:/nlohmann.me)<br />[💻](https://github.com/hackherz/pusher/commits?author=nlohmann "Code") | [<img src="https://avatars1.githubusercontent.com/u/1824603?v=4" width="100px;"/><br /><sub><b>James Rose</b></sub>](http://jameserose.co.uk)<br />[📖](https://github.com/hackherz/pusher/commits?author=jamesterjim "Documentation") | [<img src="https://avatars1.githubusercontent.com/u/2885148?v=4" width="100px;"/><br /><sub><b>Daniel Stein</b></sub>](https://hackherz.com/)<br />[💻](https://github.com/hackherz/pusher/commits?author=HackHerz "Code") [📖](https://github.com/hackherz/pusher/commits?author=HackHerz "Documentation") |
| :---: | :---: | :---: |
<!-- ALL-CONTRIBUTORS-LIST:END -->
Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome!

View file

@ -1,9 +0,0 @@
# Examples
This is a collection of examples how you can user pusher. Feel free to contact me or add it yourself if you have a snippet to share.
## Server
- [Notification on SSH login](https://github.com/HackHerz/pusher/blob/master/examples/ssh-notification.md)
- [Notification for fail2ban](https://github.com/HackHerz/pusher/blob/master/examples/fail2ban-notification.md)

View file

@ -1,17 +0,0 @@
# Notification for fail2ban
Copy [pusher.conf](https://github.com/HackHerz/pusher/blob/master/examples/pusher.conf) to **/etc/fail2ban/action.d/** and insert this snippet in your *jail.local*.
```
[ssh]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 6
action = pusher[name=ssh, dest=ONQ]
```
Example is for SSH and change ONQ to your own Device-ID.

View file

@ -1,51 +0,0 @@
# Fail2Ban configuration file
#
# author: hackherz
#
[Definition]
# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart = /usr/local/bin/pusher -i <dest> "[Fail2Ban] <name>: started on `uname -n`"
# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop = /usr/local/bin/pusher -i <dest> "[Fail2Ban] <name>: stopped on `uname -n`"
# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck =
# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = /usr/local/bin/pusher -i <dest> "[Fail2Ban] <name>: banned <ip> from `uname -n`"
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionunban =
[Init]
# Default name of the chain
#
name = default
# Destination/Addressee of the mail
#
dest = default # change this to your default device id

View file

@ -1,16 +0,0 @@
# Notification on SSH login
Maybe you want to receive a notification every time someone logs into your server. Just post this snippet at the end of your **/etc/profile**.
```bash
# SSH-login notification
if [ -n "${SSH_CLIENT}" ]
then
TEXT="$(date "+%Y-%m-%d %H:%M:%S") ssh login to ${USER}@$(hostname -f)"
TEXT+=" from $(echo "${SSH_CLIENT}" | awk '{print $1}')"
pusher -i 297 "${TEXT}"
fi
```
Do not forget to change the id (297 in this example) to the one of your own device.

View file

@ -1,61 +0,0 @@
#=============================================================================
# Set variables for the build
TARGET = pusher
INSTALL_DIR = /usr/local/bin
CXX = g++
CPPFLAGS = -std=c++11
CDEFS = -DAPI_TOKEN=\"8E7D8B2DDE7DDE7D6C3V52VB52VBD4DDETBTTTKFFB11\"
CDEFS += -DAPP_PACKAGE=\"com.hackherz.pusher\"
BUILDCOMMAND = $(CXX) $(CDEFS) $(CPPFLAGS)
LIBS = `pkg-config libcurl --cflags --libs`
#=============================================================================
# Build
all: $(TARGET)
$(TARGET): simpleini pushnotifier main
$(BUILDCOMMAND) src/simpleini/ConvertUTF.o src/pushnotifier-sdk-cpp/pushnotifier.o src/main.o $(LIBS) -o $(TARGET)
# simpleini
.PHONY: simpleini
simpleini: src/simpleini/ConvertUTF.o
src/simpleini/ConvertUTF.o: src/simpleini/ConvertUTF.c
$(BUILDCOMMAND) -c src/simpleini/ConvertUTF.c -o src/simpleini/ConvertUTF.o
# pushnotifier
.PHONY: pushnotifier
pushnotifier: src/pushnotifier-sdk-cpp/pushnotifier.o
src/pushnotifier-sdk-cpp/pushnotifier.o: src/pushnotifier-sdk-cpp/PushNotifier.cpp
$(BUILDCOMMAND) -c src/pushnotifier-sdk-cpp/PushNotifier.cpp -o src/pushnotifier-sdk-cpp/pushnotifier.o
# main
.PHONY: main
main: src/main.o
src/main.o: src/main.cpp
$(BUILDCOMMAND) -c src/main.cpp -o src/main.o
#=============================================================================
# Other targets
.PHONY: clean
clean:
rm -f src/*.o
rm -f src/simpleini/*.o
rm -f src/pushnotifier-sdk-cpp/pushnotifier.o
rm -f $(TARGET)
install: pusher
cp $(TARGET) $(INSTALL_DIR)/
.PHONY: remove
remove:
rm -f $(INSTALL_DIR)/$(TARGET)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 269 KiB

2538
src/json/json.cc Normal file

File diff suppressed because it is too large Load diff

570
src/json/json.h Normal file
View file

@ -0,0 +1,570 @@
/*!
@file
@copyright The code is licensed under the MIT License
<http://opensource.org/licenses/MIT>,
Copyright (c) 2013-2015 Niels Lohmann.
@author Niels Lohmann <http://nlohmann.me>
@see https://github.com/nlohmann/json
*/
#pragma once
#include <initializer_list> // std::initializer_list
#include <iostream> // std::istream, std::ostream
#include <map> // std::map
#include <string> // std::string
#include <vector> // std::vector
#include <iterator> // std::iterator
#include <limits> // std::numeric_limits
#include <functional> // std::hash
namespace nlohmann
{
/*!
@brief JSON for Modern C++
The size of a JSON object is 16 bytes: 8 bytes for the value union whose
largest item is a pointer type and another 8 byte for an element of the
type union. The latter only needs 1 byte - the remaining 7 bytes are wasted
due to alignment.
@see http://stackoverflow.com/questions/7758580/writing-your-own-stl-container/7759622#7759622
@bug Numbers are currently handled too generously. There are several formats
that are forbidden by the standard, but are accepted by the parser.
@todo Implement json::insert(), json::emplace(), json::emplace_back, json::erase
*/
class json
{
public:
// forward declaration to friend this class
class iterator;
class const_iterator;
public:
// container types
/// the type of elements in a JSON class
using value_type = json;
/// the type of element references
using reference = json&;
/// the type of const element references
using const_reference = const json&;
/// the type of pointers to elements
using pointer = json*;
/// the type of const pointers to elements
using const_pointer = const json*;
/// a type to represent differences between iterators
using difference_type = std::ptrdiff_t;
/// a type to represent container sizes
using size_type = std::size_t;
/// an iterator for a JSON container
using iterator = json::iterator;
/// a const iterator for a JSON container
using const_iterator = json::const_iterator;
/// a reverse iterator for a JSON container
using reverse_iterator = std::reverse_iterator<iterator>;
/// a const reverse iterator for a JSON container
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/// a type for an object
using object_t = std::map<std::string, json>;
/// a type for an array
using array_t = std::vector<json>;
/// a type for a string
using string_t = std::string;
/// a type for a Boolean
using boolean_t = bool;
/// a type for an integer number
using number_t = int64_t;
/// a type for a floating point number
using number_float_t = double;
/// a type for list initialization
using list_init_t = std::initializer_list<json>;
/// a JSON value
union value
{
/// array as pointer to array_t
array_t* array;
/// object as pointer to object_t
object_t* object;
/// string as pointer to string_t
string_t* string;
/// Boolean
boolean_t boolean;
/// number (integer)
number_t number;
/// number (float)
number_float_t number_float;
/// default constructor
value() = default;
/// constructor for arrays
value(array_t*);
/// constructor for objects
value(object_t*);
/// constructor for strings
value(string_t*);
/// constructor for Booleans
value(boolean_t);
/// constructor for numbers (integer)
value(number_t);
/// constructor for numbers (float)
value(number_float_t);
};
/// possible types of a JSON object
enum class value_t : uint8_t
{
/// ordered collection of values
array = 0,
/// unordered set of name/value pairs
object,
/// null value
null,
/// string value
string,
/// Boolean value
boolean,
/// number value (integer)
number,
/// number value (float)
number_float
};
public:
/// create an object according to given type
json(const value_t);
/// create a null object
json() = default;
/// create a null object
json(std::nullptr_t) noexcept;
/// create a string object from a C++ string
json(const std::string&);
/// create a string object from a C++ string (move)
json(std::string&&);
/// create a string object from a C string
json(const char*);
/// create a Boolean object
json(const bool) noexcept;
/// create an array
json(const array_t&);
/// create an array (move)
json(array_t&&);
/// create an object
json(const object_t&);
/// create an object (move)
json(object_t&&);
/// create from an initializer list (to an array or object)
json(list_init_t);
/*!
@brief create a number object (integer)
@param n an integer number to wrap in a JSON object
*/
template<typename T, typename
std::enable_if<
std::numeric_limits<T>::is_integer, T>::type
= 0>
json(const T n) noexcept
: type_(value_t::number),
value_(static_cast<number_t>(n))
{}
/*!
@brief create a number object (float)
@param n a floating point number to wrap in a JSON object
*/
template<typename T, typename = typename
std::enable_if<
std::is_floating_point<T>::value>::type
>
json(const T n) noexcept
: type_(value_t::number_float),
value_(static_cast<number_float_t>(n))
{}
/*!
@brief create an array object
@param v any type of container whose elements can be use to construct
JSON objects (e.g., std::vector, std::set, std::array)
@note For some reason, we need to explicitly forbid JSON iterator types.
*/
template <class V, typename
std::enable_if<
not std::is_same<V, json::iterator>::value and
not std::is_same<V, json::const_iterator>::value and
not std::is_same<V, json::reverse_iterator>::value and
not std::is_same<V, json::const_reverse_iterator>::value and
std::is_constructible<json, typename V::value_type>::value, int>::type
= 0>
json(const V& v) : json(array_t(v.begin(), v.end()))
{}
/*!
@brief create a JSON object
@param v any type of associative container whose elements can be use to
construct JSON objects (e.g., std::map<std::string, *>)
*/
template <class V, typename
std::enable_if<
std::is_constructible<std::string, typename V::key_type>::value and
std::is_constructible<json, typename V::mapped_type>::value, int>::type
= 0>
json(const V& v) : json(object_t(v.begin(), v.end()))
{}
/// copy constructor
json(const json&);
/// move constructor
json(json&&) noexcept;
/// copy assignment
json& operator=(json) noexcept;
/// destructor
~json() noexcept;
/// create from string representation
static json parse(const std::string&);
/// create from string representation
static json parse(const char*);
private:
/// return the type as string
std::string type_name() const noexcept;
/// dump the object (with pretty printer)
std::string dump(const bool, const unsigned int, unsigned int = 0) const noexcept;
/// replaced a character in a string with another string
void replaceChar(std::string& str, char c, const std::string& replacement) const;
/// escapes special characters to safely dump the string
std::string escapeString(const std::string&) const;
public:
/// explicit value conversion
template<typename T>
T get() const;
/// implicit conversion to string representation
operator std::string() const;
/// implicit conversion to integer (only for numbers)
operator int() const;
/// implicit conversion to integer (only for numbers)
operator int64_t() const;
/// implicit conversion to double (only for numbers)
operator double() const;
/// implicit conversion to Boolean (only for Booleans)
operator bool() const;
/// implicit conversion to JSON vector (not for objects)
operator array_t() const;
/// implicit conversion to JSON map (only for objects)
operator object_t() const;
/// serialize to stream
friend std::ostream& operator<<(std::ostream& o, const json& j)
{
o << j.dump();
return o;
}
/// serialize to stream
friend std::ostream& operator>>(const json& j, std::ostream& o)
{
o << j.dump();
return o;
}
/// deserialize from stream
friend std::istream& operator>>(std::istream& i, json& j)
{
j = parser(i).parse();
return i;
}
/// deserialize from stream
friend std::istream& operator<<(json& j, std::istream& i)
{
j = parser(i).parse();
return i;
}
/// explicit serialization
std::string dump(int = -1) const noexcept;
/// add constructible objects to an array
template<class T, typename std::enable_if<std::is_constructible<json, T>::value>::type = 0>
json & operator+=(const T& o)
{
push_back(json(o));
return *this;
}
/// add an object/array to an array
json& operator+=(const json&);
/// add a pair to an object
json& operator+=(const object_t::value_type&);
/// add a list of elements to array or list of pairs to object
json& operator+=(list_init_t);
/// add constructible objects to an array
template<class T, typename std::enable_if<std::is_constructible<json, T>::value>::type = 0>
void push_back(const T& o)
{
push_back(json(o));
}
/// add an object/array to an array
void push_back(const json&);
/// add an object/array to an array (move)
void push_back(json&&);
/// add a pair to an object
void push_back(const object_t::value_type&);
/// add a list of elements to array or list of pairs to object
void push_back(list_init_t);
/// operator to set an element in an array
reference operator[](const int);
/// operator to get an element in an array
const_reference operator[](const int) const;
/// operator to get an element in an array
reference at(const int);
/// operator to get an element in an array
const_reference at(const int) const;
/// operator to set an element in an object
reference operator[](const std::string&);
/// operator to set an element in an object
reference operator[](const char*);
/// operator to get an element in an object
const_reference operator[](const std::string&) const;
/// operator to get an element in an object
const_reference operator[](const char*) const;
/// operator to set an element in an object
reference at(const std::string&);
/// operator to set an element in an object
reference at(const char*);
/// operator to get an element in an object
const_reference at(const std::string&) const;
/// operator to get an element in an object
const_reference at(const char*) const;
/// return the number of stored values
size_type size() const noexcept;
/// return the maximal number of values that can be stored
size_type max_size() const noexcept;
/// checks whether object is empty
bool empty() const noexcept;
/// removes all elements from compounds and resets values to default
void clear() noexcept;
/// swaps content with other object
void swap(json&) noexcept;
/// return the type of the object
value_t type() const noexcept;
/// find an element in an object (returns end() iterator otherwise)
iterator find(const std::string&);
/// find an element in an object (returns end() iterator otherwise)
const_iterator find(const std::string&) const;
/// find an element in an object (returns end() iterator otherwise)
iterator find(const char*);
/// find an element in an object (returns end() iterator otherwise)
const_iterator find(const char*) const;
/// lexicographically compares the values
bool operator==(const json&) const noexcept;
/// lexicographically compares the values
bool operator!=(const json&) const noexcept;
/// returns an iterator to the beginning (array/object)
iterator begin() noexcept;
/// returns an iterator to the end (array/object)
iterator end() noexcept;
/// returns an iterator to the beginning (array/object)
const_iterator begin() const noexcept;
/// returns an iterator to the end (array/object)
const_iterator end() const noexcept;
/// returns an iterator to the beginning (array/object)
const_iterator cbegin() const noexcept;
/// returns an iterator to the end (array/object)
const_iterator cend() const noexcept;
/// returns a reverse iterator to the beginning
reverse_iterator rbegin() noexcept;
/// returns a reverse iterator to the end
reverse_iterator rend() noexcept;
/// returns a reverse iterator to the beginning
const_reverse_iterator crbegin() const noexcept;
/// returns a reverse iterator to the end
const_reverse_iterator crend() const noexcept;
private:
/// the type of this object
value_t type_ = value_t::null;
/// the payload
value value_ {};
public:
/// an iterator
class iterator : public std::iterator<std::bidirectional_iterator_tag, json>
{
friend class json;
friend class json::const_iterator;
public:
iterator() = default;
iterator(json*, bool);
iterator(const iterator&);
~iterator();
iterator& operator=(iterator);
bool operator==(const iterator&) const;
bool operator!=(const iterator&) const;
iterator& operator++();
iterator& operator--();
json& operator*() const;
json* operator->() const;
/// getter for the key (in case of objects)
std::string key() const;
/// getter for the value
json& value() const;
private:
/// a JSON value
json* object_ = nullptr;
/// an iterator for JSON arrays
array_t::iterator* vi_ = nullptr;
/// an iterator for JSON objects
object_t::iterator* oi_ = nullptr;
/// whether iterator points to a valid object
bool invalid = true;
};
/// a const iterator
class const_iterator : public std::iterator<std::bidirectional_iterator_tag, const json>
{
friend class json;
public:
const_iterator() = default;
const_iterator(const json*, bool);
const_iterator(const const_iterator&);
const_iterator(const json::iterator&);
~const_iterator();
const_iterator& operator=(const_iterator);
bool operator==(const const_iterator&) const;
bool operator!=(const const_iterator&) const;
const_iterator& operator++();
const_iterator& operator--();
const json& operator*() const;
const json* operator->() const;
/// getter for the key (in case of objects)
std::string key() const;
/// getter for the value
const json& value() const;
private:
/// a JSON value
const json* object_ = nullptr;
/// an iterator for JSON arrays
array_t::const_iterator* vi_ = nullptr;
/// an iterator for JSON objects
object_t::const_iterator* oi_ = nullptr;
/// whether iterator reached past the end
bool invalid = true;
};
private:
/// a helper class to parse a JSON object
class parser
{
public:
/// a parser reading from a C string
parser(const char*);
/// a parser reading from a C++ string
parser(const std::string&);
/// a parser reading from an input stream
parser(std::istream&);
/// destructor of the parser
~parser() = default;
// no copy constructor
parser(const parser&) = delete;
// no copy assignment
parser& operator=(parser) = delete;
/// parse and return a JSON object
json parse();
private:
/// read the next character, stripping whitespace
bool next();
/// raise an exception with an error message
[[noreturn]] inline void error(const std::string&) const;
/// parse a quoted string
inline std::string parseString();
/// transforms a unicode codepoint to it's UTF-8 presentation
std::string codePointToUTF8(unsigned int codePoint) const;
/// parses 4 hex characters that represent a unicode code point
inline unsigned int parse4HexCodePoint();
/// parses \uXXXX[\uXXXX] unicode escape characters
inline std::string parseUnicodeEscape();
/// parse a Boolean "true"
inline void parseTrue();
/// parse a Boolean "false"
inline void parseFalse();
/// parse a null object
inline void parseNull();
/// a helper function to expect a certain character
inline void expect(const char);
private:
/// a buffer of the input
std::string buffer_ {};
/// the current character
char current_ {};
/// the position inside the input buffer
std::size_t pos_ = 0;
};
};
}
/// user-defined literal operator to create JSON objects from strings
nlohmann::json operator "" _json(const char*, std::size_t);
// specialization of std::swap, and std::hash
namespace std
{
template <>
/// swaps the values of two JSON objects
inline void swap(nlohmann::json& j1,
nlohmann::json& j2) noexcept(
is_nothrow_move_constructible<nlohmann::json>::value and
is_nothrow_move_assignable<nlohmann::json>::value
)
{
j1.swap(j2);
}
template <>
/// hash value for JSON objects
struct hash<nlohmann::json>
{
size_t operator()(const nlohmann::json& j) const
{
// a naive hashing via the string representation
return hash<std::string>()(j.dump());
}
};
}

View file

@ -1,6 +1,6 @@
/* /*
* pusher * pusher
* (c) 2014-2016 Daniel Stein * (c) 2014-2015 Daniel Stein
* https://github.com/HackHerz/pusher * https://github.com/HackHerz/pusher
* *
* TODO * TODO
@ -11,13 +11,14 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <fstream>
#include <sstream> #include <sstream>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
#include "tclap/CmdLine.h" #include "tclap/CmdLine.h"
#include "simpleini/SimpleIni.h" #include "simpleini/SimpleIni.h"
#include "pushnotifier-sdk-cpp/PushNotifier.h" #include "pushhandler.h"
#define CONFIG_FILE "/etc/pusher.conf" #define CONFIG_FILE "/etc/pusher.conf"
@ -53,16 +54,17 @@ int main(int argc, char **argv)
try try
{ {
TCLAP::CmdLine cmd("Push notifications to your phone easily.", ' ', "0.4"); TCLAP::CmdLine cmd("Push notifications to your phone easily.", ' ', "0.3");
// Values // Values
TCLAP::ValueArg<string> idArg("i","id","ID of the device.",false,"0","string"); TCLAP::ValueArg<int> idArg("i","id","ID of the device.",false,0,"number");
cmd.add(idArg); cmd.add(idArg);
// Switches // Switches
TCLAP::SwitchArg tokenSwitch("t", "token", "Request your token.", cmd, false); TCLAP::SwitchArg tokenSwitch("t", "token", "Request your token.", cmd, false);
TCLAP::SwitchArg listSwitch("l", "list", "List all your devices.", cmd, false); TCLAP::SwitchArg listSwitch("l", "list", "List all your devices.", cmd, false);
TCLAP::SwitchArg pipeSwitch("p", "pipe", "Input via pipe.", cmd, false); TCLAP::SwitchArg pipeSwitch("p", "pipe", "Input via pipe.", cmd, false);
TCLAP::SwitchArg verifySwitch("v","verify","Checks if token is still valid.", cmd, false);
// add unlabeled argument // add unlabeled argument
@ -75,16 +77,13 @@ int main(int argc, char **argv)
// Variables // Variables
string message, id; string message;
CSimpleIniA iniReader; int id;
iniReader.SetUnicode();
// Request token // Request token
if(tokenSwitch.getValue()) if(tokenSwitch.getValue())
{ {
string username, password; string username, password, token;
PushNotifier::AppToken token;
// Read username // Read username
cout << "Username: "; cout << "Username: ";
@ -102,60 +101,84 @@ int main(int argc, char **argv)
cout << endl; cout << endl;
// pusher instance // pusher instance
PushNotifier buf; PushHandler buf(username);
token = buf.login(username, password); token = buf.login(password);
// Build config // Write config
iniReader.SetValue("pusher", "username", username.c_str()); ofstream dat_aus;
iniReader.SetValue("pusher", "appToken", token.token.c_str()); dat_aus.open(CONFIG_FILE, ios_base::out);
// Check if file is writable // Check if file is writable
if(iniReader.SaveFile(CONFIG_FILE) < 0) if(!dat_aus.is_open())
{ {
cout << "Try running pusher as root or save the following in " cout << "Try running pusher as root or save the following in "
<< CONFIG_FILE << "\n" << endl; << CONFIG_FILE << "\n" << endl;
// Data // Data
string strData; cout << "[pusher]" << endl;
iniReader.Save(strData); cout << "username=" << username << endl;
cout << strData << endl; cout << "appToken=" << token << endl;
return 1; return 1;
} }
else
{
cout << "Success!" << endl; cout << "Success!" << endl;
}
// Data
dat_aus << "[pusher]\n";
dat_aus << "username=" << username << "\n";
dat_aus << "appToken=" << token;
dat_aus.close();
return 0; return 0;
} }
// Load conf and check if token is specified
CSimpleIniA iniReader;
iniReader.SetUnicode();
// Check if reading of config is possible // Check if reading is possible
if(iniReader.LoadFile(CONFIG_FILE) < 0) if(iniReader.LoadFile(CONFIG_FILE) < 0)
{ {
throw runtime_error("You need to login first."); cout << "Error" << endl;
} return 1;
string username = iniReader.GetValue("pusher", "username", "");
string appToken = iniReader.GetValue("pusher", "appToken", "");
if(username.empty() || appToken.empty())
{
throw runtime_error("You need to login first.");
} }
string username = iniReader.GetValue("pusher", "username", NULL);
string appToken = iniReader.GetValue("pusher", "appToken", NULL);
// Loading values // Loading values
PushNotifier pusherInstance(username, appToken, 0); PushHandler pusherInstance(username, appToken);
// Verify token
if(verifySwitch.getValue())
{
if(pusherInstance.verifyToken())
{
cout << "appToken is valid" << endl;
return 0;
}
else
{
cout << "appToken is invalid" << endl;
return 1;
}
}
// List devices // List devices
if(listSwitch.getValue()) if(listSwitch.getValue())
{ {
vector<PushNotifier::Device> devices; vector<PushHandler::Device> devices;
devices = pusherInstance.getDevices(); devices = pusherInstance.getDevices();
unsigned int titleLength = 5; unsigned int titleLength = 5;
@ -191,7 +214,7 @@ int main(int argc, char **argv)
// Device id // Device id
if(sizeof(idArg) != 0) if(idArg.getValue() != 0)
{ {
id = idArg.getValue(); id = idArg.getValue();
} }
@ -224,7 +247,7 @@ int main(int argc, char **argv)
stringstream stringID; stringstream stringID;
stringID << id; stringID << id;
pusherInstance.sendMessage(stringID.str(), message); pusherInstance.sendToDevice(stringID.str(), message);
} }
@ -235,7 +258,13 @@ int main(int argc, char **argv)
catch (TCLAP::ArgException &e) catch (TCLAP::ArgException &e)
{ {
cerr << "error: " << e.error() << " for arg " << e.argId() << endl; cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
return 1; }
// errors thrown by pushhandler
catch(PusherError& e)
{
cout << "Error: " << e.what() << endl;
} }
@ -243,7 +272,6 @@ int main(int argc, char **argv)
catch(exception& e) catch(exception& e)
{ {
cout << "Some kind of error occured: " << e.what() << endl; cout << "Some kind of error occured: " << e.what() << endl;
return 1;
} }
return 0; return 0;

256
src/pushhandler.cpp Normal file
View file

@ -0,0 +1,256 @@
#include "pushhandler.h"
#include "json/json.h"
#include <sstream>
#include <algorithm>
#include <curl/curl.h>
using namespace std;
using json = nlohmann::json;
// urlDecode matches
string matches[][2] = {
{"$", "%24"},
{"&", "%26"},
{"+", "%2B"},
{",", "%2C"},
{"/", "%2F"},
{":", "%3A"},
{";", "%3B"},
{"=", "%3D"},
{"?", "%3F"},
{"@", "%40"}
};
// needed for urlencoding
string urlDecode(string url)
{
for(unsigned int i = 0; i < (sizeof(matches)/sizeof(matches[0])); i++)
{
size_t start_pos = 0;
while((start_pos = url.find(matches[i][0], start_pos)) != string::npos)
{
url.replace(start_pos, matches[i][0].length(), matches[i][1]);
start_pos += matches[i][1].length();
}
}
return url;
}
// needed for handling curl output
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// curl wrapper
string curlHandler(string data, const char* url)
{
CURL *curl;
CURLcode res;
string readBuffer;
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res != CURLE_OK)
{
throw PusherError("Network Error");
}
}
return readBuffer;
}
// constructor only username
PushHandler::PushHandler(string username)
{
this->username = username;
}
// constructor with appToken
PushHandler::PushHandler(string username, string appToken)
{
this->username = username;
this->appToken = appToken;
}
// login
string PushHandler::login(string password)
{
// build request data
stringstream requestData;
requestData << "apiToken=" << API_TOKEN;
requestData << "&username=" << this->username;
requestData << "&password=" << password;
// network request
string readBuffer;
readBuffer = curlHandler(requestData.str(), URL_PN_LOGIN);
// json parsing
stringstream jsonData;
jsonData << readBuffer;
json j;
j << jsonData;
if(j["status"].get<string>() != "ok")
{
throw PusherError("wrong credentials");
}
this->appToken = j["appToken"].get<string>();
return this->appToken;
}
// get list of devices
vector<PushHandler::Device> PushHandler::getDevices()
{
// build request data
stringstream requestData;
requestData << "apiToken=" << API_TOKEN;
requestData << "&appToken=" << this->appToken;
// network request
string readBuffer;
readBuffer = curlHandler(requestData.str(), URL_PN_GET_DEVICES);
// json parsing
stringstream jsonData;
jsonData << readBuffer;
json j;
j << jsonData;
// handle the codes
switch(j["code"].get<int>())
{
case 1: throw PusherError("Invalid API Token");
break;
case 2: throw PusherError("App Token missing");
break;
case 3: throw PusherError("App Token invalid");
}
vector<Device> buffer;
for(auto element : j["devices"])
{
Device buf;
buf.title = element["title"].get<string>();
buf.id = element["id"].get<string>();
buf.model = element["model"].get<string>();
buffer.push_back(buf);
}
return buffer;
}
// verify token
bool PushHandler::verifyToken()
{
// build request data
stringstream requestData;
requestData << "apiToken=" << API_TOKEN;
requestData << "&username=" << this->username;
requestData << "&appToken=" << this->appToken;
// network request
string readBuffer;
readBuffer = curlHandler(requestData.str(), URL_PN_CHECK_TOKEN);
// json parser
stringstream jsonData;
jsonData << readBuffer;
json j;
j << jsonData;
switch(j["code"].get<int>())
{
case 0: return true;
break;
case 1: throw PusherError("Invalid API-Token");
break;
case 2: return false;
default: throw PusherError("Invalid server response");
}
}
// send to device
void PushHandler::sendToDevice(string id, string message)
{
// analyze content-type
// ......
// actual sending
// build request data
stringstream requestData;
requestData << "apiToken=" << API_TOKEN;
requestData << "&appToken=" << this->appToken;
requestData << "&app=" << APP_PACKAGE;
requestData << "&deviceID=" << id;
requestData << "&type=" << "MESSAGE";
requestData << "&content=" << urlDecode(message);
// network request
string readBuffer;
readBuffer = curlHandler(requestData.str(), URL_PN_SEND_TO_DEVICE);
// json parsing
stringstream jsonData;
jsonData << readBuffer;
json j;
j << jsonData;
switch(j["code"].get<int>())
{
case 0: //return 0;
break;
case 1: throw PusherError("Invalid API Token");
break;
case 2: throw PusherError("App Token missing");
break;
case 3: throw PusherError("App Token invalid");
break;
case 4: throw PusherError("Package Name missing");
break;
case 5: throw PusherError("Package Name invalid");
break;
case 6: throw PusherError("Package Name is not linked with the provided API Token");
break;
case 7: throw PusherError("Device ID missing");
break;
case 8: throw PusherError("Device ID invalid");
break;
case 9: throw PusherError("Type missing or invalid");
break;
default: throw PusherError("Invalid server response");
}
}

65
src/pushhandler.h Normal file
View file

@ -0,0 +1,65 @@
#ifndef H_PUSHHANDLER
#define H_PUSHHANDLER
#include <string>
#include <vector>
// Change this line if you are using your own API-Token
const char API_TOKEN[] = {
0x38, 0x45, 0x37, 0x44, 0x38, 0x42, 0x32,
0x44, 0x44, 0x45, 0x37, 0x44, 0x44, 0x45,
0x37, 0x44, 0x36, 0x43, 0x33, 0x56, 0x35,
0x32, 0x56, 0x42, 0x35, 0x32, 0x56, 0x42,
0x44, 0x34, 0x44, 0x44, 0x45, 0x54, 0x42,
0x54, 0x54, 0x54, 0x4b, 0x46, 0x46, 0x42 };
#define APP_PACKAGE "com.hackherz.pusher"
#define USER_AGENT "pusher/0.2"
#define URL_PN_LOGIN "http://a.pushnotifier.de/1/login/"
#define URL_PN_CHECK_TOKEN "http://a.pushnotifier.de/1/checkToken/"
#define URL_PN_GET_DEVICES "http://a.pushnotifier.de/1/getDevices/"
#define URL_PN_SEND_TO_DEVICE "http://a.pushnotifier.de/1/sendToDevice/"
class PushHandler
{
public:
PushHandler(std::string username);
PushHandler(std::string username, std::string appToken);
typedef struct
{
std::string title;
std::string id;
std::string model;
} Device;
std::string login(std::string password);
std::vector<Device> getDevices();
void sendToDevice(std::string deviceID, std::string message);
bool verifyToken();
private:
std::string username;
std::string appToken;
};
// class for exceptions
class PusherError
{
public:
PusherError(std::string content) { this->content = content; }
std::string what() { return this->content; }
private:
std::string content;
};
#endif

@ -1 +0,0 @@
Subproject commit b1250dfd76f161916745ecbcc82f9b52d3418345

@ -1 +0,0 @@
Subproject commit 2af65fcc504f8242752755e836709762ef7ce062

539
src/simpleini/ConvertUTF.c Normal file
View file

@ -0,0 +1,539 @@
/*
* Copyright 2001-2004 Unicode, Inc.
*
* Disclaimer
*
* This source code is provided as is by Unicode, Inc. No claims are
* made as to fitness for any particular purpose. No warranties of any
* kind are expressed or implied. The recipient agrees to determine
* applicability of information provided. If this file has been
* purchased on magnetic or optical media from Unicode, Inc., the
* sole remedy for any claim will be exchange of defective media
* within 90 days of receipt.
*
* Limitations on Rights to Redistribute This Code
*
* Unicode, Inc. hereby grants the right to freely use the information
* supplied in this file in the creation of products supporting the
* Unicode Standard, and to make copies of this file in any form
* for internal or external distribution as long as this notice
* remains attached.
*/
/* ---------------------------------------------------------------------
Conversions between UTF32, UTF-16, and UTF-8. Source code file.
Author: Mark E. Davis, 1994.
Rev History: Rick McGowan, fixes & updates May 2001.
Sept 2001: fixed const & error conditions per
mods suggested by S. Parent & A. Lillich.
June 2002: Tim Dodd added detection and handling of incomplete
source sequences, enhanced error detection, added casts
to eliminate compiler warnings.
July 2003: slight mods to back out aggressive FFFE detection.
Jan 2004: updated switches in from-UTF8 conversions.
Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions.
See the header file "ConvertUTF.h" for complete documentation.
------------------------------------------------------------------------ */
#include "ConvertUTF.h"
#ifdef CVTUTF_DEBUG
#include <stdio.h>
#endif
static const int halfShift = 10; /* used for shifting by 10 bits */
static const UTF32 halfBase = 0x0010000UL;
static const UTF32 halfMask = 0x3FFUL;
#define UNI_SUR_HIGH_START (UTF32)0xD800
#define UNI_SUR_HIGH_END (UTF32)0xDBFF
#define UNI_SUR_LOW_START (UTF32)0xDC00
#define UNI_SUR_LOW_END (UTF32)0xDFFF
#define false 0
#define true 1
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF32toUTF16 (
const UTF32** sourceStart, const UTF32* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF32* source = *sourceStart;
UTF16* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch;
if (target >= targetEnd) {
result = targetExhausted; break;
}
ch = *source++;
if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
/* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
if (flags == strictConversion) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
*target++ = (UTF16)ch; /* normal case */
}
} else if (ch > UNI_MAX_LEGAL_UTF32) {
if (flags == strictConversion) {
result = sourceIllegal;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
/* target is a character in range 0xFFFF - 0x10FFFF. */
if (target + 1 >= targetEnd) {
--source; /* Back up source pointer! */
result = targetExhausted; break;
}
ch -= halfBase;
*target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
*target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
}
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF16toUTF32 (
const UTF16** sourceStart, const UTF16* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF16* source = *sourceStart;
UTF32* target = *targetStart;
UTF32 ch, ch2;
while (source < sourceEnd) {
const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
ch = *source++;
/* If we have a surrogate pair, convert to UTF32 first. */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
/* If the 16 bits following the high surrogate are in the source buffer... */
if (source < sourceEnd) {
ch2 = *source;
/* If it's a low surrogate, convert to UTF32. */
if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
+ (ch2 - UNI_SUR_LOW_START) + halfBase;
++source;
} else if (flags == strictConversion) { /* it's an unpaired high surrogate */
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
} else { /* We don't have the 16 bits following the high surrogate. */
--source; /* return to the high surrogate */
result = sourceExhausted;
break;
}
} else if (flags == strictConversion) {
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
}
if (target >= targetEnd) {
source = oldSource; /* Back up source pointer! */
result = targetExhausted; break;
}
*target++ = ch;
}
*sourceStart = source;
*targetStart = target;
#ifdef CVTUTF_DEBUG
if (result == sourceIllegal) {
fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2);
fflush(stderr);
}
#endif
return result;
}
/* --------------------------------------------------------------------- */
/*
* Index into the table below with the first byte of a UTF-8 sequence to
* get the number of trailing bytes that are supposed to follow it.
* Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
* left as-is for anyone who may want to do such conversion, which was
* allowed in earlier algorithms.
*/
static const char trailingBytesForUTF8[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};
/*
* Magic values subtracted from a buffer value during UTF8 conversion.
* This table contains as many values as there might be trailing bytes
* in a UTF-8 sequence.
*/
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
0x03C82080UL, 0xFA082080UL, 0x82082080UL };
/*
* Once the bits are split out into bytes of UTF-8, this is a mask OR-ed
* into the first byte, depending on how many bytes follow. There are
* as many entries in this table as there are UTF-8 sequence types.
* (I.e., one byte sequence, two byte... etc.). Remember that sequencs
* for *legal* UTF-8 will be 4 or fewer bytes total.
*/
static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
/* --------------------------------------------------------------------- */
/* The interface converts a whole buffer to avoid function-call overhead.
* Constants have been gathered. Loops & conditionals have been removed as
* much as possible for efficiency, in favor of drop-through switches.
* (See "Note A" at the bottom of the file for equivalent code.)
* If your compiler supports it, the "isLegalUTF8" call can be turned
* into an inline function.
*/
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF16toUTF8 (
const UTF16** sourceStart, const UTF16* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF16* source = *sourceStart;
UTF8* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch;
unsigned short bytesToWrite = 0;
const UTF32 byteMask = 0xBF;
const UTF32 byteMark = 0x80;
const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */
ch = *source++;
/* If we have a surrogate pair, convert to UTF32 first. */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) {
/* If the 16 bits following the high surrogate are in the source buffer... */
if (source < sourceEnd) {
UTF32 ch2 = *source;
/* If it's a low surrogate, convert to UTF32. */
if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) {
ch = ((ch - UNI_SUR_HIGH_START) << halfShift)
+ (ch2 - UNI_SUR_LOW_START) + halfBase;
++source;
} else if (flags == strictConversion) { /* it's an unpaired high surrogate */
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
} else { /* We don't have the 16 bits following the high surrogate. */
--source; /* return to the high surrogate */
result = sourceExhausted;
break;
}
} else if (flags == strictConversion) {
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
}
/* Figure out how many bytes the result will require */
if (ch < (UTF32)0x80) { bytesToWrite = 1;
} else if (ch < (UTF32)0x800) { bytesToWrite = 2;
} else if (ch < (UTF32)0x10000) { bytesToWrite = 3;
} else if (ch < (UTF32)0x110000) { bytesToWrite = 4;
} else { bytesToWrite = 3;
ch = UNI_REPLACEMENT_CHAR;
}
target += bytesToWrite;
if (target > targetEnd) {
source = oldSource; /* Back up source pointer! */
target -= bytesToWrite; result = targetExhausted; break;
}
switch (bytesToWrite) { /* note: everything falls through. */
case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]);
}
target += bytesToWrite;
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
/*
* Utility routine to tell whether a sequence of bytes is legal UTF-8.
* This must be called with the length pre-determined by the first byte.
* If not calling this from ConvertUTF8to*, then the length can be set by:
* length = trailingBytesForUTF8[*source]+1;
* and the sequence is illegal right away if there aren't that many bytes
* available.
* If presented with a length > 4, this returns false. The Unicode
* definition of UTF-8 goes up to 4-byte sequences.
*/
static Boolean isLegalUTF8(const UTF8 *source, int length) {
UTF8 a;
const UTF8 *srcptr = source+length;
switch (length) {
default: return false;
/* Everything else falls through when "true"... */
case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
case 2: if ((a = (*--srcptr)) > 0xBF) return false;
switch (*source) {
/* no fall-through in this inner switch */
case 0xE0: if (a < 0xA0) return false; break;
case 0xED: if (a > 0x9F) return false; break;
case 0xF0: if (a < 0x90) return false; break;
case 0xF4: if (a > 0x8F) return false; break;
default: if (a < 0x80) return false;
}
case 1: if (*source >= 0x80 && *source < 0xC2) return false;
}
if (*source > 0xF4) return false;
return true;
}
/* --------------------------------------------------------------------- */
/*
* Exported function to return whether a UTF-8 sequence is legal or not.
* This is not used here; it's just exported.
*/
Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
int length = trailingBytesForUTF8[*source]+1;
if (source+length > sourceEnd) {
return false;
}
return isLegalUTF8(source, length);
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF8toUTF16 (
const UTF8** sourceStart, const UTF8* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF8* source = *sourceStart;
UTF16* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch = 0;
unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
if (source + extraBytesToRead >= sourceEnd) {
result = sourceExhausted; break;
}
/* Do this check whether lenient or strict */
if (! isLegalUTF8(source, extraBytesToRead+1)) {
result = sourceIllegal;
break;
}
/*
* The cases all fall through. See "Note A" below.
*/
switch (extraBytesToRead) {
case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
}
ch -= offsetsFromUTF8[extraBytesToRead];
if (target >= targetEnd) {
source -= (extraBytesToRead+1); /* Back up source pointer! */
result = targetExhausted; break;
}
if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
if (flags == strictConversion) {
source -= (extraBytesToRead+1); /* return to the illegal value itself */
result = sourceIllegal;
break;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
*target++ = (UTF16)ch; /* normal case */
}
} else if (ch > UNI_MAX_UTF16) {
if (flags == strictConversion) {
result = sourceIllegal;
source -= (extraBytesToRead+1); /* return to the start */
break; /* Bail out; shouldn't continue */
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
/* target is a character in range 0xFFFF - 0x10FFFF. */
if (target + 1 >= targetEnd) {
source -= (extraBytesToRead+1); /* Back up source pointer! */
result = targetExhausted; break;
}
ch -= halfBase;
*target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START);
*target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START);
}
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF32toUTF8 (
const UTF32** sourceStart, const UTF32* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF32* source = *sourceStart;
UTF8* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch;
unsigned short bytesToWrite = 0;
const UTF32 byteMask = 0xBF;
const UTF32 byteMark = 0x80;
ch = *source++;
if (flags == strictConversion ) {
/* UTF-16 surrogate values are illegal in UTF-32 */
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
--source; /* return to the illegal value itself */
result = sourceIllegal;
break;
}
}
/*
* Figure out how many bytes the result will require. Turn any
* illegally large UTF32 things (> Plane 17) into replacement chars.
*/
if (ch < (UTF32)0x80) { bytesToWrite = 1;
} else if (ch < (UTF32)0x800) { bytesToWrite = 2;
} else if (ch < (UTF32)0x10000) { bytesToWrite = 3;
} else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4;
} else { bytesToWrite = 3;
ch = UNI_REPLACEMENT_CHAR;
result = sourceIllegal;
}
target += bytesToWrite;
if (target > targetEnd) {
--source; /* Back up source pointer! */
target -= bytesToWrite; result = targetExhausted; break;
}
switch (bytesToWrite) { /* note: everything falls through. */
case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
}
target += bytesToWrite;
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* --------------------------------------------------------------------- */
ConversionResult ConvertUTF8toUTF32 (
const UTF8** sourceStart, const UTF8* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
ConversionResult result = conversionOK;
const UTF8* source = *sourceStart;
UTF32* target = *targetStart;
while (source < sourceEnd) {
UTF32 ch = 0;
unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
if (source + extraBytesToRead >= sourceEnd) {
result = sourceExhausted; break;
}
/* Do this check whether lenient or strict */
if (! isLegalUTF8(source, extraBytesToRead+1)) {
result = sourceIllegal;
break;
}
/*
* The cases all fall through. See "Note A" below.
*/
switch (extraBytesToRead) {
case 5: ch += *source++; ch <<= 6;
case 4: ch += *source++; ch <<= 6;
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
}
ch -= offsetsFromUTF8[extraBytesToRead];
if (target >= targetEnd) {
source -= (extraBytesToRead+1); /* Back up the source pointer! */
result = targetExhausted; break;
}
if (ch <= UNI_MAX_LEGAL_UTF32) {
/*
* UTF-16 surrogate values are illegal in UTF-32, and anything
* over Plane 17 (> 0x10FFFF) is illegal.
*/
if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
if (flags == strictConversion) {
source -= (extraBytesToRead+1); /* return to the illegal value itself */
result = sourceIllegal;
break;
} else {
*target++ = UNI_REPLACEMENT_CHAR;
}
} else {
*target++ = ch;
}
} else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */
result = sourceIllegal;
*target++ = UNI_REPLACEMENT_CHAR;
}
}
*sourceStart = source;
*targetStart = target;
return result;
}
/* ---------------------------------------------------------------------
Note A.
The fall-through switches in UTF-8 reading code save a
temp variable, some decrements & conditionals. The switches
are equivalent to the following loop:
{
int tmpBytesToRead = extraBytesToRead+1;
do {
ch += *source++;
--tmpBytesToRead;
if (tmpBytesToRead) ch <<= 6;
} while (tmpBytesToRead > 0);
}
In UTF-8 writing code, the switches on "bytesToWrite" are
similarly unrolled loops.
--------------------------------------------------------------------- */

149
src/simpleini/ConvertUTF.h Normal file
View file

@ -0,0 +1,149 @@
/*
* Copyright 2001-2004 Unicode, Inc.
*
* Disclaimer
*
* This source code is provided as is by Unicode, Inc. No claims are
* made as to fitness for any particular purpose. No warranties of any
* kind are expressed or implied. The recipient agrees to determine
* applicability of information provided. If this file has been
* purchased on magnetic or optical media from Unicode, Inc., the
* sole remedy for any claim will be exchange of defective media
* within 90 days of receipt.
*
* Limitations on Rights to Redistribute This Code
*
* Unicode, Inc. hereby grants the right to freely use the information
* supplied in this file in the creation of products supporting the
* Unicode Standard, and to make copies of this file in any form
* for internal or external distribution as long as this notice
* remains attached.
*/
/* ---------------------------------------------------------------------
Conversions between UTF32, UTF-16, and UTF-8. Header file.
Several funtions are included here, forming a complete set of
conversions between the three formats. UTF-7 is not included
here, but is handled in a separate source file.
Each of these routines takes pointers to input buffers and output
buffers. The input buffers are const.
Each routine converts the text between *sourceStart and sourceEnd,
putting the result into the buffer between *targetStart and
targetEnd. Note: the end pointers are *after* the last item: e.g.
*(sourceEnd - 1) is the last item.
The return result indicates whether the conversion was successful,
and if not, whether the problem was in the source or target buffers.
(Only the first encountered problem is indicated.)
After the conversion, *sourceStart and *targetStart are both
updated to point to the end of last text successfully converted in
the respective buffers.
Input parameters:
sourceStart - pointer to a pointer to the source buffer.
The contents of this are modified on return so that
it points at the next thing to be converted.
targetStart - similarly, pointer to pointer to the target buffer.
sourceEnd, targetEnd - respectively pointers to the ends of the
two buffers, for overflow checking only.
These conversion functions take a ConversionFlags argument. When this
flag is set to strict, both irregular sequences and isolated surrogates
will cause an error. When the flag is set to lenient, both irregular
sequences and isolated surrogates are converted.
Whether the flag is strict or lenient, all illegal sequences will cause
an error return. This includes sequences such as: <F4 90 80 80>, <C0 80>,
or <A0> in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code
must check for illegal sequences.
When the flag is set to lenient, characters over 0x10FFFF are converted
to the replacement character; otherwise (when the flag is set to strict)
they constitute an error.
Output parameters:
The value "sourceIllegal" is returned from some routines if the input
sequence is malformed. When "sourceIllegal" is returned, the source
value will point to the illegal value that caused the problem. E.g.,
in UTF-8 when a sequence is malformed, it points to the start of the
malformed sequence.
Author: Mark E. Davis, 1994.
Rev History: Rick McGowan, fixes & updates May 2001.
Fixes & updates, Sept 2001.
------------------------------------------------------------------------ */
/* ---------------------------------------------------------------------
The following 4 definitions are compiler-specific.
The C standard does not guarantee that wchar_t has at least
16 bits, so wchar_t is no less portable than unsigned short!
All should be unsigned values to avoid sign extension during
bit mask & shift operations.
------------------------------------------------------------------------ */
typedef unsigned int UTF32; /* at least 32 bits */
typedef unsigned short UTF16; /* at least 16 bits */
typedef unsigned char UTF8; /* typically 8 bits */
typedef unsigned char Boolean; /* 0 or 1 */
/* Some fundamental constants */
#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD
#define UNI_MAX_BMP (UTF32)0x0000FFFF
#define UNI_MAX_UTF16 (UTF32)0x0010FFFF
#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF
typedef enum {
conversionOK, /* conversion successful */
sourceExhausted, /* partial character in source, but hit end */
targetExhausted, /* insuff. room in target for conversion */
sourceIllegal /* source sequence is illegal/malformed */
} ConversionResult;
typedef enum {
strictConversion = 0,
lenientConversion
} ConversionFlags;
/* This is for C++ and does no harm in C */
#ifdef __cplusplus
extern "C" {
#endif
ConversionResult ConvertUTF8toUTF16 (
const UTF8** sourceStart, const UTF8* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF16toUTF8 (
const UTF16** sourceStart, const UTF16* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF8toUTF32 (
const UTF8** sourceStart, const UTF8* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF32toUTF8 (
const UTF32** sourceStart, const UTF32* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF16toUTF32 (
const UTF16** sourceStart, const UTF16* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF32toUTF16 (
const UTF32** sourceStart, const UTF32* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd);
#ifdef __cplusplus
}
#endif
/* --------------------------------------------------------------------- */

3435
src/simpleini/SimpleIni.h Normal file

File diff suppressed because it is too large Load diff