pax_global_header 0000666 0000000 0000000 00000000064 15050573076 0014522 g ustar 00root root 0000000 0000000 52 comment=6927c35799b1edc6801344aca31b1b6d2a3532f4
readsb-3.16/ 0000775 0000000 0000000 00000000000 15050573076 0012713 5 ustar 00root root 0000000 0000000 readsb-3.16/.gitattributes 0000664 0000000 0000000 00000000014 15050573076 0015601 0 ustar 00root root 0000000 0000000 *.xz binary
readsb-3.16/.github/ 0000775 0000000 0000000 00000000000 15050573076 0014253 5 ustar 00root root 0000000 0000000 readsb-3.16/.github/workflows/ 0000775 0000000 0000000 00000000000 15050573076 0016310 5 ustar 00root root 0000000 0000000 readsb-3.16/.github/workflows/docker.yaml 0000664 0000000 0000000 00000003777 15050573076 0020461 0 ustar 00root root 0000000 0000000 name: docker build
on:
schedule:
- cron: "0 5 * * 1"
push:
branches:
- "dev"
- "sid"
tags:
- "v*.*.*"
pull_request:
branches:
- "dev"
jobs:
docker:
runs-on: ubuntu-latest
permissions:
packages: write
steps:
- name: Set variables useful for later
id: useful_vars
run: |-
echo "name=timestamp::$(date +%s)" >> $GITHUB_OUTPUT
echo "name=short_sha::${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@v3
- name: Docker meta
id: docker_meta
uses: docker/metadata-action@v4
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=schedule
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=sha,prefix=,format=long,event=tag
type=sha
type=raw,value=latest,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}
type=raw,value=${{ github.ref_name }}-${{ steps.useful_vars.outputs.short_sha }}-${{ steps.useful_vars.outputs.timestamp }},enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.docker_meta.outputs.tags }}
labels: ${{ steps.docker_meta.outputs.labels }}
platforms: linux/amd64,linux/arm64
build-args: |
BUILDKIT_CONTEXT_KEEP_GIT_DIR=true
readsb-3.16/.gitignore 0000664 0000000 0000000 00000000156 15050573076 0014705 0 ustar 00root root 0000000 0000000 *.o
.*.swp
*~
*.rej
*.orig
nbproject/*
oneoff/convert_benchmark
oneoff/decode_comm_b
readsb
viewadsb
.version
readsb-3.16/COPYING 0000664 0000000 0000000 00000104515 15050573076 0013754 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
readsb-3.16/Dockerfile 0000664 0000000 0000000 00000003506 15050573076 0014711 0 ustar 00root root 0000000 0000000 FROM ghcr.io/wiedehopf/readsb-builder:latest AS builder
SHELL ["/bin/bash", "-x", "-o", "pipefail", "-c"]
RUN --mount=type=bind,source=.,target=/app/git \
cd /app/git && \
READSB_BUILD_DIR=$(mktemp -d) && \
cp -aT /app/git $READSB_BUILD_DIR && \
cd $READSB_BUILD_DIR && \
[[ $(uname -m) == x86_64 ]] && MARCH=" -march=nehalem" || MARCH="" && \
make -j$(nproc) RTLSDR=yes OPTIMIZE="-O2 $MARCH" && \
mv readsb /usr/local/bin && \
mv viewadsb /usr/local/bin && \
chmod +x /usr/local/bin/viewadsb /usr/local/bin/readsb && \
make clean && \
make -j$(nproc) PRINT_UUIDS=yes TRACKS_UUID=yes OPTIMIZE="-O2 $MARCH" && \
mv readsb /usr/local/bin/readsb-uuid && \
mv viewadsb /usr/local/bin/viewadsb-uuid && \
chmod +x /usr/local/bin/viewadsb-uuid && \
chmod +x /usr/local/bin/readsb-uuid && \
rm -rf $READSB_BUILD_DIR && \
mkdir -p /usr/local/share/tar1090 && \
wget -O /usr/local/share/tar1090/aircraft.csv.gz https://github.com/wiedehopf/tar1090-db/raw/csv/aircraft.csv.gz && \
true
FROM debian:bookworm-slim
RUN \
--mount=type=bind,from=builder,source=/,target=/builder/ \
apt-get update && \
apt-get -y install --no-install-recommends \
librtlsdr0 libncurses6 zlib1g libzstd1 && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
mkdir -p /run/readsb && \
cp /builder/usr/local/bin/readsb* /usr/local/bin/ && \
cp /builder/usr/local/bin/viewadsb* /usr/local/bin/ && \
mkdir -p /usr/local/share/tar1090 && \
cp /builder/usr/local/share/tar1090/aircraft.csv.gz /usr/local/share/tar1090/aircraft.csv.gz && \
cp /builder/usr/local/lib/libjemalloc.so.2 /usr/local/lib/libjemalloc.so.2 && \
true
ENV LD_PRELOAD=/usr/local/lib/libjemalloc.so.2
ENV MALLOC_CONF=narenas:1,tcache:false
ENTRYPOINT ["/usr/local/bin/readsb"]
readsb-3.16/LICENSE 0000664 0000000 0000000 00000004153 15050573076 0013723 0 ustar 00root root 0000000 0000000 This version of readsb is licensed under the GPL, v3 or any later version.
Please see the individual source files and the file COPYING
for full copyright and license details.
Copyright (c) 2020 Matthias Wirth
Copyright (c) 2019 Michael Wolf
This source code incorporates work that was released under GPL, v2
or later license. For unmodified versions of the original work that
may be used under the terms of that license, please see
https://github.com/flightaware/dump1090
The source code also incorporates work that was released under a
BSD-style license, reproduced below. For unmodified versions
of the original work that may be used under the terms of that
license, please see https://github.com/antirez/dump1090 and
https://github.com/MalcolmRobb/dump1090.
Copyright (C) 2012 by Salvatore Sanfilippo
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
HOLDER 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.
readsb-3.16/Makefile 0000664 0000000 0000000 00000013325 15050573076 0014357 0 ustar 00root root 0000000 0000000 PROGNAME=readsb
READSB_VERSION := "$(shell echo -n `cat version`; { git show -s --format=format: && echo -n ' wiedehopf git: ' && git describe --abbrev --dirty --always && git show -s --format=format:"(committed: %cd)" | tr -cd '[a-z],[A-Z],[0-9],:, ,\-,_,(,)';} || echo -n ' compiled on '`date +%y%m%d` )"
RTLSDR ?= no
BLADERF ?= no
HACKRF ?= no
PLUTOSDR ?= no
SOAPYSDR ?= no
AGGRESSIVE ?= no
HAVE_BIASTEE ?= no
TRACKS_UUID ?= no
PRINT_UUIDS ?= no
DIALECT = -std=c11
CFLAGS = $(DIALECT) -W -Wall -Werror -fno-common -O2
CFLAGS += -DMODES_READSB_VERSION=\"$(READSB_VERSION)\"
CFLAGS += -DREADSB_SHORT_VERSION=\"$(shell cat version)\"
CFLAGS += -DREADSB_SHORT_COMMIT=\"$(shell git describe --abbrev --dirty --always || echo nogit)\"
CFLAGS += -Wdate-time -fstack-protector-strong -Wformat -Werror=format-security
# Platform-specific settings
UNAME := $(shell uname)
ifeq ($(UNAME), Linux)
CFLAGS += -D_GNU_SOURCE -D_DEFAULT_SOURCE
CFLAGS += -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2
LIBS = -pthread -lpthread -lm -lrt -lzstd
else ifeq ($(UNAME), Darwin)
CFLAGS += -D_DARWIN_C_SOURCE
CFLAGS += -I./compat/apple # For epoll_shim.h
CFLAGS += -I/opt/homebrew/include # For zstd.h
LDFLAGS += -L/opt/homebrew/lib
LIBS = -pthread -lpthread -lm -lzstd
COMPAT += compat/apple/epoll_shim.o
else
LIBS = -pthread -lpthread -lm -lrt -lzstd
endif
ifeq ($(ZLIB_STATIC), yes)
LIBS += -l:libz.a
else
LIBS += -lz
endif
ifeq ($(shell $(CC) -c feature_test.c -o feature_test.o -Wno-format-truncation -Werror >/dev/null 2>&1 && echo 1 || echo 0), 1)
CFLAGS += -Wno-format-truncation
endif
ifeq ($(shell uname -m | grep -qs -e arm -e aarch64 >/dev/null 2>&1 && echo 1 || echo 0), 1)
CFLAGS += -DSC16Q11_TABLE_BITS=8
endif
ifeq ($(DISABLE_INTERACTIVE), yes)
CFLAGS += -DDISABLE_INTERACTIVE
else
ifeq ($(UNAME), Darwin)
LIBS += $(shell pkg-config --libs ncurses 2>/dev/null || echo -lncurses)
else
LIBS += $(shell pkg-config --libs ncurses)
endif
endif
# only disable workaround if zerocopy is disabled in librtlsdr, otherwise expect significantly increased CPU use
ifeq ($(DISABLE_RTLSDR_ZEROCOPY_WORKAROUND), yes)
CFLAGS += -DDISABLE_RTLSDR_ZEROCOPY_WORKAROUND
endif
ifeq ($(LTO), yes)
CFLAGS += -flto
LDFLAGS += -flto
endif
ifeq ($(HISTORY), yes)
CFLAGS += -DALL_JSON=1
endif
ifneq ($(PREAMBLE_THRESHOLD_DEFAULT),)
CFLAGS += -DPREAMBLE_THRESHOLD_DEFAULT=$(PREAMBLE_THRESHOLD_DEFAULT)
endif
ifneq ($(TRACE_THREADS),)
CFLAGS += -DTRACE_THREADS=$(TRACE_THREADS)
endif
ifneq ($(TRACE_RECENT_POINTS),)
CFLAGS += -DTRACE_RECENT_POINTS=$(TRACE_RECENT_POINTS)
endif
ifneq ($(AIRCRAFT_HASH_BITS),)
CFLAGS += -DAIRCRAFT_HASH_BITS=$(AIRCRAFT_HASH_BITS)
endif
ifeq ($(STATS_PHASE),yes)
CFLAGS += -DSTATS_PHASE
endif
ifeq ($(TRACKS_UUID), yes)
CFLAGS += -DTRACKS_UUID
endif
ifeq ($(PRINT_UUIDS), yes)
CFLAGS += -DPRINT_UUIDS
endif
ifneq ($(RECENT_RECEIVER_IDS),)
CFLAGS += -DRECENT_RECEIVER_IDS=$(RECENT_RECEIVER_IDS)
endif
ifeq ($(RTLSDR), yes)
SDR_OBJ += sdr_rtlsdr.o
CFLAGS += -DENABLE_RTLSDR
ifeq ($(HAVE_BIASTEE), yes)
CFLAGS += -DENABLE_RTLSDR_BIASTEE
endif
ifdef RTLSDR_PREFIX
CFLAGS += -I$(RTLSDR_PREFIX)/include
LDFLAGS += -L$(RTLSDR_PREFIX)/lib
else
CFLAGS += $(shell pkg-config --cflags librtlsdr)
LDFLAGS += $(shell pkg-config --libs-only-L librtlsdr)
endif
# static linking not well supported, use at own risk
ifeq ($(STATIC), yes)
LIBS_SDR += -Wl,-Bstatic -lrtlsdr -Wl,-Bdynamic -lusb-1.0
else
LIBS_SDR += -lrtlsdr -lusb-1.0
endif
endif
ifeq ($(BLADERF), yes)
SDR_OBJ += sdr_bladerf.o sdr_ubladerf.o
CFLAGS += $(shell pkg-config --cflags libbladeRF) -DENABLE_BLADERF
LIBS_SDR += $(shell pkg-config --libs libbladeRF)
endif
ifeq ($(HACKRF), yes)
SDR_OBJ += sdr_hackrf.o
CFLAGS += $(shell pkg-config --cflags libhackrf) -DENABLE_HACKRF
LIBS_SDR += $(shell pkg-config --libs libhackrf)
endif
ifeq ($(PLUTOSDR), yes)
SDR_OBJ += sdr_plutosdr.o
CFLAGS += $(shell pkg-config --cflags libiio libad9361) -DENABLE_PLUTOSDR
LIBS_SDR += $(shell pkg-config --libs libiio libad9361)
endif
ifeq ($(SOAPYSDR), yes)
SDR_OBJ += sdr_soapy.o
CFLAGS += $(shell pkg-config --cflags SoapySDR) -DENABLE_SOAPYSDR
LIBS_SDR += $(shell pkg-config --libs SoapySDR)
endif
# add custom overrides if user defines them
CFLAGS += -g $(OPTIMIZE)
all: readsb viewadsb
ifneq ($(shell cat .version 2>/dev/null),prefix $(READSB_VERSION))
.PHONY: .version
.version:
@(echo 'prefix $(READSB_VERSION)' >.version &)
endif
readsb.o: readsb.c *.h .version
$(CC) $(CFLAGS) -c $< -o $@
%.o: %.c *.h
$(CC) $(CFLAGS) -c $< -o $@
readsb: readsb.o argp.o anet.o interactive.o mode_ac.o mode_s.o comm_b.o json_out.o net_io.o crc.o demod_2400.o \
uat2esnt/uat2esnt.o uat2esnt/uat_decode.o \
stats.o cpr.o icao_filter.o track.o util.o fasthash.o convert.o sdr_ifile.o sdr_beast.o sdr.o ais_charset.o \
globe_index.o geomag.o receiver.o aircraft.o api.o threadpool.o \
$(SDR_OBJ) $(COMPAT)
$(CC) -o $@ $^ $(LDFLAGS) $(LIBS) $(LIBS_SDR) $(OPTIMIZE)
viewadsb: readsb
rm -f viewadsb
cp readsb viewadsb
clean:
rm -f *.o uat2esnt/*.o compat/clock_gettime/*.o compat/clock_nanosleep/*.o compat/apple/*.o readsb viewadsb cprtests crctests convert_benchmark
test: cprtest crctest
cprtest: cprtests
./cprtests
crctest: cprtests
./cprtests
cprtests: cpr.o cprtests.o
$(CC) $(CFLAGS) -o $@ $^ -lm
crctests: crc.c crc.h
$(CC) $(CFLAGS) -DCRCDEBUG -o $@ $<
benchmarks: oneoff/convert_benchmark
./convert_benchmark
oneoff/convert_benchmark: oneoff/convert_benchmark.o convert.o util.o
$(CC) $(CFLAGS) -o $@ $^ -lm
oneoff/decode_comm_b: oneoff/decode_comm_b.o comm_b.o ais_charset.o
$(CC) $(CFLAGS) -o $@ $^ -lm
readsb-3.16/README-api.md 0000664 0000000 0000000 00000001062 15050573076 0014740 0 ustar 00root root 0000000 0000000 The api-port is best used with nginx and a unix socket:
```
readsb [...] --net-api-port unix:/run/readsb/api.sock
```
nginx location:
```
location /re-api/ {
gzip on;
proxy_http_version 1.1;
proxy_max_temp_file_size 0;
proxy_set_header Connection $http_connection;
proxy_set_header Host $http_host;
proxy_pass http://unix:/run/readsb/api.sock:/$is_args$args;
}
```
Which can then be queried like this:
```
curl --compressed -sS 'http://localhost/re-api/?box=-90,90,0,20' | jq
```
See json readme for more details on the query syntax
readsb-3.16/README-json.md 0000664 0000000 0000000 00000052530 15050573076 0015146 0 ustar 00root root 0000000 0000000 # JSON output formats
readsb generates several json files with informaton about the receiver itself, currently known aircraft,
and general statistics. These are used by the webmap, but could also be used by other things feeds stats
about readsb operation to collectd for later graphing.
## Reading the json files
There are two ways to obtain the json files:
* By HTTP from the external webserver that readsb is feeding. The json is served from the data/ path, e.g. http://somehost/tar1090/data/aircraft.json when installed with tar1090
* As a file in the directory specified by --write-json on readsb command line (by default /run/readsb)
The HTTP versions are always up to date.
The file versions are written periodically; for aircraft, typically once a second, for stats, once a minute.
The file versions are updated to a temporary file, then atomically renamed to the right path, so you should never see partial copies.
Each file contains a single JSON object. The file formats are:
## receiver.json
This file has general metadata about readsb. It does not change often and you probably just want to read it once at startup.
The keys are:
* version: the version of readsb in use
* refresh: how often aircraft.json is updated (for the file version), in milliseconds. the webmap uses this to control its refresh interval.
* lat: the latitude of the receiver in decimal degrees. Optional, may not be present.
* lon: the longitude of the receiver in decimal degrees. Optional, may not be present.
## aircraft.json and --json-port
- --json-port will supply one aircraft object per line, each aircraft object has it's own now as a timestamp
- aircraft.json contains recently seen aircraft. The keys are:
* now: the time this file was generated, in seconds since Jan 1 1970 00:00:00 GMT (the Unix epoch).
* messages: the total number of Mode S messages processed since readsb started.
* aircraft: an array of JSON objects, one per known aircraft. Each aircraft has the following keys. Keys will be omitted if data is not available.
* hex: the 24-bit ICAO identifier of the aircraft, as 6 hex digits. The identifier may start with '~', this means that the address is a non-ICAO address (e.g. from TIS-B).
* type: type of underlying messages / best source of current data for this position / aircraft:
(the following list is in order of which data is preferentially used)
* adsb_icao: messages from a Mode S or ADS-B transponder, using a 24-bit ICAO address
* adsb_icao_nt: messages from an ADS-B equipped "non-transponder" emitter e.g. a ground vehicle, using a 24-bit ICAO address
* adsr_icao: rebroadcast of ADS-B messages originally sent via another data link e.g. UAT, using a 24-bit ICAO address
* tisb_icao: traffic information about a non-ADS-B target identified by a 24-bit ICAO address, e.g. a Mode S target tracked by secondary radar
* adsc: ADS-C (received by monitoring satellite downlinks)
* mlat: MLAT, position calculated arrival time differences using multiple receivers, outliers and varying accuracy is expected.
* other: miscellaneous data received via Basestation / SBS format, quality / source is unknown.
* mode_s: ModeS data from the planes transponder (no position transmitted)
* adsb_other: messages from an ADS-B transponder using a non-ICAO address, e.g. anonymized address
* adsr_other: rebroadcast of ADS-B messages originally sent via another data link e.g. UAT, using a non-ICAO address
* tisb_other: traffic information about a non-ADS-B target using a non-ICAO address
* tisb_trackfile: traffic information about a non-ADS-B target using a track/file identifier, typically from primary or Mode A/C radar
* flight: callsign, the flight name or aircraft registration as 8 chars (2.2.8.2.6)
* alt_baro: the aircraft barometric altitude in feet as a number OR "ground" as a string
* alt_geom: geometric (GNSS / INS) altitude in feet referenced to the WGS84 ellipsoid
* gs: ground speed in knots
* ias: indicated air speed in knots
* tas: true air speed in knots
* mach: Mach number
* track: true track over ground in degrees (0-359)
* track_rate: Rate of change of track, degrees/second
* roll: Roll, degrees, negative is left roll
* mag_heading: Heading, degrees clockwise from magnetic north
* true_heading: Heading, degrees clockwise from true north (usually only transmitted on ground, in the air usually derived from the magnetic heading using magnetic model WMM2020)
* baro_rate: Rate of change of barometric altitude, feet/minute
* geom_rate: Rate of change of geometric (GNSS / INS) altitude, feet/minute
* squawk: Mode A code (Squawk), encoded as 4 octal digits
* emergency: ADS-B emergency/priority status, a superset of the 7x00 squawks (2.2.3.2.7.8.1.1) (none, general, lifeguard, minfuel, nordo, unlawful, downed, reserved)
* category: emitter category to identify particular aircraft or vehicle classes (values A0 - D7) (2.2.3.2.5.2)
* nav_qnh: altimeter setting (QFE or QNH/QNE), hPa
* nav_altitude_mcp: selected altitude from the Mode Control Panel / Flight Control Unit (MCP/FCU) or equivalent equipment
* nav_altitude_fms: selected altitude from the Flight Manaagement System (FMS) (2.2.3.2.7.1.3.3)
* nav_heading: selected heading (True or Magnetic is not defined in DO-260B, mostly Magnetic as that is the de facto standard) (2.2.3.2.7.1.3.7)
* nav_modes: set of engaged automation modes: 'autopilot', 'vnav', 'althold', 'approach', 'lnav', 'tcas'
* lat, lon: the aircraft position in decimal degrees
* nic: Navigation Integrity Category (2.2.3.2.7.2.6)
* rc: Radius of Containment, meters; a measure of position integrity derived from NIC & supplementary bits. (2.2.3.2.7.2.6, Table 2-69)
* seen_pos: how long ago (in seconds before "now") the position was last updated
* track: true track over ground in degrees (0-359)
* version: ADS-B Version Number 0, 1, 2 (3-7 are reserved) (2.2.3.2.7.5)
* nic_baro: Navigation Integrity Category for Barometric Altitude (2.2.5.1.35)
* nac_p: Navigation Accuracy for Position (2.2.5.1.35)
* nac_v: Navigation Accuracy for Velocity (2.2.5.1.19)
* sil: Source Integity Level (2.2.5.1.40)
* sil_type: interpretation of SIL: unknown, perhour, persample
* gva: Geometric Vertical Accuracy (2.2.3.2.7.2.8)
* sda: System Design Assurance (2.2.3.2.7.2.4.6)
* mlat: list of fields derived from MLAT data
* tisb: list of fields derived from TIS-B data
* messages: total number of Mode S messages received from this aircraft
* seen: how long ago (in seconds before "now") a message was last received from this aircraft
* rssi: recent average RSSI (signal power), in dbFS; this will always be negative.
* alert: Flight status alert bit (2.2.3.2.3.2)
* spi: Flight status special position identification bit (2.2.3.2.3.2)
* wd, ws: wind direction and wind speed are calculated from ground track, true heading, true airspeed and ground speed
* oat, tat: outer/static air temperature (C) and total air temperature (C) are calculated from mach number and true airspeed (typically somewhat inaccurate at lower altitudes / mach numbers below 0.5, calculation is inhibited for mach < 0.395)
* acas_ra: experimental, subject to change, see format here: https://github.com/wiedehopf/readsb/blob/ca5b8257bb6176854eb18ecd96761e107fbb12fa/json_out.c#L249
* gpsOkBefore: experimental, subject to change: aircraft lost GPS / GPS heavily degraded, it was working well before this timestamp, only displayed for 15 min after GPS is lost / degraded
(Section references (2.2.xyz) refer to DO-260B.)
If used with --db-file using a aircraft.csv.gz from the tar1090-db repository (csv branch), these additional fields will be available if the aircraft is in the database:
* r: aircraft registration pulled from database
* t: aircraft type pulled from database
* (optional with --db-file-lt: desc: long type name)
* dbFlags: bitfield for certain database flags, below & must be a bitwise and ... check the documentation for your programming language:
```
military = dbFlags & 1;
interesting = dbFlags & 2;
PIA = dbFlags & 4;
LADD = dbFlags & 8;
```
* lastPosition: {lat, lon, nic, rc, seen_pos} when the regular lat and lon are older than 60 seconds they are no longer considered valid, this will provide the last position and show the age for the last position. aircraft will only be in the aircraft json if a messages has been received in the last 60 seconds, longer for the jaero input, see readsb --help.
* rr_lat, rr_lon: If no ADS-B or MLAT position available, a rough estimated position for the aircraft based on the receiver’s estimated coordinates. (If used with multiple receivers / as an aggregation server with --net-ingest --net-receiver-id)
## --net-api-port query formats
* opens a builtin webserver that can handle a couple query formats
* for more info on nginx proxy_pass and technical details, see README-api.md
* now: the time the api data was cached, in seconds since Jan 1 1970 00:00:00 GMT (the Unix epoch).
* api caching frequency is controlled by --write-json-every
* resultCount: number of aircraft in the aircraft array
* ptime: time in milliseconds it took to parse the request and create the json output
```
--net-api-port 8042
curl -sS 'http://localhost:8042/?hexlist=3CD6E3' | jq
/?circle=,,
/?closest=,,
/?box=,,,
/?all_with_pos
/?all
/?find_hex=,,....
/?find_callsign=,,.....
/?find_reg=,,.....
/?find_type=,,.....
```
* circle returns all aircraft within radius nautical miles of lat, lon
* closest is the same as circle but only returning the closest aircraft
* box is will give you all aircraft within a rectangle delimited by 2 latitudes and longitudes
* closest and circle will supply an extra field named "dst" which will have the distance in nautical miles from the supplied location
* all_with_pos will return all aircraft for which we have received a position in the last minute or last 40 minutes for ADS-C
* all will return all aircraft returned by all_with_pos and all aircraft with ModeS messages received in the last 30 seconds
* find_hex (alias: hexList) will return all aircraft with an exact match on one of the given hex / ICAO ids (limited to 1000)
* find_callsign will return all aircraft with an exact match on one of the given callsigns (limited to 1000 or 8000 characters for the request)
* find_reg will return all aircraft with an exact match on one of the given registrations (limited to 1000 or 8000 characters for the request)
* find_type will return all aircraft that have one of the specified icao type codes (A321, B738, .....)
For circle and closest the following two fields are added to each aircraft object:
* dst: distance from supplied center point in nmi
* dir: true direction of the aircraft from the supplied center point (degrees)
To the above base queries you can add these filteroptions
```
&filter_callsign_exact=
&filter_callsign_prefix=
&filter_squawk=
&filter_with_pos
&filter_type=,,.....
&below_alt_baro=
&above_alt_baro=
```
filter any of the base queries for:
* an exact callsign match (multiple exact matches possible)
* all callsigns that start with
* a specific squawk code
* only return aircraft that have a valid position
* only return aircraft that match one of the icao type codes
* only above and / or below a certain altitude in ft (uncorrected barometric altitude, ground treated as 0 ft for simplicity / versatility)
```
&filter_mil
&filter_pia
&filter_ladd
```
filter any of the base queries for these database flags:
* filter_mil will return military aircraft
* filter_pia using a PIA hex code
* filter_ladd will return aircraft on the LADD list
these three filter options can be combined in any combination and will be connected by an OR
in contrast, when combining other filters they restrict an already filtered result
```
&jv2
```
* Change json syntax to be compatible with adsbexchange v2 API output
* now: same as normal BUT in milliseconds
* total: number of aircraft in the aircraft array
* ptime: time in milliseconds it took to parse the request and create the json output
```
?status
```
* Status code 200 during normal operation
## trace jsons
* overall structure
```
{
icao: "0123ac", // hex id of the aircraft
timestamp: 1609275898.495, // unix timestamp in seconds since epoch (1970)
trace: [
[ seconds after timestamp,
lat,
lon,
altitude in ft or "ground" or null,
ground speed in knots or null,
track in degrees or null, (if altitude == "ground", this will be true heading instead of track)
flags as a bitfield: (use bitwise and to extract data)
(flags & 1 > 0): position is stale (no position received for 20 seconds before this one)
(flags & 2 > 0): start of a new leg (tries to detect a separation point between landing and takeoff that separates fligths)
(flags & 4 > 0): vertical rate is geometric and not barometric
(flags & 8 > 0): altitude is geometric and not barometric
,
vertical rate in fpm or null,
aircraft object with extra details or null (see aircraft.json documentation, note that not all fields are present as lat and lon for example arlready in the values above),
// the following fields only in files generated 2022 and later:
type / source of this position or null,
geometric altitude or null,
geometric vertical rate or null,
indicated airspeed or null,
roll angle or null
],
[next entry like the one before],
[next entry like the one before],
]
}
```
Example :
```json
{
"icao":"3c66b0",
"r":"D-AIUP",
"t":"A320",
"dbFlags":0,
"desc":"AIRBUS A-320",
"timestamp": 1663259853.016,
"trace":[
[7016.59,49.263300,10.614239,25125,446.5,309.0,0,-2176,
{"type":"adsb_icao","flight":"DLH7YA ","alt_geom":25875,"ias":335,"tas":484,"mach":0.796,"wd":297,"ws":40,"oat":-30,"tat":1,"track":309.00,"track_rate":-0.53,"roll":-10.72,"mag_heading":304.28,"true_heading":308.02,"baro_rate":-2176,"geom_rate":-2208,"squawk":"1000","category":"A3","nav_qnh":1012.8,"nav_altitude_mcp":14016,"nic":8,"rc":186,"version":2,"nic_baro":1,"nac_p":8,"nac_v":0,"sil":3,"sil_type":"perhour","gva":2,"sda":2,"alert":0,"spi":0},
"adsb_icao",25875,-2208,335,-10.7],
[7024.85,49.273589,10.593278,24825,446.0,306.6,0,-2176,null,"adsb_icao",25550,-2144,337,-1.6],
[7035.67,49.286865,10.565890,24425,446.8,306.5,0,-2176,null,"adsb_icao",25150,-2144,339,0.3],
[7046.71,49.300403,10.537985,24025,446.8,306.5,0,-2176,null,"adsb_icao",24775,-2176,341,0.3],
[7057.80,49.314042,10.509941,23625,445.2,306.7,0,-2176,
{"type":"adsb_icao","flight":"DLH7YA ","alt_geom":24325,"ias":339,"tas":482,"mach":0.784,"wd":296,"ws":37,"oat":-24,"tat":6,"track":306.69,"track_rate":0.00,"roll":0.18,"mag_heading":302.17,"true_heading":305.89,"baro_rate":-2176,"geom_rate":-2176,"squawk":"1000","category":"A3","nav_qnh":1012.8,"nav_altitude_mcp":14016,"nic":8,"rc":186,"version":2,"nic_baro":1,"nac_p":8,"nac_v":0,"sil":3,"sil_type":"perhour","gva":2,"sda":2,"alert":0,"spi":0},
"adsb_icao",24325,-2176,339,0.2],
[7068.82,49.327469,10.482225,23250,443.2,306.6,0,-2112,null,"adsb_icao",23925,-2144,340,0.2],
[7080.53,49.341694,10.452841,22875,441.2,306.4,0,-1728,null,"adsb_icao",23550,-1728,341,-0.2]
}
```
## stats.json
This file contains statistics about readsb operations.
There are 5 top level keys: "latest", "last1min", "last5min", "last15min", "total". Each key has statistics for a different period, defined by the "start" and "end" subkeys:
* "total" covers the entire period from when readsb was started up to the current time
* "last1min" covers a recent 1-minute period. This may be up to 1 minute out of date (i.e. "end" may be up to 1 minute old).
* "last5min" covers a recent 5-minute period. As above, this may be up to 1 minute out of date.
* "last15min" covers a recent 15-minute period. As above, this may be up to 1 minute out of date.
* "latest" covers the time between the end of the "last1min" period and the current time.
Internally, live stats are collected into "latest". Once a minute, "latest" is copied to "last1min" and "latest" is reset. Then "last5min" and "last15min" are recalculated from a history of the last 5 or 15 1-minute periods.
Each period has the following subkeys:
* start: the start time (in seconds-since-1-Jan-1970) of this statistics collection period.
* end: the end time (in seconds-since-1-Jan-1970) of this statistics collection period.
* local: statistics about messages received from a local SDR dongle. Not present in --net-only mode. Has subkeys:
* blocks_processed: number of sample blocks processed
* blocks_dropped: number of sample blocks dropped before processing. A nonzero value means CPU overload.
* modeac: number of Mode A / C messages decoded
* modes: number of Mode S preambles received. This is *not* the number of valid messages!
* bad: number of Mode S preambles that didn't result in a valid message
* unknown_icao: number of Mode S preambles which looked like they might be valid but we didn't recognize the ICAO address and it was one of the message types where we can't be sure it's valid in this case.
* accepted: array. Index N has the number of valid Mode S messages accepted with N-bit errors corrected.
* signal: mean signal power of successfully received messages, in dbFS; always negative.
* peak_signal: peak signal power of a successfully received message, in dbFS; always negative.
* strong_signals: number of messages received that had a signal power above -3dBFS.
* remote: statistics about messages received from remote clients. Only present in --net or --net-only mode. Has subkeys:
* modeac: number of Mode A / C messages received.
* modes: number of Mode S messages received.
* bad: number of Mode S messages that had bad CRC or were otherwise invalid.
* unknown_icao: number of Mode S messages which looked like they might be valid but we didn't recognize the ICAO address and it was one of the message types where we can't be sure it's valid in this case.
* accepted: array. Index N has the number of valid Mode S messages accepted with N-bit errors corrected.
* http_requests: number of HTTP requests handled.
* cpu: statistics about CPU use. Has subkeys:
* demod: milliseconds spent doing demodulation and decoding in response to data from a SDR dongle
* reader: milliseconds spent reading sample data over USB from a SDR dongle
* background: milliseconds spent doing network I/O, processing received network messages, and periodic tasks.
* cpr: statistics about Compact Position Report message decoding. Has subkeys:
* surface: total number of surface CPR messages received
* airborne: total number of airborne CPR messages received
* global_ok: global positions successfuly derived
* global_bad: global positions that were rejected because they were inconsistent
* global_range: global positions that were rejected because they exceeded the receiver max range
* global_speed: global positions that were rejected because they failed the inter-position speed check
* global_skipped: global position attempts skipped because we did not have the right data (e.g. even/odd messages crossed a zone boundary)
* local_ok: local (relative) positions successfully found
* local_aircraft_relative: local positions found relative to a previous aircraft position
* local_receiver_relative: local positions found relative to the receiver position
* local_skipped: local (relative) positions not used because we did not have the right data
* local_range: local positions not used because they exceeded the receiver max range or fell into the ambiguous part of the receiver range
* local_speed: local positions not used because they failed the inter-position speed check
* filtered: number of CPR messages ignored because they matched one of the heuristics for faulty transponder output
* tracks: statistics on aircraft tracks. Each track represents a unique aircraft and persists for up to 5 minutes after the last message
from the aircraft is heard. If messages from the same aircraft are subsequently heard after the 5 minute period, this will be counted
as a new track.
* all: total tracks created
* single_message: tracks consisting of only a single message. These are usually due to message decoding errors that produce a bad aircraft address.
* messages: total number of messages accepted by readsb from any source
## minimal example on how to use python to process aircraft.json:
```
from contextlib import closing
from urllib.request import urlopen, URLError
import json
url="http://192.168.2.14/tar1090/data/aircraft.json"
with closing(urlopen(url, None, 5.0)) as aircraft_file:
aircraft_data = json.load(aircraft_file)
for a in aircraft_data['aircraft']:
hex = a.get('hex')
lat = a.get('lat')
lon = a.get('lon')
if lat and lon:
print("Icao 24 bit id: {hex} Latitude: {lat:.4f} Longitude: {lon:.4f}".format(hex=hex, lat=lat, lon=lon))
```
readsb-3.16/README.md 0000664 0000000 0000000 00000071572 15050573076 0014206 0 ustar 00root root 0000000 0000000 # Readsb
This is a detached fork of https://github.com/Mictronics/readsb
It's continually under development, expect bugs, segfaults and all the good stuff :)
## NO WARRANTY
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
see the LICENSE file for details
## how to install / build
I'd recommend this script to automatically install it:
- https://github.com/wiedehopf/adsb-scripts/wiki/Automatic-installation-for-readsb
See the [Debian Package](##debian-package) section if you want to build the package yourself.
Or check here on how to further install a webinterface and other useful stuff:
- https://github.com/wiedehopf/adsb-wiki/wiki/Building-readsb-from-source
- https://github.com/wiedehopf/adsb-wiki/wiki/Raspbian-Lite:-ADS-B-receiver
For macOS build and info, check the [macOS](##macos) section
## Credits / history
antirez (original dump1090)
Malcom Robb (work on his dump1090 fork)
mutability (forked to dump1090-mutability and further to dump1090-fa)
Mictronics (readsb as a fork of dump1090-fa)
wiedehopf (this fork of Mictronics readsb)
### aircraft.json format:
[json file Readme](README-json.md)
### Push server support
readsb connects to a listening server.
Sending beast data (beast_out):
```
--net-connector 192.168.2.22,30004,beast_out
```
Receiving beast data (beast_in);
```
--net-connector 192.168.2.28,30005,beast_in
```
### BeastReduce output
Selectively forwards beast messages if the received data hasn't been forwarded in the last 125 ms (or `--net-beast-reduce-interval`).
Data not related to the physical aircraft state are only forwarded every 500 ms (4 * `--net-beast-reduce-interval`).The messages of
this output are normal beast messages and compatible with every program able to receive beast messages.
This is used by some aggregators to aggregate ADS-B data, an example net connector would be:
```
--net-connector=feed.airplanes.live,30004,beast_reduce_plus_out,uuid=0033062d-e17e-4389-91a9-79ebb967fb4c
```
The uuid is optional, if none is given, the uuid from --uuid-file is used, if that isn't present no uuid is sent.
The beast_reduce_out net-connector will never send an uuid.
The aggregator enables --net-receiver-id and --net-ingest on their readsb server, it's made to work with beast_reduce_plus_out.
## Debian package
- Build and install with rtlsdr support:
```
sudo apt update
sudo apt install --no-install-recommends --no-install-suggests -y \
git build-essential debhelper libusb-1.0-0-dev pkg-config fakeroot \
libncurses-dev zlib1g-dev zlib1g libzstd-dev libzstd1 \
librtlsdr-dev
git clone --depth 20 https://github.com/wiedehopf/readsb.git
cd readsb
export DEB_BUILD_OPTIONS=noddebs
rm -f ../readsb_*.deb
dpkg-buildpackage -b -ui -uc -us --build-profiles=rtlsdr
sudo dpkg -i ../readsb_*.deb
```
- Build package with no additional receiver library dependencies: `dpkg-buildpackage -b -ui -uc -us`.
- Build with RTLSDR support: `dpkg-buildpackage -b -ui -uc -us --build-profiles=rtlsdr`
- Build with all the support: `dpkg-buildpackage -b -ui -uc -us --build-profiles=with_sdrs`
required build deps (omit last line if you're not building with the various SDR support)
```
git build-essential debhelper libusb-1.0-0-dev pkg-config fakeroot \
libncurses-dev zlib1g-dev zlib1g libzstd-dev libzstd1 \
librtlsdr-dev libsoapysdr-dev libhackrf-dev libbladerf-dev libad9361-dev libiio-dev
```
## Building manually
You can probably just run "make". By default "make" builds with no specific library support. See below.
Binaries are built in the source directory; you will need to arrange to
install them (and a method for starting them) yourself.
"make RTLSDR=yes" will enable rtl-sdr support and add the dependency on
librtlsdr.
On Raspbian 32 bit, mostly rpi2 and older you might want to use this to compile if you're running into CPU issues:
```
make RTLSDR=yes OPTIMIZE="-Ofast -mcpu=arm1176jzf-s -mfpu=vfp"
```
In general if you want to save on CPU cycles, you can try building with these options:
```
make AIRCRAFT_HASH_BITS=11 RTLSDR=yes OPTIMIZE="-O3 -march=native"
```
The difference of using -Ofast or -O3 over the default of -O2 is likely very minimal.
-march=native also usually makes little difference but it might, so it's worth a try.
## Configuration
If required, edit `/etc/default/readsb` to set the service options, device type, network ports etc.
## Autogain
For rtl-sdr devices a software gain algorithm is the default, it's optimized for ADS-B.
On the command line it's activated using `--gain=auto` an is silent by default.
`--gain=auto-verbose` can be used to enable log messages for gain changes.
To tweak the internals, more parameters can be passed:
```
--gain=auto-verbose,,,,
```
The defaults are:
```
--gain=auto-verbose,0,27,31,243
```
The thresholds are numbers 0 to 256, tweaking them requires some understanding of how it works.
One option would be to change the noise thresholds up or down and then observe the log.
There should be no need to tweak these parameters.
## rtl-sdr bias tee
Use this utility independent of readsb:
https://github.com/wiedehopf/adsb-wiki/wiki/RTL-Bias-Tee
## Global map of aircraft
One of this forks main uses is to be the backend of a global map.
For that purpose it's used in conjunction with tar1090 with some extra options to cope with the number of aircraft and also record a history of flight paths: https://github.com/wiedehopf/tar1090#0800-destroy-sd-card
Websites using this software:
- https://adsb.lol/
- https://globe.airplanes.live/
- https://globe.adsb.fi/
- https://globe.adsbexchange.com/
Projects using this softare:
- https://sdr-enthusiasts.gitbook.io/ads-b/
- https://github.com/sdr-enthusiasts/docker-adsb-ultrafeeder
- https://adsb.im/ (indirectly via an SDR-E container)
Projects that use or have used data generated by this software:
- https://gpsjam.org/
- https://adsb.exposed/
- https://tech.marksblogg.com/global-flight-tracking-adsb.html
## Saving traces
History function as used by several online aggregators using tar1090.
Warning: the following will generate several thousand files a day and can use significant amounts of
disk space depending on your data source.
The following command line options need to be added to for example the decoder options in `/etc/default/readsb`
```
--write-globe-history /var/globe_history --heatmap 30
```
To increase time resolution to maximum, you can add `--json-trace-interval=0.1` which will add every
position received to traces. The heatmap interval can also be reduced from the default of 30
seconds, i wouldn't recommend less than 5 seconds for that though.
Aggregators will generally use `--write-json-globe-index` as well but that's not necessary if you don't have more than 500 concurrent planes.
/var/globe_history needs to be a directory writeable by the user readsb.
`sudo mkdir /var/globe_history` and `sudo chown readsb /var/globe_history` are useful for that.
You should also download
```
wget -O /usr/local/share/tar1090/aircraft.csv.gz https://github.com/wiedehopf/tar1090-db/raw/csv/aircraft.csv.gz
```
and add this command line option (for exaple via /etc/default/readsb):
```
--db-file /usr/local/share/tar1090/aircraft.csv.gz
```
This will obviously write data to the hard drive, be aware of that.
The data format is subject to change, don't expect this to be stable.
Be aware of that when upgrading either tar1090 or readsb to a new commit.
If you're using --write-json-globe-index, it's also recommended to use --tar1090-use-api
It will use the readsb API to get data, it's less requests and usually more efficient,
for details see the file nginx-readsb-api.conf
(this needs adding to your existing nginx tar1090 configuration, this is only for people who really know their stuff anyway)
If configuring this stuff seems complicated, consider just using the sdr-enthusiasts ultrafeeder
container. Just don't configure feeds for aggregated data or if you don't want to feed data from
there.
## non-SDR data source
If you don't want readsb to read data from the SDR, you'll also need to change the receiver options line to something like this:
```
RECEIVER_OPTIONS="--net-only --net-connector 192.168.2.7,30005,beast_in"
```
If you have another dump1090/readsb running on the same machine, you'll also need to change all the ports to avoid conflicts.
## --debug=S: speed check debugging output
For current reference please see the speed_check function.
hex
SQ means same quality (ADS-B vs MLAT and stuff)
LQ means lower quality
fail / ok
ok means speed check passed (displayed only with cpr-focus)
A means airborne and S means surface.
reliable is my reliability counter
every good position increases each aircrafts position reliability,
if it gets to zero, speed check is no longer applied and it's allowed to "JUMP",
"JUMP" is also allowed if we haven't had a position for 2 minutes.
tD is the trackDifference
170 or 180 means the new position goes in the opposite direction of the ground track broadcast by the aircraft.
then we have actual distance / allowed distance.
the allowed distance i tweak depending on the trackDifference
high trackDifference makes the allowed distance go slightly negative
as i don't want aircraft to jump backwards.
elapsed time
actual / allowed speed (allowed speed based on allowed distance)
old --> new
lat, lon -> lat, lon
oh if you want that display:
--debug=S
you'll have to update, just disabled the MLAT speed check from displayign stuff ... because usually it's not interesting
## macOS
Thank you to https://github.com/ind006/readsb_macos/ for all the shims needed to make this work.
readsb should be (largely) compatible with macOS, on both Intel and ARM architectures.
There is a recipe for homebrew avalailable: https://formulae.brew.sh/formula/readsb
Run `brew install readsb` to install readsb using homebrew.
Or compile manually roughly like this:
You may need to modify the Makefile to point at where on your mac you have the standard libs and includes installed.
This in turn depends on whether you're using macports or homebrew for those libs and includes. The Makefile has paths
pre-set for homebrew.
These packages are needed, possibly more:
```
git librtlsdr libusb ncurses
```
Build using:
```
make -j4 RTLSDR=yes
```
You can run it from the command line (try `screen -S readsb` and run it in there, press ctrl-A to detach the terminal)
Example command line:
```sh
./readsb --quiet --net --device-type rtlsdr --gain auto
# add console table of planes for a quick test:
--interactive
# optionally add coordinates:
--lat -33.874 --lon 151.206
# add --interactive for testing, it will show a list of planes in the terminal
# optional output of json and other regularly updated files:
--write-json-every 0.5 --write-json=~/tar1090/html/data/
# optional database info
--db-file ~/tar1090/aircraft.csv.gz
# optional listen ports:
--net-ri-port 30001 --net-ro-port 30002 --net-sbs-port 30003 --net-bi-port 30004,30104 --net-bo-port 30005
# optional sending of data to an aggregator:
--net-connector feed.flyrealtraffic.com,30004,beast_reduce_plus_out,7817bd08-f226-11ef-ba9e-072eee452592
```
For a graphical interface, the tar1090 webinterface is recommended: https://github.com/wiedehopf/tar1090
The install script won't work so i'd recommend the following basic webserver configuration:
- serve the html directory as /tar1090
- serve the write-json directory as /tar1090/data
```
git clone --depth 1 https://github.com/wiedehopf/tar1090 ~/tar1090
wget -O ~/tar1090/aircraft.csv.gz https://github.com/wiedehopf/tar1090-db/raw/csv/aircraft.csv.gz
```
Simple http server using python reachable using http://localhost:8081
```
cd ~/tar1090/html
python3 -m http.server 8081
```
Using nginx this would look something like this (replace USER appropriately):
```
location /tar1090/data/ {
alias /home/USER/tar1090/data/;
add_header Cache-Control "no-cache";
location /tar1090/data/traces/ {
gzip off;
add_header Content-Encoding "gzip";
add_header Cache-Control "no-cache";
}
}
location /tar1090/globe_history/ {
alias /home/USER/readsb_history/;
gzip off;
add_header Content-Encoding "gzip";
add_header Cache-Control "no-cache";
}
location /tar1090 {
alias /home/USER/tar1090/html/;
add_header Cache-Control "no-cache";
}
```
An easy way to add some traces when selecting a plane (with nginx):
Add `--write-globe-history=/home/USER/readsb_history` to the readsb command line.
You can also serve this folder as /tar1090/globe_history but that's only required for the history going back further
than 24h.
The classical tar1090 uses traces created via a shell script and served at /tar1090/chunks but running that shell
script is probably a hassle, so just use the above.
## readsb --help
might be out of date, check the command on a freshly compiled version
```
Usage: readsb [OPTIONS...]
readsb Mode-S/ADSB/TIS Receiver
Build options: ENABLE_RTLSDR
General options:
--lat= Reference/receiver surface latitude
--lon= Reference/receiver surface longitude
--no-interactive Disable interactive mode, print to stdout
--interactive-ttl= Remove from list if idle for (default: 60)
--modeac Enable decoding of SSR Modes 3/A & 3/C
--modeac-auto Enable Mode A/C if requested by a Beast connection
--max-range= Absolute maximum range for position decoding (in nm, default: 300)
--fix Enable CRC single-bit error correction (default)
--no-fix Disable CRC single-bit error correction
--no-fix-df Disable CRC single-bit error correction on the DF type to produce more DF17 messages (disabling reduces CPU usage)
--metric Use metric units
--show-only= Show only messages by given ICAO on stdout
--process-only= Process only messages by given ICAO
--filter-DF= When displaying decoded ModeS messages on stdout only show this DF type
--device-type= Select SDR type (this needs to be placed on the command line before any SDR type specific options)
--gain= Set gain (default: auto gain, possible values for rtl-sdr devices: auto auto-verbose 0.0 0.9 1.4 2.7 3.7 7.7 8.7 12.5 14.4 15.7 16.6 19.7 20.7 22.9 25.4 28.0 29.7 32.8 33.8 36.4 37.2 38.6 40.2 42.1 43.4 43.9 44.5 48.0 49.6 58)
--freq= Set frequency (default: 1090 MHz)
--interactive Interactive mode refreshing data on screen. Implies --throttle
--raw Show only messages hex values
--preamble-threshold=<40-400> lower threshold --> more CPU usage (default: 58, pi zero / pi 1: 75, hot CPU 42)
--forward-mlat Forward received beast mlat results to beast output ports
--forward-mlat-sbs Forward received mlat results to sbs output ports
--stats Print stats at exit. No other output
--stats-range Collect/show range histogram
--stats-every= Show and reset stats every seconds (rounded to the nearest 10 seconds due to implementation, first inteval can be up to 5 seconds shorter)
--auto-exit= Run for X seconds, then exit (default: run indefinitely)
--range-outline-hours= Make the range outline retain data for the last X hours (float, default: 24.0)
--onlyaddr Show only ICAO addresses
--gnss Show altitudes as GNSS when available
--snip= Strip IQ file removing samples < level
--debug= Debug mode (verbose), n: network, P: CPR, S: speed check
--devel= Development debugging mode, see source for options, can be specified more than once
--receiver-focus= only process messages from receiverId
--cpr-focus= show CPR details for this hex
--leg-focus= show leg marking details for this hex
--trace-focus= show traceAdd details for this hex
--quiet Disable output (default)
--write-json= Periodically write json output to
--write-prom= Periodically write prometheus output to
--write-globe-history= Write traces to this directory, 1 gz compressed json per day and airframe
--write-state= Write state to disk to have traces after a restart
--write-state-every= Continuously write state to disk every X seconds (default: 3600)
--write-state-only-on-exit Don't continously update state.
--heatmap-dir= Change the directory where heatmaps are saved (default is in globe history dir)
--heatmap= Make Heatmap, each aircraft at most every interval seconds (creates historydir/heatmap.bin and exit after that)
--dump-beast=,, Dump compressed beast files to this directory, start a new file evey interval seconds
--write-json-every= Write json output and update API json every sec seconds (default 1)
--json-location-accuracy= Accuracy of receiver location in json metadata: 0=no location, 1=approximate, 2=exact
--ac-hash-bits= Main hash map size: 2^n entries (default: AIRCRAFT_HASH_BITS)
--write-json-globe-index Write specially indexed globe_xxxx.json files (for tar1090)
--write-receiver-id-json Write receivers.json
--json-trace-interval= Interval after which a new position will guaranteed to be written to the trace and the json position output (default: 30)
--json-trace-hist-only=1,2,3,8 Don't write recent(1), full(2), either(3) traces to /run, only archive via write-globe-history (8: irregularly write limited traces to run, subject to change)
--write-json-gzip Write aircraft.json also as aircraft.json.gz
--write-json-binCraft-only= Use only binary binCraft format for globe files (1), for aircraft.json as well (2)
--write-binCraft-old write old gzipped binCraft files
--json-reliable= Minimum position reliability to put it into json (default: 1, globe options will default set this to 2, disable speed filter: -1, max: 4)
--position-persistence= Position persistence against outliers (default: 4), incremented by json-reliable minus 1
--jaero-timeout= How long in minutes JAERO positions remain valid and on the map in tar1090 (default:33)
--db-file= Default: "none" (as of writing a compatible file is available here: https://github.com/wiedehopf/tar1090-db/tree/csv)
--db-file-lt aircraft.json: add long type as field desc, add field ownOp for the owner, add field year
Network options:
--net-connector= Establish connection, can be specified multiple times (e.g. 127.0.0.1,23004,beast_out) Protocols: beast_out, beast_in, raw_out, raw_in, sbs_in, sbs_in_jaero, sbs_out, sbs_out_jaero, vrs_out, json_out, gpsd_in, uat_in, uat_replay_out, planefinder_in, asterix_in, asterix_out (one failover ip/address,port can be specified: primary-address,primary-port,protocol,failover-address,failover-port) (any position in the comma separated list can also be either silent_fail or uuid=)
--net Enable networking
--net-only Legacy Option, Enable networking, use --net instead
--net-bind-address= IP address to bind to (default: Any; Use 127.0.0.1 for private)
--net-bo-port= TCP Beast output listen ports (default: 0)
--net-bi-port= TCP Beast input listen ports (default: 0)
--net-ro-port= TCP raw output listen ports (default: 0)
--net-ri-port= TCP raw input listen ports (default: 0)
--net-uat-replay-port= UAT replay output listen ports (default: 0)
--net-uat-in-port= UAT input listen ports (default: 0)
--net-sbs-port= TCP BaseStation output listen ports (default: 0)
--net-sbs-in-port= TCP BaseStation input listen ports (default: 0)
--net-sbs-jaero-port= TCP SBS Jaero output listen ports (default: 0)
--net-sbs-jaero-in-port= TCP SBS Jaero input listen ports (default: 0)
--net-asterix-out-port= TCP Asterix output listen ports (default: 0)
--net-asterix-in-port= TCP Asterix input listen ports (default: 0)
--net-asterix-reduce Apply beast reduce logic and interval to ASTERIX outputs
--net-vrs-port= TCP VRS json output listen ports (default: 0)
--net-vrs-interval= TCP VRS json output interval (default: 5.0)
--net-json-port= TCP json position output listen ports, sends one line with a json object containing aircraft details for every position received (default: 0) (consider raising --net-ro-size to 8192 for less fragmentation if this is a concern)
--net-json-port-interval= Set minimum interval between outputs per aircraft for TCP json output, default: 0.0 (every position)
--net-json-port-include-noposition TCP json position output: include aircraft without position (state is sent for aircraft for every DF11 with CRC if the aircraft hasn't sent a position in the last 10 seconds and interval allowing)
--net-api-port= TCP API listen port (in contrast to other listeners, only a single port is allowed) (update frequency controlled by write-json-every parameter) (default: 0)
--api-shutdown-delay= Shutdown delay to server remaining API queries, new queries get a 503 response (default: 0)
--tar1090-use-api when running with globe-index, signal tar1090 use the readsb API to get data, requires webserver mapping of /tar1090/re-api to proxy_pass the requests to the --net-api-port, see nginx-readsb-api.conf in the tar1090 repository for details
--net-beast-reduce-out-port= TCP BeastReduce output listen ports (default: 0)
--net-beast-reduce-interval= BeastReduce data update interval, longer means less data (default: 0.250, valid range: 0.000 - 14.999)
--net-beast-reduce-optimize-for-mlat BeastReduce output: keep all messages relevant to mlat-client
--net-beast-reduce-filter-dist= beast-reduce: remove aircraft which are further than distance from the receiver
--net-beast-reduce-filter-alt= beast-reduce: remove aircraft which are above altitude
--net-sbs-reduce Apply beast reduce logic and interval to SBS outputs
--net-receiver-id forward receiver ID
--net-ingest primary ingest node
--net-garbage= timeout receivers, output messages from timed out receivers as beast on
--decode-threads= Number of decode threads, either 1 or 2 (default: 1). Only use 2 when you have beast traffic > 200 MBit/s, expect 1.4x speedup for 2x CPU
--uuid-file= path to UUID file
--net-ro-size= TCP output flush size (maximum amount of internally buffered data before writing to network) (default: 1280)
--net-ro-interval= TCP output flush interval in seconds (maximum delay between placing data in the output buffer and sending)(default: 0.05, valid values 0.0 - 1.0)
--net-ro-interval-beast-reduce= TCP output flush interval in seconds for beast-reduce outputs (default: value from --net-ro-interval, valid values 0.0 - 1.0)
--net-connector-delay= Outbound re-connection delay (default: 15)
--net-heartbeat= TCP heartbeat rate in seconds (default: 60 sec; 0 to disable)
--net-buffer= control some buffer sizes: 8KB * (2^n) (default: n=1, 16KB)
--net-verbatim Forward messages unchanged
--sdr-buffer-size= SDR buffer / USB transfer size in kibibytes (default: 256 which is equivalent to around 54 ms using rtl-sdr, option might be ignored in future versions)
RTL-SDR options:
use with --device-type rtlsdr
--device= Select device by index or serial number
--enable-agc Enable digital AGC (not tuner AGC!)
--ppm= Set oscillator frequency correction in PPM
Modes-S Beast options, use with --device-type modesbeast:
--beast-serial= Path to Beast serial device (default /dev/ttyUSB0)
--beast-df1117-on Turn ON DF11/17-only filter
--beast-mlat-off Turn OFF MLAT time stamps
--beast-crc-off Turn OFF CRC checking
--beast-df045-on Turn ON DF0/4/5 filter
--beast-fec-off Turn OFF forward error correction
--beast-modeac Turn ON mode A/C
--beast-baudrate= Override Baudrate (default rate 3000000 baud)
GNS HULC options, use with --device-type gnshulc:
Beast binary and HULC protocol input with hardware handshake enabled.
--beast-serial= Path to GNS HULC serial device (default /dev/ttyUSB0)
ifile-specific options, use with --device-type ifile:
--ifile= Read samples from given file ('-' for stdin)
--iformat= Set sample format (UC8, SC16, SC16Q11)
--throttle Process samples at the original capture speed
Help options:
--help Give this help list
--usage Give a short usage message
```
readsb-3.16/aircraft.c 0000664 0000000 0000000 00000067625 15050573076 0014672 0 ustar 00root root 0000000 0000000 #include "readsb.h"
void freeAircraftBack() {
while (Modes.aircraftBack) {
struct aircraftBack *prev = Modes.aircraftBack->prev;
if (Modes.thp) {
cmMunmap(Modes.aircraftBack, aircraftBackAlloc);
} else {
sfree(Modes.aircraftBack);
}
Modes.aircraft_data_size -= aircraftBackAlloc;
Modes.aircraftBack = prev;
}
}
static inline void lockBack() {
pthread_mutex_lock(&Modes.aircraftBackMutex);
//spinLock(&Modes.aircraftBackSpinlock);
}
static inline void unlockBack() {
pthread_mutex_unlock(&Modes.aircraftBackMutex);
//spinRelease(&Modes.aircraftBackSpinlock);
}
static struct aircraft *allocAircraft() {
struct aircraft *a = NULL;
lockBack();
if (Modes.aircraftBackFree) {
//fprintf(stderr, "alloc from freelist\n");
a = Modes.aircraftBackFree;
Modes.aircraftBackFree = a->next;
unlockBack();
return a;
}
if (!Modes.aircraftBack) {
Modes.aircraft_data_size += aircraftBackAlloc;
if (Modes.thp) {
Modes.aircraftBack = cmMmap(aircraftBackAlloc);
} else {
Modes.aircraftBack = cmalloc(aircraftBackAlloc);
}
Modes.aircraftBack->used = 0;
Modes.aircraftBack->prev = NULL;
Modes.aircraftBack->next = NULL;
}
if (Modes.aircraftBack->used >= aircraftBackCap) {
struct aircraftBack *prev = Modes.aircraftBack;
Modes.aircraft_data_size += aircraftBackAlloc;
if (Modes.thp) {
Modes.aircraftBack = cmMmap(aircraftBackAlloc);
} else {
Modes.aircraftBack = cmalloc(aircraftBackAlloc);
}
Modes.aircraftBack->used = 0;
Modes.aircraftBack->prev = prev;
prev->next = Modes.aircraftBack;
Modes.aircraftBack->next = NULL;
}
if (!Modes.aircraftBack || Modes.aircraftBack->used >= aircraftBackCap) {
fprintf(stderr, "FATAL allocAircraft\n");
abort();
}
//fprintf(stderr, "alloc fresh\n");
a = &(Modes.aircraftBack->store[Modes.aircraftBack->used]);
Modes.aircraftBack->used++;
unlockBack();
return a;
}
static void deallocAircraft(struct aircraft *a) {
if (Modes.quickFree) {
return;
}
lockBack();
a->next = Modes.aircraftBackFree;
Modes.aircraftBackFree = a;
unlockBack();
}
static int isMilRange(uint32_t i);
static void updateDetails(struct aircraft *curr, struct char_buffer cb, uint32_t offset);
static inline uint32_t dbHash(uint32_t addr) {
return addrHash(addr, DB_HASH_BITS);
}
static inline uint32_t aircraftHash(uint32_t addr) {
return addrHash(addr, Modes.acHashBits);
}
#define EMPTY 0xFFFFFFFF
#define quickMinBits 8
#define quickMaxBits 16
#define quickStride 8
static int quickBits;
static int quickBuckets;
static int quickSize;
struct ap {
uint32_t addr;
struct aircraft *ptr;
};
static struct ap *quick;
static void quickResize(int bits) {
quickBits = bits;
quickBuckets = (1LL << bits) + quickStride;
quickSize = sizeof(struct ap) * quickBuckets;
if (quickBuckets > 64000)
fprintf(stderr, "quickLookup: changing size to %d!\n", (int) quickBuckets);
sfree(quick);
quick = cmalloc(quickSize);
memset(quick, 0xFF, quickSize);
}
static struct ap *quickGet(uint32_t addr) {
uint32_t hash = addrHash(addr, quickBits);
for (unsigned i = 0; i < quickStride; i++) {
struct ap *q = &(quick[hash + i]);
if (q->addr == addr) {
return q;
}
}
return NULL;
}
static void quickMaintenance() {
for (int i = 0; i < quickBuckets; i++) {
struct ap *q = &(quick[i]);
if (q->addr != EMPTY) {
if (!q->ptr->onActiveList) {
q->addr = EMPTY;
q->ptr = NULL;
}
}
}
}
void quickRemove(struct aircraft *a) {
struct ap *q = quickGet(a->addr);
if (q) {
q->addr = EMPTY;
q->ptr = NULL;
}
//fprintf(stderr, "r: %06x\n", a->addr);
}
void quickAdd(struct aircraft *a) {
struct ap *q = quickGet(a->addr);
if (q)
return;
uint32_t hash = addrHash(a->addr, quickBits);
for (unsigned i = 0; i < quickStride; i++) {
q = &quick[hash + i];
if (q->addr == EMPTY) {
q->addr = a->addr;
q->ptr = a;
return;
}
}
}
void quickInit() {
if (quickBits > quickMinBits && Modes.aircraftActive.len < quickBuckets * 2 / 8) {
quickResize(quickBits - 1);
} else if (quickBits < quickMinBits) {
quickResize(quickMinBits);
} else if (quickBits < quickMaxBits && Modes.aircraftActive.len > quickBuckets * 5 / 8) {
quickResize(quickBits + 1);
}
static int64_t nextMaintenance;
int64_t mono = mono_milli_seconds();
if (mono > nextMaintenance) {
quickMaintenance();
nextMaintenance = mono + 1 * MINUTES;
}
/*
for (int i = 0; i < quickBuckets; i++) {
if (quick[i].addr == EMPTY)
fprintf(stderr, " ");
else
fprintf(stderr, ".");
}
fprintf(stderr, "\n");
*/
}
void quickDestroy() {
sfree(quick);
}
struct aircraft *aircraftGet(uint32_t addr) {
struct ap *q = quickGet(addr);
if (q) {
return q->ptr;
}
struct aircraft *a = Modes.aircraft[aircraftHash(addr)];
while (a && a->addr != addr) {
a = a->next;
}
if (a) {
quickAdd(a);
}
return a;
}
void freeAircraft(struct aircraft *a) {
if (Modes.quickFree) {
traceCleanupNoUnlink(a);
deallocAircraft(a);
return;
}
quickRemove(a);
// remove from the globeList
set_globe_index(a, -5);
if (a->onActiveList) {
ca_remove(&Modes.aircraftActive, a);
}
traceCleanup(a);
memset(a, 0x0, sizeof (struct aircraft));
deallocAircraft(a);
}
void aircraftZeroTail(struct aircraft *a) {
memset(&a->zeroStart, 0x0, &a->zeroEnd - &a->zeroStart);
}
struct aircraft *aircraftCreate(uint32_t addr) {
struct aircraft *a = aircraftGet(addr);
if (a) {
return a;
}
a = allocAircraft();
// Default everything to zero/NULL
memset(a, 0, sizeof (struct aircraft));
// Now initialise things that should not be 0/NULL to their defaults
a->addr = addr;
a->addrtype = ADDR_UNKNOWN;
// defaults until we see a message otherwise
a->adsb_version = -1;
a->adsb_hrd = HEADING_MAGNETIC;
a->adsb_tah = HEADING_GROUND_TRACK;
if (Modes.json_globe_index) {
a->globe_index = -5;
}
// initialize data validity ages
//adjustExpire(a, 58);
updateTypeReg(a);
uint32_t hash = aircraftHash(addr);
// this isn't needed as this happens on separate areas of the hashtable when it's called in
// parallel
//pthread_mutex_lock(&Modes.aircraftCreateMutex);
a->next = Modes.aircraft[hash];
Modes.aircraft[hash] = a;
//pthread_mutex_unlock(&Modes.aircraftCreateMutex);
return a;
}
void toBinCraft(struct aircraft *a, struct binCraft *new, int64_t now) {
memset(new, 0, sizeof(struct binCraft));
new->hex = a->addr;
new->seen = (int32_t) nearbyint((now - a->seen) / 100.0);
new->callsign_valid = trackDataValid(&a->callsign_valid);
for (unsigned i = 0; i < sizeof(new->callsign); i++)
new->callsign[i] = a->callsign[i] * new->callsign_valid;
if (Modes.db) {
memcpy(new->registration, a->registration, sizeof(new->registration));
memcpy(new->typeCode, a->typeCode, sizeof(new->typeCode));
new->dbFlags = a->dbFlags;
}
new->extraFlags |= ((nogps(now, a)) << 0);
if (Modes.json_globe_index || Modes.apiShutdownDelay) {
new->messages = (uint16_t) nearbyint(10 * a->messageRate);
} else {
new->messages = (uint16_t) a->messages;
}
new->position_valid = trackDataValid(&a->pos_reliable_valid);
if (new->position_valid || now < a->seenPosReliable + 14 * 24 * HOURS) {
new->seen_pos = (int32_t) nearbyint((now - a->seenPosReliable) / 100.0);
new->lat = (int32_t) nearbyint(a->latReliable * 1E6);
new->lon = (int32_t) nearbyint(a->lonReliable * 1E6);
new->pos_nic = a->pos_nic_reliable;
new->pos_rc = a->pos_rc_reliable;
}
new->baro_alt_valid = altBaroReliable(a);
new->baro_alt = (int16_t) nearbyint(a->baro_alt * BINCRAFT_ALT_FACTOR);
new->geom_alt = (int16_t) nearbyint(a->geom_alt * BINCRAFT_ALT_FACTOR);
new->baro_rate = (int16_t) nearbyint(a->baro_rate / 8.0);
new->geom_rate = (int16_t) nearbyint(a->geom_rate / 8.0);
new->ias = a->ias;
new->tas = a->tas;
new->squawk = a->squawk;
new->category = a->category * (now < a->category_updated + Modes.trackExpireJaero);
// Aircraft category A0 - D7 encoded as a single hex byte. 00 = unset
new->nav_altitude_mcp = (uint16_t) nearbyint(a->nav_altitude_mcp / 4.0);
new->nav_altitude_fms = (uint16_t) nearbyint(a->nav_altitude_fms / 4.0);
new->nav_qnh = (int16_t) nearbyint(a->nav_qnh * 10.0);
new->gs = (int16_t) nearbyint(a->gs * 10.0);
new->mach = (int16_t) nearbyint(a->mach * 1000.0);
new->track_rate = (int16_t) nearbyint(a->track_rate * 100.0);
new->roll = (int16_t) nearbyint(a->roll * 100.0);
if (trackDataValid(&a->track_valid))
new->track = (int16_t) nearbyint(a->track * 90.0);
else
new->track = (int16_t) nearbyint(a->calc_track * 90.0);
new->mag_heading = (int16_t) nearbyint(a->mag_heading * 90.0);
new->true_heading = (int16_t) nearbyint(a->true_heading * 90.0);
new->nav_heading = (int16_t) nearbyint(a->nav_heading * 90.0);
new->emergency = a->emergency;
new->airground = a->airground * trackDataValid(&a->airground_valid);
new->addrtype = a->addrtype;
new->nav_modes = a->nav_modes;
new->nav_altitude_src = a->nav_altitude_src;
new->sil_type = a->sil_type;
new->wind_valid = (now < a->wind_updated + TRACK_EXPIRE && abs(a->wind_altitude - a->baro_alt) < 500);
new->wind_direction = (int) nearbyint(a->wind_direction) * new->wind_valid;
new->wind_speed = (int) nearbyint(a->wind_speed) * new->wind_valid;
new->temp_valid = (now < a->oat_updated + TRACK_EXPIRE);
new->oat = (int) nearbyint(a->oat) * new->temp_valid;
new->tat = (int) nearbyint(a->tat) * new->temp_valid;
if (a->adsb_version < 0)
new->adsb_version = 15;
else
new->adsb_version = a->adsb_version;
if (a->adsr_version < 0)
new->adsr_version = 15;
else
new->adsr_version = a->adsr_version;
if (a->tisb_version < 0)
new->tisb_version = 15;
else
new->tisb_version = a->tisb_version;
new->nic_a = a->nic_a;
new->nic_c = a->nic_c;
new->nic_baro = a->nic_baro;
new->nac_p = a->nac_p;
new->nac_v = a->nac_v;
new->sil = a->sil;
new->gva = a->gva;
new->sda = a->sda;
new->alert = a->alert;
new->spi = a->spi;
//new->signal = get8bitSignal(a); old version
new->signal = nearbyint((getSignal(a) + 50.0f) * (255.0f / 50.0f));
//fprintf(stderr, "%0.1f %u\n", getSignal(a), new->signal);
#if defined(TRACKS_UUID)
new->receiverId = (uint32_t) (a->receiverId >> 32);
#endif
if (Modes.netReceiverId) {
new->receiverCount = a->receiverCount;
}
#define F(f) do { new->f##_valid = trackDataValid(&a->f##_valid); new->f *= new->f##_valid; } while (0)
F(geom_alt);
F(gs);
F(ias);
F(tas);
F(mach);
F(track);
F(track_rate);
F(roll);
F(mag_heading);
F(true_heading);
F(baro_rate);
F(geom_rate);
F(nic_a);
F(nic_c);
F(nic_baro);
F(nac_p);
F(nac_v);
F(sil);
F(gva);
F(sda);
F(squawk);
F(emergency);
F(nav_qnh);
F(nav_altitude_mcp);
F(nav_altitude_fms);
F(nav_altitude_src);
F(nav_heading);
F(nav_modes);
F(alert);
F(spi);
#undef F
}
// rudimentary sanitization so the json output hopefully won't be invalid
static inline void sanitize(char *str, int len) {
unsigned char b2 = (1<<7) + (1<<6); // 2 byte code or more
unsigned char b3 = (1<<7) + (1<<6) + (1<<5); // 3 byte code or more
unsigned char b4 = (1<<7) + (1<<6) + (1<<5) + (1<<4); // 4 byte code
int debug = 0;
// UTF that goes beyond our string is cut off by terminating the string
if (len >= 3 && (str[len - 3] & b4) == b4) {
if (debug) { fprintf(stderr, "b4%d\n", str[len - 3]); }
str[len - 3] = '\0';
}
if (len >= 2 && (str[len - 2] & b3) == b3) {
if (debug) { fprintf(stderr, "b3%d\n", str[len - 2]); }
str[len - 2] = '\0';
}
if (len >= 1 && (str[len - 1] & b2) == b2) {
if (debug) { fprintf(stderr, "b2%d\n", str[len - 1]); }
str[len - 1] = '\0';
}
char *p = str;
// careful str might be unterminated, use len
while(p - str < len) {
if (*p == '"') {
//if (debug) { fprintf(stderr, "quotation marks: %s\n", str); }
// replace with single quote
*p = '\'';
}
if (*p > 0 && *p < 0x1f) {
if (debug) { fprintf(stderr, "non-printable: %s\n", str); }
// replace with space
*p = ' ';
}
p++;
}
if (p - 1 >= str && *(p - 1) == '\\') {
*(p - 1) = '\0';
}
}
static char *sprintDB2(char *p, char *end, dbEntry *d) {
struct aircraft aBack;
struct aircraft *a = &aBack;
updateDetails(a, Modes.db2Raw, d->rawOffset);
a->addr = d->addr;
p = safe_snprintf(p, end, "\n\"%s%06x\":{", (a->addr & MODES_NON_ICAO_ADDRESS) ? "~" : "", a->addr & 0xFFFFFF);
char *regInfo = p;
if (a->registration[0])
p = safe_snprintf(p, end, "\"r\":\"%.*s\",", (int) sizeof(a->registration), a->registration);
if (a->typeCode[0])
p = safe_snprintf(p, end, "\"t\":\"%.*s\",", (int) sizeof(a->typeCode), a->typeCode);
if (a->typeLong[0])
p = safe_snprintf(p, end, "\"desc\":\"%.*s\",", (int) sizeof(a->typeLong), a->typeLong);
if (a->dbFlags)
p = safe_snprintf(p, end, "\"dbFlags\":%u,", a->dbFlags);
if (a->ownOp[0])
p = safe_snprintf(p, end, "\"ownOp\":\"%.*s\",", (int) sizeof(a->ownOp), a->ownOp);
if (a->year[0])
p = safe_snprintf(p, end, "\"year\":\"%.*s\",", (int) sizeof(a->year), a->year);
if (p == regInfo)
p = safe_snprintf(p, end, "\"noRegData\":true,");
if (*(p-1) == ',')
p--;
p = safe_snprintf(p, end, "},");
return p;
}
static void db2ToJson() {
size_t buflen = 32 * 1024 * 1024;
char *buf = (char *) cmalloc(buflen), *p = buf, *end = buf + buflen;
p = safe_snprintf(p, end, "{");
for (int j = 0; j < DB_BUCKETS; j++) {
if (0 && j % 1000 == 0) {
fprintf(stderr, "db print %d\n", j);
}
for (dbEntry *d = Modes.db2Index[j]; d; d = d->next) {
p = sprintDB2(p, end, d);
if ((p + 1000) >= end) {
int used = p - buf;
buflen *= 2;
buf = (char *) realloc(buf, buflen);
p = buf + used;
end = buf + buflen;
}
}
}
if (*(p-1) == ',')
p--;
p = safe_snprintf(p, end, "\n}");
struct char_buffer cb2;
cb2.len = p - buf;
cb2.buffer = buf;
writeJsonToFile(Modes.json_dir, "db.json", cb2); // location changed
free(buf);
}
// get next CSV token based on the assumption eot points to the previous delimiter
static inline int nextToken(char delim, char **sot, char **eot, char **eol) {
*sot = *eot + 1;
if (*sot >= *eol)
return 0;
*eot = memchr(*sot, delim, *eol - *sot);
if (!*eot)
return 0;
return 1;
}
static int is_df18_exception(uint32_t addr) {
switch (addr) {
case 0xa08508:
case 0xab33a0:
case 0xa7d24c:
case 0xa6e2cd:
case 0xaa8fca:
case 0xac808b:
case 0x48f6f7:
case 0x7cbc3d:
case 0x7c453a:
case 0x401cf9:
case 0x40206a:
case 0xa3227d:
case 0x478676:
case 0x40389d:
case 0x405acf:
case 0xc82452:
case 0x40334a:
return 1;
default:
return 0;
}
}
// meant to be used with this DB: https://raw.githubusercontent.com/wiedehopf/tar1090-db/csv/aircraft.csv.gz
int dbUpdate(int64_t now) {
static int64_t next_db_check;
if (now < next_db_check) {
return 0;
}
// db update check every 30 seconds
next_db_check = now + 30 * SECONDS;
// this update only takes effect in dbFinishUpdate with all other threads locked
char *filename = Modes.db_file;
if (!filename) {
return 0;
}
struct timespec watch;
startWatch(&watch);
gzFile gzfp = NULL;
struct char_buffer cb = {0};
int fd = open(filename, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "dbUpdate: open db-file failed:");
perror(filename);
return 0;
}
//fprintf(stderr, "checking for db Update\n");
struct stat fileinfo = {0};
if (fstat(fd, &fileinfo)) {
fprintf(stderr, "%s: dbUpdate: fstat failed, wat?!\n", filename);
goto DBU0;
}
int64_t modTime = fileinfo.st_mtim.tv_sec;
if (Modes.dbModificationTime == modTime)
goto DBU0;
gzfp = gzdopen(fd, "r");
if (!gzfp) {
fprintf(stderr, "db update error: gzdopen failed.\n");
goto DBU0;
}
cb = readWholeGz(gzfp, filename);
if (!cb.buffer) {
fprintf(stderr, "database read failed due to readWholeGz.\n");
goto DBU0;
}
if (cb.len < 1000) {
fprintf(stderr, "database file very small, bailing out of dbUpdate.\n");
goto DBU0;
}
if (1) {
// reallocate so we don't waste memory
char *oldBuffer = cb.buffer;
cb.len++; // for adding zero termination
cb.buffer = realloc(cb.buffer, cb.len);
if (!cb.buffer) {
fprintf(stderr, "database read failed due to realloc\n");
sfree(oldBuffer);
goto DBU0;
}
cb.buffer[cb.len - 1] = '\0'; // zero terminate for good measure
}
int alloc = 0;
// memchr is not faster, seems the compiler is smart enough to optimize a simple loop that counts the newlines
for (uint32_t i = 0; i < cb.len; i++) {
if (cb.buffer[i] == '\n')
alloc++;
}
int indexSize = DB_BUCKETS * sizeof(void*);
int entriesSize = alloc * sizeof(dbEntry);
Modes.db2 = cmalloc(entriesSize);
Modes.db2Raw = cb;
Modes.db2Index = cmalloc(indexSize);
memset(Modes.db2Index, 0, indexSize);
if (0) {
fprintf(stderr, "db mem usage: total %d index %d entries %d text %d kB\n",
indexSize / 1024 + entriesSize / 1024 + (int) (cb.len / 1024),
indexSize / 1024, entriesSize / 1024, (int) (cb.len / 1024));
}
if (!Modes.db2 || !Modes.db2Index) {
fprintf(stderr, "db update error: malloc failure!\n");
goto DBU0;
}
fprintf(stderr, "Database update in progress!\n");
char *eob = cb.buffer + cb.len;
char *sol = cb.buffer;
char *eol;
int i;
for (i = 0; eob > sol && (eol = memchr(sol, '\n', eob - sol)); sol = eol + 1) {
char *sot;
char *eot = sol - 1; // this pointer must not be dereferenced, nextToken will increment it.
dbEntry *curr = &Modes.db2[i];
memset(curr, 0, sizeof(dbEntry));
if (!nextToken(';', &sot, &eot, &eol)) continue;
curr->addr = strtol(sot, NULL, 16);
if (curr->addr == 0)
continue;
if (!nextToken(';', &sot, &eot, &eol)) continue;
curr->rawOffset = sot - cb.buffer;
i++; // increment db array index
// add to hashtable
dbPut(curr->addr, Modes.db2Index, curr);
}
if (i < 1) {
fprintf(stderr, "db update error: DB has no entries, maybe old / incorrect format?!\n");
goto DBU0;
}
//fflush(stdout);
//fprintf(stderr, "dbUpdate() done\n");
gzclose(gzfp);
Modes.dbModificationTime = modTime;
if (Modes.json_dir) {
free(writeJsonToFile(Modes.json_dir, "receiver.json", generateReceiverJson()).buffer);
}
double elapsed = stopWatch(&watch) / 1000.0;
fprintf(stderr, "Database update first part took %.3f seconds!\n", elapsed);
// write database to json dir for testing
if (Modes.json_dir && Modes.debug_dbJson) {
db2ToJson();
}
return 1;
DBU0:
if (gzfp)
gzclose(gzfp);
free(cb.buffer);
free(Modes.db2);
free(Modes.db2Index);
Modes.db2 = NULL;
Modes.db2Index = NULL;
Modes.db2Raw.buffer = NULL;
Modes.db2Raw.len = 0;
close(fd);
return 1;
}
static void updateTypeRegRange(void *arg, threadpool_threadbuffers_t *threadbuffers) {
MODES_NOTUSED(threadbuffers);
readsb_task_t *info = (readsb_task_t *) arg;
//fprintf(stderr, "%d %d\n", info->from, info->to);
for (int j = info->from; j < info->to; j++) {
for (struct aircraft *a = Modes.aircraft[j]; a; a = a->next) {
updateTypeReg(a);
}
}
}
int dbFinishUpdate() {
if (!Modes.db2) {
return 0;
}
// finish db update
struct timespec watch;
startWatch(&watch);
sfree(Modes.dbIndex);
sfree(Modes.dbRaw.buffer);
sfree(Modes.db);
Modes.dbIndex = Modes.db2Index;
Modes.dbRaw = Modes.db2Raw;
Modes.db = Modes.db2;
Modes.db2Index = NULL;
Modes.db2 = NULL;
Modes.db2Raw.buffer = NULL;
Modes.db2Raw.len = 0;
/*
for (int j = 0; j < Modes.acBuckets; j++) {
for (struct aircraft *a = Modes.aircraft[j]; a; a = a->next) {
updateTypeReg(a);
}
}
*/
int64_t now = mstime();
threadpool_distribute_and_run(Modes.allPool, Modes.allTasks, updateTypeRegRange, Modes.acBuckets, 0, now);
double elapsed = stopWatch(&watch) / 1000.0;
fprintf(stderr, "Database update done! (critical part took %.3f seconds)\n", elapsed);
return 1;
}
dbEntry *dbGet(uint32_t addr, dbEntry **index) {
if (!index)
return NULL;
dbEntry *d = index[dbHash(addr)];
while (d && d->addr != addr) {
d = d->next;
}
return d;
}
void dbPut(uint32_t addr, dbEntry **index, dbEntry *d) {
uint32_t hash = dbHash(addr);
d->next = index[hash];
index[hash] = d;
}
static void copyDetailFunc(char *sot, char *eot, char *target, int alloc) {
int len = imin(alloc, eot - sot);
memcpy(target, sot, len);
// terminate if string doesn't fill up alloc
// this mildly insane program can hopefully handle unterminated database strings
if (len < alloc) {
target[len] = '\0';
}
sanitize(target, len);
}
static void updateDetails(struct aircraft *curr, struct char_buffer cb, uint32_t offset) {
//fprintf(stdout, "%u %u\n", offset, (uint32_t) cb.len);
char *eob = cb.buffer + cb.len;
char *sol = cb.buffer + offset;
char *eol = memchr(sol, '\n', eob - sol);
char *sot;
char *eot = sol - 1; // this pointer must not be dereferenced, nextToken will increment it.
if (!eol) goto BAD_ENTRY;
#define copyDetail(d) do { copyDetailFunc(sot, eot, curr->d, sizeof(curr->d)); } while (0)
if (!nextToken(';', &sot, &eot, &eol)) goto BAD_ENTRY;
copyDetail(registration);
if (!nextToken(';', &sot, &eot, &eol)) goto BAD_ENTRY;
copyDetail(typeCode);
if (!nextToken(';', &sot, &eot, &eol)) goto BAD_ENTRY;
curr->dbFlags = 0;
for (int j = 0; j < 8 * (int) sizeof(curr->dbFlags) && sot < eot; j++, sot++)
curr->dbFlags |= ((*sot == '1') << j);
if (!nextToken(';', &sot, &eot, &eol)) goto BAD_ENTRY;
copyDetail(typeLong);
if (!nextToken(';', &sot, &eot, &eol)) goto BAD_ENTRY;
copyDetail(year);
if (!nextToken(';', &sot, &eot, &eol)) goto BAD_ENTRY;
copyDetail(ownOp);
#undef copyDetail
if (false) {
// debugging output
fprintf(stdout, "%06X;%.12s;%.4s;%c%c;%.54s\n",
curr->addr,
curr->registration,
curr->typeCode,
curr->dbFlags & 1 ? '1' : '0',
curr->dbFlags & 2 ? '1' : '0',
curr->typeLong);
}
return;
BAD_ENTRY:
curr->registration[0] = '\0';
curr->typeCode[0] = '\0';
curr->typeLong[0] = '\0';
curr->ownOp[0] = '\0';
curr->year[0] = '\0';
curr->dbFlags = 0;
}
void updateTypeReg(struct aircraft *a) {
dbEntry *d = dbGet(a->addr, Modes.dbIndex);
if (d) {
updateDetails(a, Modes.dbRaw, d->rawOffset);
} else {
a->registration[0] = '\0';
a->typeCode[0] = '\0';
a->typeLong[0] = '\0';
a->ownOp[0] = '\0';
a->year[0] = '\0';
a->dbFlags = 0;
}
if (is_df18_exception(a->addr)) {
a->is_df18_exception = 1;
}
if (isMilRange(a->addr)) {
a->dbFlags |= 1;
}
}
static int isMilRange(uint32_t i) {
return
false
// us military
//adf7c8-adf7cf = united states mil_5(uf)
//adf7d0-adf7df = united states mil_4(uf)
//adf7e0-adf7ff = united states mil_3(uf)
//adf800-adffff = united states mil_2(uf)
//ae0000-afffff = united states mil_1(uf)
|| (i >= 0xadf7c8 && i <= 0xafffff)
//010070-01008f = egypt_mil
|| (i >= 0x010070 && i <= 0x01008f)
//0a4000-0a4fff = algeria mil(ap)
|| (i >= 0x0a4000 && i <= 0x0a4fff)
//33ff00-33ffff = italy mil(iy)
|| (i >= 0x33ff00 && i <= 0x33ffff)
//350000-37ffff = spain mil(sp)
|| (i >= 0x350000 && i <= 0x37ffff)
//3aa000-3affff = france mil_1(fs)
|| (i >= 0x3aa000 && i <= 0x3affff)
//3b7000-3bffff = france mil_2(fs)
|| (i >= 0x3b7000 && i <= 0x3bffff)
//3ea000-3ebfff = germany mil_1(df)
|| (i >= 0x3ea000 && i <= 0x3ebfff)
//3f4000-3f7fff = germany mil_2(df)
//3f8000-3fbfff = germany mil_3(df)
|| (i >= 0x3f4000 && i <= 0x3fbfff)
//400000-40003f = united kingdom mil_1(ra)
|| (i >= 0x400000 && i <= 0x40003f)
//43c000-43cfff = united kingdom mil(ra)
|| (i >= 0x43c000 && i <= 0x43cfff)
//444000-446fff = austria mil(aq)
|| (i >= 0x444000 && i <= 0x446fff)
//44f000-44ffff = belgium mil(bc)
|| (i >= 0x44f000 && i <= 0x44ffff)
//457000-457fff = bulgaria mil(bu)
|| (i >= 0x457000 && i <= 0x457fff)
//45f400-45f4ff = denmark mil(dg)
|| (i >= 0x45f400 && i <= 0x45f4ff)
//468000-4683ff = greece mil(gc)
|| (i >= 0x468000 && i <= 0x4683ff)
//473c00-473c0f = hungary mil(hm)
|| (i >= 0x473c00 && i <= 0x473c0f)
//478100-4781ff = norway mil(nn)
|| (i >= 0x478100 && i <= 0x4781ff)
//480000-480fff = netherlands mil(nm)
|| (i >= 0x480000 && i <= 0x480fff)
//48d800-48d87f = poland mil(po)
|| (i >= 0x48d800 && i <= 0x48d87f)
//497c00-497cff = portugal mil(pu)
|| (i >= 0x497c00 && i <= 0x497cff)
//498420-49842f = czech republic mil(ct)
|| (i >= 0x498420 && i <= 0x49842f)
//4b7000-4b7fff = switzerland mil(su)
|| (i >= 0x4b7000 && i <= 0x4b7fff)
//4b8200-4b82ff = turkey mil(tq)
|| (i >= 0x4b8200 && i <= 0x4b82ff)
//506f32-506fff = slovenia mil(sj)
//|| (i >= 0x506f32 && i <= 0x506fff)
//70c070-70c07f = oman mil(on)
|| (i >= 0x70c070 && i <= 0x70c07f)
//710258-71025f = saudi arabia mil_1(sx)
//710260-71027f = saudi arabia mil_2(sx)
//710280-71028f = saudi arabia mil_3(sx)
|| (i >= 0x710258 && i <= 0x71028f)
//710380-71039f = saudi arabia mil_4(sx)
|| (i >= 0x710380 && i <= 0x71039f)
//738a00-738aff = israel mil(iz)
|| (i >= 0x738a00 && i <= 0x738aff)
//7cf800-7cfaff australia mil
|| (i >= 0x7cf800 && i <= 0x7cfaff)
//800200-8002ff = india mil(im)
|| (i >= 0x800200 && i <= 0x8002ff)
//c20000-c3ffff = canada mil(cb)
|| (i >= 0xc20000 && i <= 0xc3ffff)
//e40000-e41fff = brazil mil(bq)
|| (i >= 0xe40000 && i <= 0xe41fff)
//e80600-e806ff = chile mil(cq)
//|| (i >= 0xe80600 && i <= 0xe806ff)
// disabled due to civilian aircraft in hex range
;
}
readsb-3.16/aircraft.h 0000664 0000000 0000000 00000012057 15050573076 0014664 0 ustar 00root root 0000000 0000000 #ifndef AIRCRAFT_H
#define AIRCRAFT_H
void freeAircraftBack();
static inline uint32_t addrHash(uint32_t addr, uint32_t bits) {
const uint64_t m = 0x880355f21e6d1965ULL;
const uint64_t seed = 0x30732349f7810465ULL;
uint64_t h = seed ^ (4 * m);
uint64_t v = addr;
h ^= mix_fasthash(v);
h *= m;
h = mix_fasthash(h);
// collapse to required bit width while retaining as much info as possible
uint64_t res = h ^ (h >> 32);
if (bits < 16)
res ^= (res >> 16);
res ^= (res >> bits);
// mask to fit the requested bit width
res &= (((uint64_t) 1) << bits) - 1;
return (uint32_t) res;
}
void quickInit();
void quickDestroy();
void quickAdd(struct aircraft *a);
void quickRemove(struct aircraft *a);
void aircraftZeroTail(struct aircraft *a);
struct aircraft *aircraftGet(uint32_t addr);
struct aircraft *aircraftCreate(uint32_t addr);
void freeAircraft(struct aircraft *a);
typedef struct dbEntry {
struct dbEntry *next;
uint32_t addr;
uint32_t rawOffset;
} dbEntry;
dbEntry *dbGet(uint32_t addr, dbEntry **index);
void dbPut(uint32_t addr, dbEntry **index, dbEntry *d);
#define BINCRAFT_ALT_FACTOR (1.0f/25.0f)
struct binCraft {
uint32_t hex;
int32_t seen;
// 8
int32_t lon;
int32_t lat;
// 16
int16_t baro_rate;
int16_t geom_rate;
int16_t baro_alt;
int16_t geom_alt;
// 24
uint16_t nav_altitude_mcp; // FCU/MCP selected altitude
uint16_t nav_altitude_fms; // FMS selected altitude
int16_t nav_qnh; // Altimeter setting (QNH/QFE), millibars
int16_t nav_heading; // target heading, degrees (0-359)
// 32
uint16_t squawk; // Squawk
int16_t gs;
int16_t mach;
int16_t roll; // Roll angle, degrees right
// 40
int16_t track; // Ground track
int16_t track_rate; // Rate of change of ground track, degrees/second
int16_t mag_heading; // Magnetic heading
int16_t true_heading; // True heading
// 48
int16_t wind_direction;
int16_t wind_speed;
int16_t oat;
int16_t tat;
// 56
uint16_t tas;
uint16_t ias;
uint16_t pos_rc; // Rc of last computed position
uint16_t messages;
// 64
unsigned category:8; // Aircraft category A0 - D7 encoded as a single hex byte. 00 = unset
unsigned pos_nic:8; // NIC of last computed position
// 66
nav_modes_t nav_modes:8; // enabled modes (autopilot, vnav, etc)
emergency_t emergency:4; // Emergency/priority status
addrtype_t addrtype:4; // highest priority address type seen for this aircraft
// 68
airground_t airground:4; // air/ground status
nav_altitude_source_t nav_altitude_src:4; // source of altitude used by automation
sil_type_t sil_type:4; // SIL supplement from TSS or opstatus
unsigned adsb_version:4; // ADS-B version (from ADS-B operational status); -1 means no ADS-B messages seen
// 70
unsigned adsr_version:4; // As above, for ADS-R messages
unsigned tisb_version:4; // As above, for TIS-B messages
unsigned nac_p : 4; // NACp from TSS or opstatus
unsigned nac_v : 4; // NACv from airborne velocity or opstatus
// 72
unsigned sil : 2; // SIL from TSS or opstatus
unsigned gva : 2; // GVA from opstatus
unsigned sda : 2; // SDA from opstatus
unsigned nic_a : 1; // NIC supplement A from opstatus
unsigned nic_c : 1; // NIC supplement C from opstatus
unsigned nic_baro : 1; // NIC baro supplement from TSS or opstatus
unsigned alert : 1; // FS Flight status alert bit
unsigned spi : 1; // FS Flight status SPI (Special Position Identification) bit
unsigned callsign_valid:1;
unsigned baro_alt_valid:1;
unsigned geom_alt_valid:1;
unsigned position_valid:1;
unsigned gs_valid:1;
// 74
unsigned ias_valid:1;
unsigned tas_valid:1;
unsigned mach_valid:1;
unsigned track_valid:1;
unsigned track_rate_valid:1;
unsigned roll_valid:1;
unsigned mag_heading_valid:1;
unsigned true_heading_valid:1;
unsigned baro_rate_valid:1;
unsigned geom_rate_valid:1;
unsigned nic_a_valid:1;
unsigned nic_c_valid:1;
unsigned nic_baro_valid:1;
unsigned nac_p_valid:1;
unsigned nac_v_valid:1;
unsigned sil_valid:1;
// 76
unsigned gva_valid:1;
unsigned sda_valid:1;
unsigned squawk_valid:1;
unsigned emergency_valid:1;
unsigned spi_valid:1;
unsigned nav_qnh_valid:1;
unsigned nav_altitude_mcp_valid:1;
unsigned nav_altitude_fms_valid:1;
unsigned nav_altitude_src_valid:1;
unsigned nav_heading_valid:1;
unsigned nav_modes_valid:1;
unsigned alert_valid:1;
unsigned wind_valid:1;
unsigned temp_valid:1;
unsigned unused_1:1;
unsigned unused_2:1;
// 78
char callsign[8]; // Flight number
// 86
uint16_t dbFlags;
// 88
char typeCode[4];
// 92
char registration[12];
// 104
uint8_t receiverCount;
uint8_t signal;
uint8_t extraFlags;
uint8_t reserved;
// 108
// javascript sucks, this must be a multiple of 4 bytes for Int32Array to work correctly
int32_t seen_pos;
// 112
#if defined(TRACKS_UUID)
uint32_t receiverId;
#endif
// 116
} __attribute__ ((__packed__));
void toBinCraft(struct aircraft *a, struct binCraft *new, int64_t now);
int dbUpdate(int64_t now);
int dbFinishUpdate();
void updateTypeReg(struct aircraft *a);
#endif
readsb-3.16/ais_charset.c 0000664 0000000 0000000 00000001756 15050573076 0015355 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// ais_charset.c: Valid character set.
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2017 FlightAware, LLC
//
// This file 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
// any later version.
//
// This file 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 .
#include "ais_charset.h"
char ais_charset[65] = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_ !\"#$%&'()*+,-./0123456789:;<=>?";
readsb-3.16/ais_charset.h 0000664 0000000 0000000 00000001722 15050573076 0015353 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// ais_charset.h: Valid character set. (header)
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2017 FlightAware, LLC
//
// This file 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
// any later version.
//
// This file 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 .
#ifndef AIS_CHARSET_H
#define AIS_CHARSET_H
extern char ais_charset[65];
#endif
readsb-3.16/anet.c 0000664 0000000 0000000 00000034020 15050573076 0014005 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// anet.c: Basic TCP socket stuff made a bit less boring
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2016 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
//
// This file incorporates work covered by the following copyright and
// license:
//
// Copyright (c) 2006-2012, Salvatore Sanfilippo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Redis nor the names of its contributors may be used
// to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef __APPLE__
#include "compat/apple/net_compat.h"
#endif
#include "anet.h"
#define _UNUSED(V) ((void) V)
static void anetSetError(char *err, const char *fmt, ...)
{
va_list ap;
if (!err) return;
va_start(ap, fmt);
vsnprintf(err, ANET_ERR_LEN, fmt, ap);
va_end(ap);
}
int anetNonBlock(char *err, int fd)
{
int flags;
/* Set the socket nonblocking.
* Note that fcntl(2) for F_GETFL and F_SETFL can't be
* interrupted by a signal. */
if ((flags = fcntl(fd, F_GETFL)) == -1) {
anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno));
return ANET_ERR;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno));
return ANET_ERR;
}
return ANET_OK;
}
int anetTcpNoDelay(char *err, int fd)
{
int yes = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(yes)) == -1)
{
anetSetError(err, "setsockopt TCP_NODELAY: %s", strerror(errno));
return ANET_ERR;
}
return ANET_OK;
}
int anetSetSendBuffer(char *err, int fd, int buffsize)
{
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void*)&buffsize, sizeof(buffsize)) == -1)
{
anetSetError(err, "setsockopt SO_SNDBUF: %s", strerror(errno));
return ANET_ERR;
}
return ANET_OK;
}
int anetTcpKeepAlive(char *err, int fd)
{
int yes = 1;
int idle = 20;
int interval = 2;
int count = 3;
#ifdef __APPLE__
_UNUSED(yes);
if (set_tcp_keepalive(fd, idle, interval, count) == -1) {
anetSetError(err, "setsockopt tcp keepalive: %s", strerror(errno));
return ANET_ERR;
}
#else
if (
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*) &yes, sizeof(yes))
|| setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*) &idle, sizeof(idle))
|| setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void*) &interval, sizeof(interval))
|| setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void*) &count, sizeof(count))
) {
anetSetError(err, "setsockopt SO_KEEPALIVE: %s", strerror(errno));
return ANET_ERR;
}
#endif
return ANET_OK;
}
static inline void emfileError() {
struct rlimit limits;
getrlimit(RLIMIT_NOFILE, &limits);
fprintf(stderr, "<3>EMFILE: Out of file descriptors (either there is a leak that needs fixing or you need to increase ulimit if you need more than %d connections)!\n", (int) limits.rlim_cur);
}
int anetCreateSocket(char *err, int domain, int typeFlags)
{
int s, on = 1;
if ((s = socket(domain, SOCK_STREAM | typeFlags, 0)) == -1) {
if (errno == EMFILE) {
emfileError();
}
anetSetError(err, "creating socket: %s", strerror(errno));
return ANET_ERR;
}
/* Make sure connection-intensive things like the redis benckmark
* will be able to close/open sockets a zillion of times */
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&on, sizeof(on)) == -1) {
anetSetError(err, "setsockopt SO_REUSEADDR: %s", strerror(errno));
anetCloseSocket(s);
return ANET_ERR;
}
return s;
}
#define ANET_CONNECT_NONE 0
#define ANET_CONNECT_NONBLOCK 1
static int anetTcpGenericConnect(char *err, char *addr, char *service, int flags, struct sockaddr_storage *ss)
{
int s;
struct addrinfo gai_hints;
struct addrinfo *gai_result, *p;
int gai_error;
gai_hints.ai_family = AF_UNSPEC;
gai_hints.ai_socktype = SOCK_STREAM;
gai_hints.ai_protocol = 0;
gai_hints.ai_flags = 0;
gai_hints.ai_addrlen = 0;
gai_hints.ai_addr = NULL;
gai_hints.ai_canonname = NULL;
gai_hints.ai_next = NULL;
gai_error = getaddrinfo(addr, service, &gai_hints, &gai_result);
if (gai_error != 0) {
anetSetError(err, "can't resolve %s: %s", addr, gai_strerror(gai_error));
return ANET_ERR;
}
for (p = gai_result; p != NULL; p = p->ai_next) {
int nonBlock = (flags & ANET_CONNECT_NONBLOCK) ? SOCK_NONBLOCK : 0;
if ((s = anetCreateSocket(err, p->ai_family, nonBlock)) == ANET_ERR)
continue;
if (connect(s, p->ai_addr, p->ai_addrlen) >= 0 || (errno == EINPROGRESS && (flags & ANET_CONNECT_NONBLOCK))
) {
// If we were passed a place to toss the sockaddr info, save it
if (ss) {
memcpy(ss, p->ai_addr, sizeof(*ss));
}
if (gai_result) {
freeaddrinfo(gai_result);
gai_result = NULL;
}
return s;
}
anetSetError(err, "connect: %s", strerror(errno));
anetCloseSocket(s);
}
if (gai_result) {
freeaddrinfo(gai_result);
gai_result = NULL;
}
return ANET_ERR;
}
int anetTcpConnect(char *err, char *addr, char *service, struct sockaddr_storage *ss)
{
return anetTcpGenericConnect(err,addr,service,ANET_CONNECT_NONE, ss);
}
int anetTcpNonBlockConnect(char *err, char *addr, char *service, struct sockaddr_storage *ss)
{
return anetTcpGenericConnect(err,addr,service,ANET_CONNECT_NONBLOCK, ss);
}
int anetGetaddrinfo(char *err, char *addr, char *service, struct addrinfo **gai_result)
{
struct addrinfo gai_hints;
int gai_error;
gai_hints.ai_family = AF_UNSPEC;
gai_hints.ai_socktype = SOCK_STREAM;
gai_hints.ai_protocol = 0;
gai_hints.ai_flags = 0;
gai_hints.ai_addrlen = 0;
gai_hints.ai_addr = NULL;
gai_hints.ai_canonname = NULL;
gai_hints.ai_next = NULL;
gai_error = getaddrinfo(addr, service, &gai_hints, gai_result);
if (gai_error != 0) {
anetSetError(err, "can't resolve %s: %s", addr, gai_strerror(gai_error));
return ANET_ERR;
}
return 0;
}
int anetTcpNonBlockConnectAddr(char *err, struct addrinfo *p)
{
int s;
if ((s = anetCreateSocket(err, p->ai_family, SOCK_NONBLOCK)) == ANET_ERR)
return ANET_ERR;
if (connect(s, p->ai_addr, p->ai_addrlen) >= 0) {
return s;
}
if (errno == EINPROGRESS) {
return s;
}
anetSetError(err, "connect: %s", strerror(errno));
anetCloseSocket(s);
return ANET_ERR;
}
/* Like read(2) but make sure 'count' is read before to return
* (unless error or EOF condition is encountered) */
int anetRead(int fd, char *buf, int count)
{
int nread, totlen = 0;
while(totlen < count) {
nread = read(fd, buf, (size_t) (count - totlen));
if (nread == 0) return totlen;
if (nread == -1) return -1;
totlen += nread;
buf += nread;
}
return totlen;
}
/* Like write(2) but make sure 'count' is read before to return
* (unless error is encountered) */
int anetWrite(int fd, char *buf, int count)
{
int nwritten, totlen = 0;
while(totlen != count) {
nwritten = write(fd, buf, (size_t) (count - totlen));
if (nwritten == 0) return totlen;
if (nwritten == -1) return -1;
totlen += nwritten;
buf += nwritten;
}
return totlen;
}
static int anetListen(char *err, int s, struct sockaddr *sa, socklen_t len) {
if (sa->sa_family == AF_INET6) {
int on = 1;
setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
}
if (bind(s,sa,len) == -1) {
anetSetError(err, "bind: %s", strerror(errno));
anetCloseSocket(s);
return ANET_ERR;
}
// no real drawback to using a large backlog, will usually be capped to 4096 by the kernel
if (listen(s, 65535) == -1) {
anetSetError(err, "listen: %s", strerror(errno));
anetCloseSocket(s);
return ANET_ERR;
}
return ANET_OK;
}
static void anetSetBuffers(int fd, int sndsize, int rcvsize) {
if (sndsize > 0 && setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void*)&sndsize, sizeof(sndsize)) == -1) {
fprintf(stderr, "setsockopt SO_SNDBUF: %s", strerror(errno));
}
if (rcvsize > 0 && setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&rcvsize, sizeof(rcvsize)) == -1) {
fprintf(stderr, "setsockopt SO_RCVBUF: %s", strerror(errno));
}
}
int anetTcpServer(char *err, char *service, char *bindaddr, int *fds, int nfds, int flags, int sndsize, int rcvsize)
{
int s;
int i = 0;
struct addrinfo gai_hints;
struct addrinfo *gai_result, *p;
int gai_error;
gai_hints.ai_family = AF_UNSPEC;
gai_hints.ai_socktype = SOCK_STREAM;
gai_hints.ai_protocol = 0;
gai_hints.ai_flags = AI_PASSIVE;
gai_hints.ai_addrlen = 0;
gai_hints.ai_addr = NULL;
gai_hints.ai_canonname = NULL;
gai_hints.ai_next = NULL;
gai_error = getaddrinfo(bindaddr, service, &gai_hints, &gai_result);
if (gai_error != 0) {
anetSetError(err, "can't resolve %s: %s", bindaddr, gai_strerror(gai_error));
return ANET_ERR;
}
for (p = gai_result; p != NULL && i < nfds; p = p->ai_next) {
if ((s = anetCreateSocket(err, p->ai_family, flags)) == ANET_ERR)
continue;
anetSetBuffers(s, sndsize, rcvsize);
if (anetListen(err, s, p->ai_addr, p->ai_addrlen) == ANET_ERR) {
continue;
}
fds[i++] = s;
}
if (gai_result) {
freeaddrinfo(gai_result);
gai_result = NULL;
}
return (i > 0 ? i : ANET_ERR);
}
int anetUnixSocket(char *err, char *path, int flags)
{
int s;
if ((s = anetCreateSocket(err, AF_UNIX, flags)) == ANET_ERR) {
return ANET_ERR;
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, path);
if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
anetSetError(err, "bind: %s", strerror(errno));
anetCloseSocket(s);
return ANET_ERR;
}
// explicitely setting tcp buffers causes failure of linux tcp window auto tuning ... it just doesn't work well without the auto tuning
// anetSetBuffers(s, 512 * 1024, 64 * 1024);
// no real drawback to using a large backlog, will usually be capped to 4096 by the kernel
if (listen(s, 65535) == -1) {
anetSetError(err, "listen: %s", strerror(errno));
anetCloseSocket(s);
return ANET_ERR;
}
return s;
}
int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len, int flags)
{
int fd;
fd = accept4(s, sa, len, flags);
if (fd == -1) {
if (errno == EMFILE) {
emfileError();
}
if (errno != EINTR) {
anetSetError(err, "Generic accept error: %s %d", strerror(errno), fd);
}
return ANET_ERR;
}
return fd;
}
static inline int get_socket_error(int fd) {
int err = 1;
socklen_t len = sizeof err;
if (-1 == getsockopt(fd, SOL_SOCKET, SO_ERROR, (char *) &err, &len)) {
fprintf(stderr, "Get client socket error failed.\n");
}
if (err) {
errno = err; // Set errno to the socket SO_ERROR
}
return err;
}
void anetCloseSocket(int fd) {
if (fd < 0) {
return;
}
get_socket_error(fd); // First clear any errors, which can cause close to fail
if (shutdown(fd, SHUT_RDWR) < 0) { // Secondly, terminate the reliable delivery
if (errno != ENOTCONN && errno != EINVAL) { // SGI causes EINVAL
fprintf(stderr, "Shutdown client socket failed.\n");
}
}
close(fd);
}
readsb-3.16/anet.h 0000664 0000000 0000000 00000007325 15050573076 0014022 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// anet.h: Basic TCP socket stuff made a bit less boring (header)
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2016 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
//
// This file incorporates work covered by the following copyright and
// license:
//
// Copyright (c) 2006-2012, Salvatore Sanfilippo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Redis nor the names of its contributors may be used
// to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
#ifndef ANET_H
#define ANET_H
#define ANET_OK 0
#define ANET_ERR -1
#define ANET_ERR_LEN 256
#if defined(__sun)
#define AF_LOCAL AF_UNIX
#endif
#include
#include
#include
int anetTcpConnect(char *err, char *addr, char *service, struct sockaddr_storage *ss);
int anetTcpNonBlockConnect(char *err, char *addr, char *service, struct sockaddr_storage *ss);
int anetTcpNonBlockConnectAddr(char *err, struct addrinfo *p);
int anetGetaddrinfo(char *err, char *addr, char *service, struct addrinfo **gai_result);
int anetRead(int fd, char *buf, int count);
int anetTcpServer(char *err, char *service, char *bindaddr, int *fds, int nfds, int flags, int sndsize, int rcvsize);
int anetUnixSocket(char *err, char *path, int flags);
int anetGenericAccept(char *err, int s, struct sockaddr *sa, socklen_t *len, int flags);
int anetWrite(int fd, char *buf, int count);
int anetNonBlock(char *err, int fd);
int anetTcpNoDelay(char *err, int fd);
int anetTcpKeepAlive(char *err, int fd);
int anetSetSendBuffer(char *err, int fd, int buffsize);
int anetCreateSocket(char *err, int domain, int typeFlags);
void anetCloseSocket(int fd);
#endif
readsb-3.16/api.c 0000664 0000000 0000000 00000220701 15050573076 0013632 0 ustar 00root root 0000000 0000000 #include "readsb.h"
static int apiUpdate();
static inline uint32_t hexHash(uint32_t addr, struct apiBuffer *buffer) {
uint32_t res = addrHash(addr, buffer->hashBits);
//fprintf(stderr, "%06x -> %06u\n", addr, res);
return res;
}
static inline uint32_t regHash(char *reg, struct apiBuffer *buffer) {
const uint64_t seed = 0x30732349f7810465ULL;
uint64_t h = fasthash64(reg, memberSize(struct binCraft, registration), seed);
uint32_t bits = buffer->hashBits;
uint64_t res = h ^ (h >> 32);
if (bits < 16)
res ^= (res >> 16);
res ^= (res >> bits);
// mask to fit the requested bit width
res &= (((uint64_t) 1) << bits) - 1;
//fprintf(stderr, "%s -> %06u\n", reg, (uint32_t) res);
return (uint32_t) res;
}
static inline uint32_t callsignHash(char *callsign, struct apiBuffer *buffer) {
const uint64_t seed = 0x30732349f7810465ULL;
uint64_t h = fasthash64(callsign, 8, seed);
uint32_t bits = buffer->hashBits;
uint64_t res = h ^ (h >> 32);
if (bits < 16)
res ^= (res >> 16);
res ^= (res >> bits);
// mask to fit the requested bit width
res &= (((uint64_t) 1) << bits) - 1;
return (uint32_t) res;
}
static int antiSpam(int64_t *nextPrint, int64_t interval) {
int64_t now = mstime();
if (now > *nextPrint) {
*nextPrint = now + interval;
return 1;
} else {
return 0;
}
}
static int compareLon(const void *p1, const void *p2) {
struct apiEntry *a1 = (struct apiEntry*) p1;
struct apiEntry *a2 = (struct apiEntry*) p2;
return (a1->bin.lon > a2->bin.lon) - (a1->bin.lon < a2->bin.lon);
}
static struct range findLonRange(int32_t ref_from, int32_t ref_to, struct apiEntry *list, int len) {
struct range res;
memset(&res, 0, sizeof(res));
if (len == 0 || ref_from > ref_to)
return res;
// get lower bound
int i = 0;
int j = len - 1;
while (j > i + 1) {
int pivot = (i + j) / 2;
if (list[pivot].bin.lon < ref_from)
i = pivot;
else
j = pivot;
}
if (list[j].bin.lon < ref_from) {
res.from = j + 1;
} else if (list[i].bin.lon < ref_from) {
res.from = i + 1;
} else {
res.from = i;
}
// get upper bound (exclusive)
i = imin(res.from, len - 1);
j = len - 1;
while (j > i + 1) {
int pivot = (i + j) / 2;
if (list[pivot].bin.lon <= ref_to)
i = pivot;
else
j = pivot;
}
if (list[j].bin.lon <= ref_to) {
res.to = j + 1;
} else if (list[i].bin.lon <= ref_to) {
res.to = i + 1;
} else {
res.to = i;
}
return res;
}
static int filter_alt_baro(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, struct apiOptions *options) {
int count = 0;
float reverse_alt_factor = 1.0f / BINCRAFT_ALT_FACTOR;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
int32_t alt = INT32_MIN;
if (e->bin.baro_alt_valid) {
alt = e->bin.baro_alt * reverse_alt_factor;
} else if (e->bin.airground == AG_GROUND) {
alt = 0;
}
if (alt >= options->above_alt_baro && alt <= options->below_alt_baro && alt != INT32_MIN) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filter_dbFlags(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, struct apiOptions *options) {
int count = 0;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
if (
(options->filter_mil && (e->bin.dbFlags & 1))
|| (options->filter_interesting && (e->bin.dbFlags & 2))
|| (options->filter_pia && (e->bin.dbFlags & 4))
|| (options->filter_ladd && (e->bin.dbFlags & 8))
) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterWithPos(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc) {
int count = 0;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
if (e->bin.position_valid) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterSquawk(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, unsigned squawk) {
int count = 0;
for (int i = 0; i < haylen; i++) {
struct apiEntry *e = &haystack[i];
//fprintf(stderr, "%04x %04x\n", options->squawk, e->bin.squawk);
if (e->bin.squawk == squawk && e->bin.squawk_valid) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterCallsignPrefix(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, char *callsign_prefix) {
int count = 0;
int prefix_len = strlen(callsign_prefix);
for (int i = 0; i < prefix_len; i++) {
// upper case callsign prefix
callsign_prefix[i] = toupper(callsign_prefix[i]);
}
for (int j = 0; j < haylen; j++) {
struct apiEntry *e = &haystack[j];
if (e->bin.callsign_valid && strncmp(e->bin.callsign, callsign_prefix, prefix_len) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
return count;
}
static int filterCallsignExact(struct apiEntry *haystack, int haylen, struct apiEntry *matches, size_t *alloc, char *callsign) {
int callLen = memberSize(struct binCraft, callsign);
for (int i = 0; i < callLen; i++) {
// replace null padding with space padding
if (callsign[i] == '\0') {
callsign[i] = ' ';
}
// upper case callsign
callsign[i] = toupper(callsign[i]);
}
int count = 0;
for (int j = 0; j < haylen; j++) {
struct apiEntry *e = &haystack[j];
if (e->bin.callsign_valid) {
//fprintf(stderr, "%s %s\n", callsign, e->bin.callsign);
if (strncmp(e->bin.callsign, callsign, callLen) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
}
return count;
}
static int filterTypeList(struct apiEntry *haystack, int haylen, char *typeList, int typeCount, struct apiEntry *matches, size_t *alloc) {
int count = 0;
int typeLen = memberSize(struct binCraft, typeCode);
for (int k = 0; k < typeCount; k++) {
char *typeCode = typeList + typeLen * k;
// upper case typeCode
for (int i = 0; i < typeLen; i++) {
typeCode[i] = toupper(typeCode[i]);
}
}
for (int j = 0; j < haylen; j++) {
struct apiEntry *e = &haystack[j];
for (int k = 0; k < typeCount; k++) {
char *typeCode = typeList + typeLen * k;
if (strncmp(e->bin.typeCode, typeCode, typeLen) == 0) {
//fprintf(stderr, "typeCode: %.4s %.4s alloc increase by %d\n", e->bin.typeCode, typeCode, e->jsonOffset.len);
matches[count++] = *e;
*alloc += e->jsonOffset.len;
// break inner loop
break;
}
}
}
return count;
}
static int inLatRange(struct apiEntry *e, int32_t lat1, int32_t lat2, struct apiOptions *options) {
return (e->bin.lat >= lat1 && e->bin.lat <= lat2 && (e->bin.position_valid || options->binCraft));
}
static int findInBox(struct apiEntry *haystack, int haylen, struct apiOptions *options, struct apiEntry *matches, size_t *alloc) {
double *box = options->box;
struct range r[2];
memset(r, 0, sizeof(r));
int count = 0;
int32_t lat1 = (int32_t) (box[0] * 1E6);
int32_t lat2 = (int32_t) (box[1] * 1E6);
int32_t lon1 = (int32_t) (box[2] * 1E6);
int32_t lon2 = (int32_t) (box[3] * 1E6);
if (lon1 <= lon2) {
r[0] = findLonRange(lon1, lon2, haystack, haylen);
} else if (lon1 > lon2) {
r[0] = findLonRange(lon1, 180E6, haystack, haylen);
r[1] = findLonRange(-180E6, lon2, haystack, haylen);
//fprintf(stderr, "%.1f to 180 and -180 to %1.f\n", lon1 / 1E6, lon2 / 1E6);
}
for (int k = 0; k < 2; k++) {
for (int j = r[k].from; j < r[k].to; j++) {
struct apiEntry *e = &haystack[j];
if (inLatRange(e, lat1, lat2, options)) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
}
}
}
//fprintf(stderr, "box: lat %.1f to %.1f, lon %.1f to %.1f, count: %d\n", box[0], box[1], box[2], box[3], count);
return count;
}
static int findRegList(struct apiBuffer *buffer, char *regList, int regCount, struct apiEntry *matches, size_t *alloc) {
struct apiEntry **hashList = buffer->regHash;
int count = 0;
int regLen = memberSize(struct binCraft, registration);
for (int k = 0; k < regCount; k++) {
char *reg = ®List[k * regLen];
// upper case reg
for (int i = 0; i < regLen; i++) {
reg[i] = toupper(reg[i]);
}
//fprintf(stderr, "reg: %s\n", reg);
uint32_t hash = regHash(reg, buffer);
struct apiEntry *e = hashList[hash];
while (e) {
if (strncmp(e->bin.registration, reg, regLen) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
break;
}
e = e->nextReg;
}
}
return count;
}
static int findCallsignList(struct apiBuffer *buffer, char *callsignList, int callsignCount, struct apiEntry *matches, size_t *alloc) {
struct apiEntry **hashList = buffer->callsignHash;
int count = 0;
int callLen = memberSize(struct binCraft, callsign);
for (int k = 0; k < callsignCount; k++) {
char *callsign = &callsignList[k * callLen];
// replace null padding with space padding, upper case input
for (int i = 0; i < callLen; i++) {
callsign[i] = toupper(callsign[i]);
if (callsign[i] == '\0') {
callsign[i] = ' ';
}
}
uint32_t hash = callsignHash(callsign, buffer);
//fprintf(stderr, "callsign: %8s hash: %u\n", callsign, hash);
struct apiEntry *e = hashList[hash];
while (e) {
//fprintf(stderr, "callsign: %8s\n", e->bin.callsign);
if (strncmp(e->bin.callsign, callsign, callLen) == 0) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
break;
}
e = e->nextCallsign;
}
}
return count;
}
static int findHexList(struct apiBuffer *buffer, uint32_t *hexList, int hexCount, struct apiEntry *matches, size_t *alloc) {
struct apiEntry **hashList = buffer->hexHash;
int count = 0;
for (int k = 0; k < hexCount; k++) {
uint32_t addr = hexList[k];
uint32_t hash = hexHash(addr, buffer);
//fprintf(stderr, "----> %06x -> %06u\n", addr, hash);
struct apiEntry *e = hashList[hash];
while (e) {
if (e->bin.hex == addr) {
matches[count++] = *e;
*alloc += e->jsonOffset.len;
break;
}
e = e->nextHex;
}
}
return count;
}
static int findInCircle(struct apiEntry *haystack, int haylen, struct apiOptions *options, struct apiEntry *matches, size_t *alloc) {
struct apiCircle *circle = &options->circle;
struct range r[2];
memset(r, 0, sizeof(r));
int count = 0;
double lat = circle->lat;
double lon = circle->lon;
double radius = circle->radius; // in meters
bool onlyClosest = circle->onlyClosest;
double circum = 40075e3; // earth circumference is 40075km
double fudge = 1.002; // make the box we check a little bigger
double londiff = fudge * radius / (cos(lat * M_PI / 180.0) * circum + 1) * 360;
double o1 = lon - londiff;
double o2 = lon + londiff;
o1 = o1 < -180 ? o1 + 360: o1;
o2 = o2 > 180 ? o2 - 360 : o2;
if (londiff >= 180) {
// just check all lon
o1 = -180;
o2 = 180;
}
double latdiff = fudge * radius / (circum / 2) * 180.0;
double a1 = lat - latdiff;
double a2 = lat + latdiff;
if (a1 < -90 || a2 > 90) {
// going over a pole, just check all lon
o1 = -180;
o2 = 180;
}
int32_t lat1 = (int32_t) (a1 * 1E6);
int32_t lat2 = (int32_t) (a2 * 1E6);
int32_t lon1 = (int32_t) (o1 * 1E6);
int32_t lon2 = (int32_t) (o2 * 1E6);
//fprintf(stderr, "radius:%8.0f latdiff: %8.0f londiff: %8.0f\n", radius, greatcircle(a1, lon, lat, lon), greatcircle(lat, o1, lat, lon, 0));
if (lon1 <= lon2) {
r[0] = findLonRange(lon1, lon2, haystack, haylen);
} else if (lon1 > lon2) {
r[0] = findLonRange(lon1, 180E6, haystack, haylen);
r[1] = findLonRange(-180E6, lon2, haystack, haylen);
//fprintf(stderr, "%.1f to 180 and -180 to %1.f\n", lon1 / 1E6, lon2 / 1E6);
}
if (onlyClosest) {
bool found = false;
double minDistance = 300E6; // larger than any distances we encounter, also how far light travels in a second
for (int k = 0; k < 2; k++) {
for (int j = r[k].from; j < r[k].to; j++) {
struct apiEntry *e = &haystack[j];
if (inLatRange(e, lat1, lat2, options)) {
double dist = greatcircle(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6, 0);
if (dist < radius && dist < minDistance) {
// first match is overwritten repeatedly
matches[0] = *e;
matches[0].distance = (float) dist;
minDistance = dist;
found = true;
}
}
}
}
if (found) {
// calculate bearing for (the only) match
struct apiEntry *e = &matches[0];
*alloc += e->jsonOffset.len;
e->direction = (float) bearing(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6);
count = 1;
}
}
if (!onlyClosest) {
for (int k = 0; k < 2; k++) {
for (int j = r[k].from; j < r[k].to; j++) {
struct apiEntry *e = &haystack[j];
if (inLatRange(e, lat1, lat2, options)) {
double dist = greatcircle(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6, 0);
if (dist < radius) {
matches[count] = *e;
matches[count].distance = (float) dist;
matches[count].direction = (float) bearing(lat, lon, e->bin.lat / 1E6, e->bin.lon / 1E6);
*alloc += e->jsonOffset.len;
count++;
}
}
}
}
}
//fprintf(stderr, "circle count: %d\n", count);
return count;
}
static struct apiEntry *apiAlloc(int count) {
struct apiEntry *buf = cmalloc(count * sizeof(struct apiEntry));
if (!buf) {
fprintf(stderr, "FATAL: apiAlloc malloc fail\n");
setExit(2);
}
return buf;
}
static struct char_buffer apiReq(struct apiThread *thread, struct apiOptions *options) {
int flip = atomic_load(&Modes.apiFlip[thread->index]);
struct apiBuffer *buffer = &Modes.apiBuffer[flip];
struct apiEntry *haystack;
int haylen;
struct range pos_range;
struct range all_range;
if (options->filter_dbFlag) {
haystack = buffer->list_flag;
haylen = buffer->len_flag;
pos_range = buffer->list_flag_pos_range;
all_range.from = 0;
all_range.to = haylen;
} else {
haystack = buffer->list;
haylen = buffer->len;
pos_range = buffer->list_pos_range;
all_range.from = 0;
all_range.to = haylen;
}
struct char_buffer cb = { 0 };
struct apiEntry *matches = NULL;
size_t alloc_base = API_REQ_PADSTART + 1024;
size_t alloc = alloc_base;
int count = 0;
int doFree = 0;
if (options->is_box) {
int combined_len = haylen;
if (options->is_hexList) {
// this is a special case, in addition to the box, also return results for the hexList
// we don't bother deduplicating, so this can return results more than once
// thus allocate haylen and then also the number of hexes queried in addition
combined_len += options->hexCount;
}
doFree = 1; matches = apiAlloc(combined_len); if (!matches) { return cb; };
// first get matches for the box
count = findInBox(haystack, haylen, options, matches, &alloc);
if (options->is_hexList) {
// optionally add matches for &find_hex
count += findHexList(buffer, options->hexList, options->hexCount, matches + count, &alloc);
}
} else if (options->is_circle) {
doFree = 1; matches = apiAlloc(haylen); if (!matches) { return cb; };
count = findInCircle(haystack, haylen, options, matches, &alloc);
alloc += count * 30; // adding 27 characters per entry: ,"dst":1000.000, "dir":357
} else if (options->is_hexList) {
doFree = 1; matches = apiAlloc(options->hexCount); if (!matches) { return cb; };
count = findHexList(buffer, options->hexList, options->hexCount, matches, &alloc);
} else if (options->is_regList) {
doFree = 1; matches = apiAlloc(options->regCount); if (!matches) { return cb; };
count = findRegList(buffer, options->regList, options->regCount, matches, &alloc);
} else if (options->is_callsignList) {
doFree = 1; matches = apiAlloc(options->callsignCount); if (!matches) { return cb; };
count = findCallsignList(buffer, options->callsignList, options->callsignCount, matches, &alloc);
} else if (options->is_typeList) {
doFree = 1; matches = apiAlloc(haylen); if (!matches) { return cb; };
count = filterTypeList(haystack, haylen, options->typeList, options->typeCount, matches, &alloc);
} else if (options->all || options->all_with_pos) {
struct range range;
if (options->all) {
range = all_range;
} else if ( options->all_with_pos) {
range = pos_range;
} else {
fprintf(stderr, "FATAL: unreachablei ahchoh8R\n");
setExit(2);
return cb;
}
count = range.to - range.from;
if (count > 0) {
struct apiEntry *first = &haystack[range.from];
struct apiEntry *last = &haystack[range.to - 1];
// assume continuous allocation from generation of api buffer
alloc += last->jsonOffset.offset + last->jsonOffset.len - first->jsonOffset.offset;
doFree = 0;
matches = first;
} else {
doFree = 0;
matches = NULL;
}
}
if (options->filter_squawk) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterSquawk(matches, count, filtered, &alloc, options->squawk);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
// filter all_with_pos as pos_range unreliable due do gpsOkBefore f***ery
if (options->filter_with_pos || options->all_with_pos) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterWithPos(matches, count, filtered, &alloc);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_dbFlag) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filter_dbFlags(matches, count, filtered, &alloc, options);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_alt_baro) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filter_alt_baro(matches, count, filtered, &alloc, options);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_callsign_prefix) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterCallsignPrefix(matches, count, filtered, &alloc, options->callsign_prefix);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_callsign_exact) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterCallsignExact(matches, count, filtered, &alloc, options->callsign_exact);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
if (options->filter_typeList) {
struct apiEntry *filtered = apiAlloc(count); if (!filtered) { return cb; }
size_t alloc = alloc_base;
count = filterTypeList(matches, count, options->typeList, options->typeCount, filtered, &alloc);
if (doFree) { sfree(matches); }; doFree = 1; matches = filtered;
}
// elementSize only applies to binCraft output
uint32_t elementSize = sizeof(struct binCraft);
if (options->binCraft) {
alloc = API_REQ_PADSTART + 2 * elementSize + count * elementSize;
}
cb.buffer = cmalloc(alloc);
if (!cb.buffer)
return cb;
char *payload = cb.buffer + API_REQ_PADSTART;
char *p = payload;
char *end = cb.buffer + alloc;
if (options->binCraft) {
memset(p, 0, elementSize);
#define memWrite(p, var) do { if (p + sizeof(var) > end) { break; }; memcpy(p, &var, sizeof(var)); p += sizeof(var); } while(0)
int64_t now = buffer->timestamp;
memWrite(p, now);
memWrite(p, elementSize);
uint32_t ac_count_pos = Modes.globalStatsCount.readsb_aircraft_with_position;
memWrite(p, ac_count_pos);
uint32_t index = 0;
memWrite(p, index);
int16_t south = -90;
int16_t west = -180;
int16_t north = 90;
int16_t east = 180;
if (options->is_box) {
south = nearbyint(options->box[0]);
north = nearbyint(options->box[1]);
west = nearbyint(options->box[2]);
east = nearbyint(options->box[3]);
}
memWrite(p, south);
memWrite(p, west);
memWrite(p, north);
memWrite(p, east);
uint32_t messageCount = Modes.stats_current.messages_total + Modes.stats_alltime.messages_total;
memWrite(p, messageCount);
uint32_t resultCount = count;
memWrite(p, resultCount);
int32_t dummy = 0;
memWrite(p, dummy);
memWrite(p, Modes.binCraftVersion);
uint32_t messageRate = nearbyint(Modes.messageRate * 10);
memWrite(p, messageRate);
uint32_t flags = 0;
if (Modes.json_globe_index || Modes.apiShutdownDelay) {
flags |= (1 << 0);
}
memWrite(p, flags);
#undef memWrite
if (p - payload > (int) elementSize) {
fprintf(stderr, "apiBin: too many details in first element\n");
}
p = payload + elementSize;
for (int i = 0; i < count; i++) {
if (unlikely(p + elementSize > end)) {
fprintf(stderr, "search code deeK9OoR: count: %d need: %ld alloc: %ld\n", count, (long) ((count + 1) * elementSize), (long) alloc);
break;
}
struct apiEntry *e = &matches[i];
memcpy(p, &e->bin, elementSize);
p += elementSize;
}
} else {
if (options->jamesv2) {
p = safe_snprintf(p, end, "{\"ac\":[");
} else {
p = safe_snprintf(p, end, "{\"now\": %.3f", buffer->timestamp / 1000.0);
p = safe_snprintf(p, end, "\n,\"aircraft\":[");
}
char *json = buffer->json;
for (int i = 0; i < count; i++) {
struct apiEntry *e = &matches[i];
struct offset off = e->jsonOffset; // READ-ONLY here
if (unlikely(p + off.len + 100 >= end)) {
fprintf(stderr, "search code ieva2aeV: count: %d need: %ld alloc: %ld\n", count, (long) ((p + off.len + 100) - payload), (long) alloc);
break;
}
memcpy(p, json + off.offset, off.len);
p += off.len;
if (options->is_circle) {
// json objects in cache are terminated by a comma: \n{ .... },
p -= 2; // remove \} and , and make sure printf puts those back
p = safe_snprintf(p, end, ",\"dst\":%.3f,\"dir\":%.1f},", e->distance / 1852.0, e->direction);
}
}
// json objects in cache are terminated by a comma: \n{ .... },
if (*(p - 1) == ',')
p--; // remove trailing comma if necessary
options->request_processed = microtime();
p = safe_snprintf(p, end, "\n]");
if (options->jamesv2) {
p = safe_snprintf(p, end, "\n,\"msg\": \"No error\"");
p = safe_snprintf(p, end, "\n,\"now\": %lld", (long long) buffer->timestamp);
p = safe_snprintf(p, end, "\n,\"total\": %d", count);
p = safe_snprintf(p, end, "\n,\"ctime\": %lld", (long long) buffer->timestamp);
p = safe_snprintf(p, end, "\n,\"ptime\": %lld", (long long) nearbyint((options->request_processed - options->request_received) / 1000.0));
} else {
p = safe_snprintf(p, end, "\n,\"resultCount\": %d", count);
p = safe_snprintf(p, end, "\n,\"ptime\": %.3f", (options->request_processed - options->request_received) / 1000.0);
}
p = safe_snprintf(p, end, "\n}\n");
}
cb.len = p - cb.buffer;
size_t payload_len = p - payload;
if (cb.len > alloc) {
fprintf(stderr, "apiReq buffer insufficient\n");
}
if (doFree) {
sfree(matches);
}
if (options->zstd || options->zstd_encode) {
struct char_buffer new = { 0 };
size_t new_alloc = API_REQ_PADSTART + ZSTD_compressBound(alloc);
new.buffer = cmalloc(new_alloc);
memset(new.buffer, 0x0, new_alloc);
struct char_buffer dst;
dst.buffer = new.buffer + API_REQ_PADSTART;
dst.len = new_alloc - API_REQ_PADSTART;
//fprintf(stderr, "payload_len %ld\n", (long) payload_len);
size_t compressedSize = ZSTD_compressCCtx(thread->cctx,
dst.buffer, dst.len,
payload, payload_len,
API_ZSTD_LVL);
dst.len = compressedSize;
new.len = API_REQ_PADSTART + compressedSize;
ident(dst);
//free uncompressed buffer
sfree(cb.buffer);
cb = new;
if (ZSTD_isError(compressedSize)) {
fprintf(stderr, "API zstd error: %s\n", ZSTD_getErrorName(compressedSize));
sfree(cb.buffer);
cb.buffer = NULL;
cb.len = 0;
return cb;
}
//fprintf(stderr, "first 4 bytes: %08x len: %ld\n", *((uint32_t *) cb.buffer), (long) cb.len);
}
return cb;
}
static inline int apiAdd(struct apiBuffer *buffer, struct aircraft *a, int64_t now) {
if (!(includeAircraftJson(now, a)))
return 0;
if (buffer->len >= buffer->alloc) {
return -1;
}
struct apiEntry *entry = &(buffer->list[buffer->len]);
memset(entry, 0, sizeof(struct apiEntry));
toBinCraft(a, &entry->bin, now);
if (trackDataValid(&a->pos_reliable_valid)) {
// position valid
// else if (trackDataAge(now, &a->pos_reliable_valid) < 30 * MINUTES)
} else if (a->nogpsCounter >= NOGPS_SHOW && now - a->seenAdsbReliable < NOGPS_DWELL) {
// keep in box
} else {
// change lat / lon for sorting purposes
entry->bin.lat = INT32_MAX;
entry->bin.lon = INT32_MAX;
}
buffer->aircraftJsonCount++;
entry->globe_index = a->globe_index;
buffer->len++;
return 1;
}
static inline void apiGenerateJson(struct apiBuffer *buffer, int64_t now) {
sfree(buffer->json);
buffer->json = NULL;
size_t alloc = buffer->len * 1024 + 4096; // The initial buffer is resized as needed
buffer->json = (char *) cmalloc(alloc);
char *p = buffer->json;
char *end = buffer->json + alloc;
for (int i = 0; i < buffer->len; i++) {
if ((p + 16 * 1024) >= end) {
int used = p - buffer->json;
alloc *= 2;
buffer->json = (char *) realloc(buffer->json, alloc);
p = buffer->json + used;
end = buffer->json + alloc;
}
struct apiEntry *entry = &buffer->list[i];
struct aircraft *a = aircraftGet(entry->bin.hex);
if (!a) {
fprintf(stderr, "FATAL: apiGenerateJson: aircraft missing, this shouldn't happen.");
setExit(2);
entry->jsonOffset.offset = 0;
entry->jsonOffset.len = 0;
continue;
}
uint32_t hash;
hash = hexHash(entry->bin.hex, buffer);
entry->nextHex = buffer->hexHash[hash];
buffer->hexHash[hash] = entry;
if (strlen(entry->bin.registration) > 0) {
hash = regHash(entry->bin.registration, buffer);
entry->nextReg = buffer->regHash[hash];
buffer->regHash[hash] = entry;
}
if (strlen(entry->bin.callsign) > 0) {
hash = callsignHash(entry->bin.callsign, buffer);
entry->nextCallsign = buffer->callsignHash[hash];
buffer->callsignHash[hash] = entry;
}
//fprintf(stderr, "callsign: %8s hash: %u\n", entry->bin.callsign, hash);
char *start = p;
*p++ = '\n';
p = sprintAircraftObject(p, end, a, now, 0, NULL);
*p++ = ',';
entry->jsonOffset.offset = start - buffer->json;
entry->jsonOffset.len = p - start;
}
buffer->jsonLen = p - buffer->json;
if (p >= end) {
fprintf(stderr, "FATAL: buffer full apiAdd\n");
setExit(2);
}
}
static int apiUpdate() {
struct craftArray *ca = &Modes.aircraftActive;
// always clear and update the inactive apiBuffer
int flip = (atomic_load(&Modes.apiFlip[0]) + 1) % 2;
struct apiBuffer *buffer = &Modes.apiBuffer[flip];
// reset buffer lengths
buffer->len = 0;
buffer->len_flag = 0;
int acCount = ca->len;
if (buffer->alloc < acCount + 32) {
if (acCount > 100000) {
fprintf(stderr, "<3> this is strange, too many aircraft!\n");
}
buffer->alloc = acCount + 64;
sfree(buffer->list);
sfree(buffer->list_flag);
buffer->list = cmalloc(buffer->alloc * sizeof(struct apiEntry));
buffer->list_flag = cmalloc(buffer->alloc * sizeof(struct apiEntry));
if (!buffer->list || !buffer->list_flag) {
fprintf(stderr, "apiList alloc: out of memory!\n");
exit(1);
}
}
int reallocHash = 0;
while (buffer->hashBuckets < buffer->alloc) {
buffer->hashBits += 1;
buffer->hashBuckets = 1 << buffer->hashBits;
reallocHash = 1;
}
if (reallocHash) {
//fprintf(stderr, "-----> hashBuckets: %d\n", buffer->hashBuckets);
sfree(buffer->hexHash);
sfree(buffer->regHash);
sfree(buffer->callsignHash);
buffer->hexHash = cmalloc(buffer->hashBuckets * sizeof(struct apiEntry*));
buffer->regHash = cmalloc(buffer->hashBuckets * sizeof(struct apiEntry*));
buffer->callsignHash = cmalloc(buffer->hashBuckets * sizeof(struct apiEntry*));
}
// reset hashList to NULL
memset(buffer->hexHash, 0x0, buffer->hashBuckets * sizeof(struct apiEntry*));
memset(buffer->regHash, 0x0, buffer->hashBuckets * sizeof(struct apiEntry*));
memset(buffer->callsignHash, 0x0, buffer->hashBuckets * sizeof(struct apiEntry*));
// reset api list, just in case we don't set the entries completely due to oversight
memset(buffer->list, 0x0, buffer->alloc * sizeof(struct apiEntry));
memset(buffer->list_flag, 0x0, buffer->alloc * sizeof(struct apiEntry));
buffer->aircraftJsonCount = 0;
int64_t now = mstime();
ca_lock_read(ca);
for (int i = 0; i < ca->len; i++) {
struct aircraft *a = ca->list[i];
if (a == NULL)
continue;
int res = apiAdd(buffer, a, now);;
if (res == -1) {
fprintf(stderr, "transitory: skipping a couple of aircraft for api / json due to insufficient buffer\n");
break;
}
}
ca_unlock_read(ca);
// sort api lists
qsort(buffer->list, buffer->len, sizeof(struct apiEntry), compareLon);
apiGenerateJson(buffer, now);
for (int i = 0; i < buffer->len; i++) {
struct apiEntry entry = buffer->list[i];
if (entry.bin.dbFlags) {
// copy entry into flags list (only contains aircraft with at least one dbFlag set
buffer->list_flag[buffer->len_flag++] = entry;
}
}
// sort not needed as order is maintained copying from main list
buffer->list_pos_range = findLonRange(-180 * 1E6, 180 * 1E6, buffer->list, buffer->len);
buffer->list_flag_pos_range = findLonRange(-180 * 1E6, 180 * 1E6, buffer->list_flag, buffer->len_flag);
buffer->timestamp = now;
// doesn't matter which of the 2 buffers the api req will use they are both pretty current
for (int i = 0; i < Modes.apiThreadCount; i++) {
atomic_store(&Modes.apiFlip[i], flip);
}
pthread_cond_signal(&Threads.json.cond);
pthread_cond_signal(&Threads.globeJson.cond);
return buffer->len;
}
static int shutClose(int fd) {
if (shutdown(fd, SHUT_RDWR) < 0) { // Secondly, terminate the reliable delivery
if (errno != ENOTCONN && errno != EINVAL) { // SGI causes EINVAL
fprintf(stderr, "API: Shutdown client socket failed.\n");
}
}
return close(fd);
}
static void apiCloseCon(struct apiCon *con, struct apiThread *thread) {
if (!con->open) {
fprintf(stderr, "apiCloseCon double close!\n");
return;
}
int fd = con->fd;
if (con->events && epoll_ctl(thread->epfd, EPOLL_CTL_DEL, fd, NULL)) {
fprintf(stderr, "apiCloseCon: EPOLL_CTL_DEL %d: %s\n", fd, strerror(errno));
}
con->events = 0;
if (shutClose(fd) != 0) {
perror("apiCloseCon: close:");
}
if (Modes.debug_api) {
fprintf(stderr, "%d %d apiCloseCon()\n", thread->index, fd);
}
sfree(con->request.buffer);
con->request.len = 0;
con->request.alloc = 0;
struct char_buffer *reply = &con->reply;
thread->responseBytesBuffered -= reply->len;
sfree(reply->buffer);
reply->len = 0;
reply->alloc = 0;
con->open = 0;
thread->conCount--;
// put it back on the stack of free connection structs
thread->stack[thread->stackCount++] = con;
//fprintf(stderr, "%2d %5d\n", thread->index, thread->conCount);
}
static void apiResetCon(struct apiCon *con, struct apiThread *thread) {
if (!con->open) {
fprintf(stderr, "apiResetCon called on closed connection!\n");
return;
}
if (!con->keepalive) {
apiCloseCon(con, thread);
return;
}
if (Modes.debug_api) {
fprintf(stderr, "%d %d apiResetCon\n", thread->index, con->fd);
}
// not freeing request buffer, rather reusing it
con->request.len = 0;
con->bytesSent = 0;
struct char_buffer *reply = &con->reply;
thread->responseBytesBuffered -= reply->len;
// free reply buffer
sfree(reply->buffer);
reply->len = 0;
reply->alloc = 0;
con->lastReset = mstime();
}
static void sendStatus(int fd, int keepalive, const char *http_status) {
char buf[256];
char *p = buf;
char *end = buf + sizeof(buf);
p = safe_snprintf(p, end,
"HTTP/1.1 %s\r\n"
"Server: readsb/wiedehopf\r\n"
"Connection: %s\r\n"
"Cache-control: no-store\r\n"
"Content-length: 0\r\n\r\n",
http_status,
keepalive ? "keep-alive" : "close");
int res = send(fd, buf, strlen(buf), 0);
MODES_NOTUSED(res);
}
static void send200(int fd, int keepalive) {
sendStatus(fd, keepalive, "200 OK");
}
static void send400(int fd, int keepalive) {
sendStatus(fd, keepalive, "400 Bad Request");
}
static void send405(int fd, int keepalive) {
sendStatus(fd, keepalive, "405 Method Not Allowed");
}
static void send505(int fd, int keepalive) {
sendStatus(fd, keepalive, "505 HTTP Version Not Supported");
}
static void send503(int fd, int keepalive) {
sendStatus(fd, keepalive, "503 Service Unavailable");
}
static void send500(int fd, int keepalive) {
sendStatus(fd, keepalive, "500 Internal Server Error");
}
static int parseDoubles(char *start, char *end, double *results, int max) {
int count = 0;
char *sot;
char *eot = start - 1;
char *endptr = NULL;
//fprintf(stderr, "%s\n", start);
while ((sot = eot + 1) < end) {
eot = memchr(sot, ',', end - sot);
if (!eot) {
eot = end; // last token memchr returns NULL and eot is set to end
}
*eot = '\0';
results[count++] = strtod(sot, &endptr);
if (eot != endptr) {
return -1;
}
if (count > max) {
return -1;
}
}
return count;
}
// expects lower cased input
static struct char_buffer parseFetch(struct apiCon *con, struct char_buffer *request, struct apiOptions *options, struct apiThread *thread) {
struct char_buffer invalid = { 0 };
char *req = request->buffer;
// GET URL HTTPVERSION
char *query = memchr(req, '?', request->len);
if (!query) {
return invalid;
}
// skip URL to after ? which signifies start of query options
query++;
// find end of query
char *eoq = memchr(query, ' ', request->len);
if (!eoq) {
return invalid;
}
// we only want the URL
*eoq = '\0';
// set some option defaults:
options->above_alt_baro = INT32_MIN;
options->below_alt_baro = INT32_MAX;
options->request_received = microtime();
char *sot;
char *eot = query - 1;
while ((sot = eot + 1) < eoq) {
eot = memchr(sot, '&', eoq - sot);
if (!eot) {
eot = eoq; // last token memchr returns NULL and eot is set to eoq
}
*eot = '\0';
char *p = sot;
char *option = strsep(&p, "=");
char *value = p;
if (value) {
//fprintf(stderr, "%s=%s\n", option, value);
// handle parameters WITH associated value
if (byteMatchStrict(option, "box")) {
options->is_box = 1;
double *box = options->box;
int count = parseDoubles(value, eot, box, 4);
if (count < 4)
return invalid;
for (int i = 0; i < 4; i++) {
if (box[i] > 180 || box[i] < -180)
return invalid;
}
if (box[0] > box[1])
return invalid;
} else if (byteMatchStrict(option, "closest") || byteMatchStrict(option, "circle")) {
options->is_circle = 1;
if (byteMatchStrict(option, "closest")) {
options->closest = 1;
}
struct apiCircle *circle = &options->circle;
double numbers[3];
int count = parseDoubles(value, eot, numbers, 3);
if (count < 3)
return invalid;
circle->onlyClosest = options->closest;
circle->lat = numbers[0];
circle->lon = numbers[1];
// user input in nmi, internally we use meters
circle->radius = numbers[2] * 1852;
//fprintf(stderr, "%.1f, %.1f, %.1f\n", circle->lat, circle->lon, circle->radius);
if (circle->lat > 90 || circle->lat < -90)
return invalid;
if (circle->lon > 180 || circle->lon < -180)
return invalid;
} else if (byteMatchStrict(option, "find_hex") || byteMatchStrict(option, "hexlist")) {
options->is_hexList = 1;
int hexCount = 0;
int maxCount = API_REQ_LIST_MAX;
uint32_t *hexList = options->hexList;
char *saveptr = NULL;
char *endptr = NULL;
char *tok = strtok_r(value, ",", &saveptr);
while (tok && hexCount < maxCount) {
int other = 0;
if (tok[0] == '~') {
other = 1;
tok++; // skip over ~
}
uint32_t hex = (uint32_t) strtol(tok, &endptr, 16);
if (tok != endptr) {
hex |= (other ? MODES_NON_ICAO_ADDRESS : 0);
hexList[hexCount] = hex;
hexCount++;
//fprintf(stderr, "%06x\n", hex);
}
tok = strtok_r(NULL, ",", &saveptr);
}
options->hexCount = hexCount;
} else if (byteMatchStrict(option, "find_callsign")) {
options->is_callsignList = 1;
int callsignCount = 0;
int maxCount = API_REQ_LIST_MAX;
char *callsignList = options->callsignList;
char *saveptr = NULL;
char *endptr = NULL;
char *tok = strtok_r(value, ",", &saveptr);
while (tok && callsignCount < maxCount) {
strncpy(callsignList + callsignCount * 8, tok, 8);
if (tok != endptr)
callsignCount++;
tok = strtok_r(NULL, ",", &saveptr);
}
if (callsignCount == 0)
return invalid;
options->callsignCount = callsignCount;
} else if (byteMatchStrict(option, "find_reg")) {
options->is_regList = 1;
int regCount = 0;
int maxCount = API_REQ_LIST_MAX;
char *regList = options->regList;
char *saveptr = NULL;
char *endptr = NULL;
char *tok = strtok_r(value, ",", &saveptr);
int regLen = memberSize(struct binCraft, registration);
while (tok && regCount < maxCount) {
strncpy(regList + regCount * regLen, tok, regLen);
if (tok != endptr)
regCount++;
tok = strtok_r(NULL, ",", &saveptr);
}
if (regCount == 0)
return invalid;
options->regCount = regCount;
} else if (byteMatchStrict(option, "find_type") || byteMatchStrict(option, "filter_type")) {
if (byteMatchStrict(option, "find_type")) {
options->is_typeList = 1;
} else {
options->filter_typeList = 1;
}
int typeCount = 0;
int typeLen = memberSize(struct binCraft, typeCode);
int maxCount = API_REQ_LIST_MAX;
char *typeList = options->typeList;
char *saveptr = NULL;
char *endptr = NULL;
char *tok = strtok_r(value, ",", &saveptr);
while (tok && typeCount < maxCount) {
strncpy(typeList + typeCount * typeLen, tok, typeLen);
if (tok != endptr)
typeCount++;
tok = strtok_r(NULL, ",", &saveptr);
}
if (typeCount == 0)
return invalid;
options->typeCount = typeCount;
} else if (byteMatchStrict(option, "filter_callsign_exact")) {
options->filter_callsign_exact = 1;
memset(options->callsign_exact, 0x0, sizeof(options->callsign_exact));
strncpy(options->callsign_exact, value, memberSize(struct binCraft, callsign));
} else if (byteMatchStrict(option, "filter_callsign_prefix")) {
options->filter_callsign_prefix = 1;
memset(options->callsign_prefix, 0x0, sizeof(options->callsign_prefix));
strncpy(options->callsign_prefix, value, memberSize(struct binCraft, callsign));
} else if (byteMatchStrict(option, "above_alt_baro")) {
options->filter_alt_baro = 1;
options->above_alt_baro = strtol(value, NULL, 10);
} else if (byteMatchStrict(option, "below_alt_baro")) {
options->filter_alt_baro = 1;
options->below_alt_baro = strtol(value, NULL, 10);
} else if (byteMatchStrict(option, "filter_squawk")) {
options->filter_squawk = 1;
//int dec = strtol(value, NULL, 10);
//options->squawk = (dec / 1000) * 16*16*16 + (dec / 100 % 10) * 16*16 + (dec / 10 % 10) * 16 + (dec % 10);
int hex = strtol(value, NULL, 16);
//fprintf(stderr, "%04d %04x\n", dec, hex);
options->squawk = hex;
} else {
return invalid;
}
} else {
// handle parameters WITHOUT associated value
if (byteMatchStrict(option, "json")) {
// this is the default
} else if (byteMatchStrict(option, "jv2")) {
options->jamesv2 = 1;
} else if (byteMatchStrict(option, "zstd")) {
options->zstd = 1;
} else if (byteMatchStrict(option, "bincraft")) {
options->binCraft = 1;
} else if (byteMatchStrict(option, "all")) {
options->all = 1;
} else if (byteMatchStrict(option, "all_with_pos")) {
options->all_with_pos = 1;
} else if (byteMatchStrict(option, "filter_with_pos")) {
options->filter_with_pos = 1;
} else if (byteMatchStrict(option, "filter_mil")) {
options->filter_dbFlag = 1;
options->filter_mil = 1;
} else if (byteMatchStrict(option, "filter_interesting")) {
options->filter_dbFlag = 1;
options->filter_interesting = 1;
} else if (byteMatchStrict(option, "filter_pia")) {
options->filter_dbFlag = 1;
options->filter_pia = 1;
} else if (byteMatchStrict(option, "filter_ladd")) {
options->filter_dbFlag = 1;
options->filter_ladd = 1;
} else if (byteMatchStrict(option, "include_version")) {
con->include_version = 1;
} else {
return invalid;
}
}
}
int mainOptionCount = options->is_box
+ options->is_circle
+ options->is_hexList
+ options->is_callsignList
+ options->is_regList
+ options->is_typeList
+ options->all
+ options->all_with_pos;
if (mainOptionCount != 1) {
if (mainOptionCount == 2 && options->is_hexList && options->is_box) {
// this is ok
} else {
return invalid;
}
}
if (options->is_typeList && options->filter_typeList) {
return invalid;
}
//fprintf(stderr, "parseFetch calling apiReq\n");
if (options->zstd) {
// don't double zstd compress
options->zstd_encode = 0;
con->content_type = "application/zstd";
} else if (options->binCraft) {
con->content_type = "application/octet-stream";
} else {
con->content_type = "application/json";
}
return apiReq(thread, options);
}
static void apiSendData(struct apiCon *con, struct apiThread *thread) {
struct char_buffer *reply = &con->reply;
int toSend = reply->len - con->bytesSent;
if (toSend <= 0) {
if ((con->events & EPOLLOUT)) {
con->events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLHUP;
struct epoll_event epollEvent = { .events = con->events };
epollEvent.data.ptr = con;
if (epoll_ctl(thread->epfd, EPOLL_CTL_MOD, con->fd, &epollEvent)) {
perror("apiResetCon() epoll_ctl fail:");
}
}
if (toSend < 0) {
fprintf(stderr, "wat?! toSend < 0\n");
}
return;
}
char *dataStart = reply->buffer + con->bytesSent;
int nwritten = send(con->fd, dataStart, toSend, 0);
if (nwritten > 0) {
con->bytesSent += nwritten;
}
// all data has been sent, reset the connection
if (nwritten == toSend) {
apiResetCon(con, thread);
return;
}
if (nwritten < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
// no progress, make sure EPOLLOUT is set.
} else {
// non recoverable error, close connection
if (antiSpam(&thread->antiSpam[0], 5 * SECONDS)) {
fprintf(stderr, "apiSendData fail: %s (was trying to send %d bytes)\n", strerror(errno), toSend);
}
apiCloseCon(con, thread);
return;
}
}
//fprintf(stderr, "wrote only %d of %d\n", nwritten, toSend);
// couldn't write everything, set EPOLLOUT
if (!(con->events & EPOLLOUT)) {
con->events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLHUP | EPOLLOUT;
struct epoll_event epollEvent = { .events = con->events };
epollEvent.data.ptr = con;
if (epoll_ctl(thread->epfd, EPOLL_CTL_MOD, con->fd, &epollEvent)) {
perror("apiSendData() epoll_ctl fail:");
}
}
return;
}
static void apiShutdown(struct apiCon *con, struct apiThread *thread, int line, int err) {
if (con->bytesSent != con->reply.len) {
if (antiSpam(&thread->antiSpam[1], 5 * SECONDS)) {
fprintf(stderr, "Connection shutdown with incomplete or no reply sent."
" (reply.len: %d, bytesSent: %d, request.len: %d open: %d line: %d errno: %s)\n",
(int) con->reply.len,
(int) con->bytesSent,
(int) con->request.len,
con->open,
line,
err ? strerror(err) : "-");
}
}
apiCloseCon(con, thread);
}
static void apiReadRequest(struct apiCon *con, struct apiThread *thread) {
// delay processing requests until we have more memory
if (thread->responseBytesBuffered > 512 * 1024 * 1024) {
if (antiSpam(&thread->antiSpam[2], 5 * SECONDS)) {
fprintf(stderr, "Delaying request processing due to per thread memory limit: 512 MB\n");
}
return;
}
int nread, toRead;
int fd = con->fd;
struct char_buffer *request = &con->request;
int end_pad = 32;
size_t requestMax = 1024 + 13 * API_REQ_LIST_MAX + end_pad;
if (request->len > requestMax) {
send400(con->fd, con->keepalive);
apiResetCon(con, thread);
return;
}
if (!request->alloc) {
request->alloc = 2048;
request->buffer = realloc(request->buffer, request->alloc);
} else if (request->len + end_pad + 512 > request->alloc) {
request->alloc = requestMax;
request->buffer = realloc(request->buffer, request->alloc);
}
if (!request->buffer) {
fprintf(stderr, "FATAL: apiReadRequest request->buffer malloc fail\n");
setExit(2);
send503(con->fd, con->keepalive);
apiCloseCon(con, thread);
return;
}
toRead = (request->alloc - end_pad) - request->len;
nread = recv(fd, request->buffer + request->len, toRead, 0);
if (Modes.debug_api) {
fprintf(stderr, "%d %d nread %d\n", thread->index, con->fd, nread);
}
if (nread < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
return;
}
apiShutdown(con, thread, __LINE__, errno);
return;
}
if (nread == 0) {
apiShutdown(con, thread, __LINE__, 0);
return;
}
if (con->reply.buffer) {
int toSend = con->reply.len - con->bytesSent;
fprintf(stderr, "wat?! reply buffer but got new request data. toSend: %d\n", toSend);
apiCloseCon(con, thread);
return;
}
int oldlen = request->len;
if (nread > 0) {
request->len += nread;
// terminate string
request->buffer[request->len] = '\0';
}
int req_len = request->len;
char *req_start = request->buffer;
char *newline = memchr(req_start + oldlen, '\n', req_len);
if (!newline || !strstr(req_start + imax(0, oldlen - 4), "\r\n\r\n")) {
// request not complete
return;
}
thread->requestCount++;
char *eol = memchr(req_start, '\n', req_len) + 1; // we already know we have at least one newline
char *req_end = req_start + req_len;
char *protocol = eol - litLen("HTTP/1.x\r\n"); // points to H
if (protocol < req_start) {
send505(con->fd, con->keepalive);
apiResetCon(con, thread);
return;
}
struct apiOptions optionsBack = { 0 };
struct apiOptions *options = &optionsBack;
// set end padding to zeros for byteMatchStart and byteMatch (memcmp) use without regrets
memset(req_end, 0, end_pad);
int isGET = byteMatchStart(req_start, "GET");
char *http_minor_version = protocol + litLen("HTTP/1.");
if (!byteMatchStart(protocol, "HTTP/1.") || !((*http_minor_version == '0') || (*http_minor_version == '1'))) {
send505(con->fd, con->keepalive);
apiResetCon(con, thread);
return;
}
con->http_minor_version = (*http_minor_version == '1') ? 1 : 0;
// parseFetch expects lower cased input
// lower case entire request
// HTTP / GET checks are done above as they are case sensitive
_unroll_32
for (int k = 0; k < req_len; k++) {
req_start[k] = tolower(req_start[k]);
}
// header parsing
char *hl = eol;
con->keepalive = con->http_minor_version == 1 ? 1 : 0;
while (hl < req_end && (eol = memchr(hl, '\n', req_end - hl))) {
*eol = '\0';
if (byteMatchStart(hl, "accept-encoding")) {
if (strstr(hl, "zstd")) {
options->zstd_encode = 1;
}
}
if (byteMatchStart(hl, "connection")) {
if (strstr(hl, "close")) {
con->keepalive = 0;
} else if (con->keepalive || strstr(hl, "keep-alive")) {
con->keepalive = 1;
}
}
hl = eol + 1;
}
if (!isGET) {
send405(con->fd, con->keepalive);
apiResetCon(con, thread);
return;
}
//fprintf(stderr, "%s\n", request->buffer);
thread->request_len_sum += req_len;
thread->request_count++;
if (thread->request_count % (1000 * 1000) == 0) {
int64_t avg = thread->request_len_sum / thread->request_count;
thread->request_len_sum = 0;
thread->request_count = 0;
fprintf(stderr, "API average req_len: %d\n", (int) avg);
}
char *status = protocol - litLen("?status ");
if (status > req_start && byteMatchStart(status, "?status ")) {
if (Modes.exitSoon) {
send503(con->fd, con->keepalive);
} else {
send200(con->fd, con->keepalive);
}
apiResetCon(con, thread);
return;
}
con->content_type = "multipart/mixed";
struct char_buffer reply = parseFetch(con, request, options, thread);
if (reply.len == 0) {
//fprintf(stderr, "parseFetch returned invalid\n");
send400(con->fd, con->keepalive);
apiResetCon(con, thread);
return;
}
thread->responseBytesBuffered += reply.len;
// at header before payload
char header[API_REQ_PADSTART];
char *p = header;
char *end = header + API_REQ_PADSTART;
int content_len = reply.len - API_REQ_PADSTART;
p = safe_snprintf(p, end,
"HTTP/1.1 200 OK\r\n"
"Server: readsb/wiedehopf\r\n"
"%s"
"Content-Type: %s\r\n"
"Connection: %s\r\n"
"Cache-Control: no-store\r\n"
"%s"
"Content-Length: %d\r\n\r\n",
con->include_version ? "readsb_version: "MODES_READSB_VERSION"\r\n" : "",
con->content_type,
con->keepalive ? "keep-alive" : "close",
options->zstd_encode ? "Content-Encoding: zstd\r\n" : "",
content_len);
int hlen = p - header;
//fprintf(stderr, "hlen %d\n", hlen);
if (hlen >= API_REQ_PADSTART) {
fprintf(stderr, "API error: API_REQ_PADSTART insufficient\n");
send500(con->fd, con->keepalive);
apiResetCon(con, thread);
return;
}
// increase bytesSent counter so we don't transmit the empty buffer before the header
con->bytesSent = API_REQ_PADSTART - hlen;
// copy the header into the correct position immediately before the payload (which we already have)
memcpy(reply.buffer + con->bytesSent, header, hlen);
con->reply = reply;
apiSendData(con, thread);
}
static void acceptCon(struct apiCon *con, struct apiThread *thread) {
int listen_fd = con->fd;
struct sockaddr_storage storage;
struct sockaddr *saddr = (struct sockaddr *) &storage;
socklen_t slen = sizeof(storage);
// accept at most 16 connections per epoll_wait wakeup and thread
for (int j = 0; j < 16; j++) {
int fd = accept4(listen_fd, saddr, &slen, SOCK_NONBLOCK);
if (fd < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
break;
} else if (errno == EMFILE) {
if (antiSpam(&thread->antiSpam[5], 5 * SECONDS)) {
fprintf(stderr, "<3>Out of file descriptors accepting api clients, "
"exiting to make sure we don't remain in a broken state!\n");
}
setExit(2);
break;
} else {
if (antiSpam(&thread->antiSpam[6], 5 * SECONDS)) {
fprintf(stderr, "api acceptCon(): Error accepting new connection: errno: %d %s\n", errno, strerror(errno));
}
break;
}
}
// when starving for connections, close old connections
if (!thread->stackCount) {
int64_t now = mstime();
int64_t bounce_delay = 5 * SECONDS;
if (now > thread->next_bounce) {
thread->next_bounce = now + bounce_delay / 20;
if (antiSpam(&thread->antiSpam[3], 5 * SECONDS)) {
fprintf(stderr, "starving for connections, closing all connections idle for 5 or more seconds\n");
}
for (int j = 0; j < Modes.api_fds_per_thread; j++) {
struct apiCon *con = &thread->cons[j];
if (now - con->lastReset > bounce_delay) {
apiCloseCon(con, thread);
}
}
}
}
// reject new connection if we still don't have a free connection
if (!thread->stackCount) {
if (antiSpam(&thread->antiSpam[4], 5 * SECONDS)) {
fprintf(stderr, "too many concurrent connections, rejecting new connections, sendng 503s :/\n");
}
send503(fd, 0);
if (shutClose(fd) != 0) {
if (antiSpam(&thread->antiSpam[4], 5 * SECONDS)) {
perror("accept: shutClose failed when rejecting a new connection:");
}
}
return;
}
// take a free connection from the stack
struct apiCon *con = thread->stack[--thread->stackCount];
memset(con, 0, sizeof(struct apiCon));
thread->conCount++;
con->open = 1;
con->fd = fd;
con->lastReset = mstime();
if (Modes.debug_api) {
fprintf(stderr, "%d %d acceptCon()\n", thread->index, fd);
}
int op = EPOLL_CTL_ADD;
con->events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLHUP;
struct epoll_event epollEvent = { .events = con->events };
epollEvent.data.ptr = con;
if (epoll_ctl(thread->epfd, op, fd, &epollEvent)) {
perror("acceptCon() epoll_ctl fail:");
}
}
}
static void *apiThreadEntryPoint(void *arg) {
struct apiThread *thread = (struct apiThread *) arg;
srandom(get_seed());
int core = imax(0, Modes.num_procs - Modes.apiThreadCount + thread->index);
//fprintf(stderr, "%d\n", core);
threadAffinity(core);
// set this thread low priority
setLowestPriorityPthread();
thread->cons = cmalloc(Modes.api_fds_per_thread * sizeof(struct apiCon));
memset(thread->cons, 0x0, Modes.api_fds_per_thread * sizeof(struct apiCon));
thread->stack = cmalloc(Modes.api_fds_per_thread * sizeof(struct apiCon *));
for (int k = 0; k < Modes.api_fds_per_thread; k++) {
thread->stack[k] = &thread->cons[k];
thread->stackCount++;
}
thread->cctx = ZSTD_createCCtx();
thread->epfd = my_epoll_create(&Modes.exitNowEventfd);
for (int i = 0; i < Modes.apiService.listener_count; ++i) {
struct apiCon *con = Modes.apiListeners[i];
struct epoll_event epollEvent = { .events = con->events };
epollEvent.data.ptr = con;
if (epoll_ctl(thread->epfd, EPOLL_CTL_ADD, con->fd, &epollEvent)) {
perror("apiThreadEntryPoint() epoll_ctl fail:");
}
}
int count = 0;
struct epoll_event *events = NULL;
int maxEvents = 0;
struct timespec cpu_timer;
start_cpu_timing(&cpu_timer);
int64_t next_stats_sync = 0;
while (!Modes.exit) {
if (count == maxEvents) {
epollAllocEvents(&events, &maxEvents);
}
int64_t wait_ms = 5 * SECONDS;
#ifdef NO_EVENT_FD
wait_ms = imin(wait_ms, 100); // no event_fd, limit sleep to 100 ms
#endif
count = epoll_wait(thread->epfd, events, maxEvents, wait_ms);
int64_t now = mstime();
if (now > next_stats_sync) {
next_stats_sync = now + 1 * SECONDS;
struct timespec used = { 0 };
end_cpu_timing(&cpu_timer, &used);
int micro = (int) (used.tv_sec * 1000LL * 1000LL + used.tv_nsec / 1000LL);
atomic_fetch_add(&Modes.apiWorkerCpuMicro, micro);
start_cpu_timing(&cpu_timer);
//fprintf(stderr, "%2d %5d\n", thread->index, thread->conCount);
unsigned int requestCount = thread->requestCount;
atomic_fetch_add(&Modes.apiRequestCounter, requestCount);
thread->requestCount = 0;
}
for (int i = 0; i < count; i++) {
struct epoll_event event = events[i];
if (event.data.ptr == &Modes.exitNowEventfd)
continue;
struct apiCon *con = event.data.ptr;
if (con->accept && (event.events & EPOLLIN)) {
acceptCon(con, thread);
continue;
}
if (event.events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
if (con->open) {
apiReadRequest(con, thread);
} else {
apiShutdown(con, thread, __LINE__, 0);
}
continue;
}
if (con->open) {
if (event.events & EPOLLIN) {
apiReadRequest(con, thread);
}
if (event.events & EPOLLOUT) {
apiSendData(con, thread);
}
}
if (con->wakeups++ > 512 * 1024) {
if (antiSpam(&thread->antiSpam[7], 5 * SECONDS)) {
fprintf(stderr, "connection triggered too many events (bad webserver logic), send 500 :/ (EPOLLIN: %d, EPOLLOUT: %d) "
"(reply.len: %d, bytesSent: %d, request.len: %d open: %d)\n",
(event.events & EPOLLIN), (event.events & EPOLLOUT),
(int) con->reply.len,
(int) con->bytesSent,
(int) con->request.len,
con->open);
}
send500(con->fd, con->keepalive);
apiCloseCon(con, thread);
continue;
}
}
}
for (int j = 0; j < Modes.api_fds_per_thread; j++) {
struct apiCon *con = &thread->cons[j];
if (con->open) {
apiCloseCon(con, thread);
}
}
sfree(events);
ZSTD_freeCCtx(thread->cctx);
close(thread->epfd);
sfree(thread->stack);
sfree(thread->cons);
return NULL;
}
static void *apiUpdateEntryPoint(void *arg) {
MODES_NOTUSED(arg);
srandom(get_seed());
pthread_mutex_lock(&Threads.apiUpdate.mutex);
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
struct timespec cpu_timer;
while (!Modes.exit) {
struct timespec watch;
int debug = 0;
if (debug) {
fprintTimePrecise(stderr, mstime());
fprintf(stderr, " apiUpdate\n");
startWatch(&watch);
}
start_cpu_timing(&cpu_timer);
int ac_count = apiUpdate();
end_cpu_timing(&cpu_timer, &Modes.stats_current.api_update_cpu);
if (0 && debug) {
int64_t elapsed = stopWatch(&watch);
fprintTimePrecise(stderr, mstime());
fprintf(stderr, " apiUpdate took: %.3f s for %d aircraft!\n", elapsed / 1000.0, ac_count);
}
int64_t now = mstime();
int64_t ival = Modes.json_interval;
int64_t remaining = ival - (now % ival);
if (remaining < 5) {
remaining += ival;
}
int64_t waitStarted = now;
int64_t elapsed = 0;
do {
threadTimedWait(&Threads.apiUpdate, &ts, remaining - elapsed);
//fprintf(stderr, ".");
elapsed = mstime() - waitStarted;
} while (!Modes.exit && elapsed < remaining);
}
pthread_mutex_unlock(&Threads.apiUpdate.mutex);
return NULL;
}
void apiBufferInit() {
if (Modes.apiThreadCount <= 0) {
// if --devel=apiThreads, isn't given, use nproc - 1 api threads
// don't use more than 8 threads unless explicit count is given
Modes.apiThreadCount = imin(8, imax(1, Modes.num_procs - 1));
}
size_t size = sizeof(struct apiThread) * Modes.apiThreadCount;
Modes.apiThread = cmalloc(size);
memset(Modes.apiThread, 0x0, size);
size = sizeof(atomic_int) * Modes.apiThreadCount;
Modes.apiFlip = cmalloc(size);
memset(Modes.apiFlip, 0x0, size);
apiUpdate(); // run an initial apiUpdate
Modes.apiBufferInitDone++;
if (Modes.apiBufferInitDone != 1) {
fprintf(stderr, "FATAL: buffer init call fail %d\n", Modes.apiBufferInitDone);
setExit(2);
return;
}
threadCreate(&Threads.apiUpdate, NULL, apiUpdateEntryPoint, NULL);
}
void apiBufferCleanup() {
threadSignalJoin(&Threads.apiUpdate);
for (int i = 0; i < 2; i++) {
sfree(Modes.apiBuffer[i].list);
sfree(Modes.apiBuffer[i].list_flag);
sfree(Modes.apiBuffer[i].json);
sfree(Modes.apiBuffer[i].hexHash);
sfree(Modes.apiBuffer[i].regHash);
sfree(Modes.apiBuffer[i].callsignHash);
}
sfree(Modes.apiThread);
sfree(Modes.apiFlip);
}
void apiInit() {
if (Modes.apiBufferInitDone != 1) {
fprintf(stderr, "FATAL: buffer init call fail %d\n", Modes.apiBufferInitDone);
setExit(2);
return;
}
Modes.apiService.descr = "API output";
serviceListen(&Modes.apiService, Modes.net_bind_address, Modes.net_output_api_ports, -1);
fprintf(stderr, "\n");
if (Modes.apiService.listener_count <= 0) {
Modes.api = 0;
return;
}
Modes.apiListeners = cmalloc(sizeof(struct apiCon*) * Modes.apiService.listener_count);
memset(Modes.apiListeners, 0, sizeof(struct apiCon*) * Modes.apiService.listener_count);
for (int i = 0; i < Modes.apiService.listener_count; ++i) {
struct apiCon *con = cmalloc(sizeof(struct apiCon));
memset(con, 0, sizeof(struct apiCon));
if (!con) fprintf(stderr, "EMEM, how much is the fish?\n"), exit(1);
Modes.apiListeners[i] = con;
con->fd = Modes.apiService.listener_fds[i];
con->accept = 1;
#ifndef EPOLLEXCLUSIVE
#define EPOLLEXCLUSIVE (0)
#endif
con->events = EPOLLIN | EPOLLEXCLUSIVE;
}
Modes.api_fds_per_thread = imin(Modes.max_fds_api / Modes.apiThreadCount, Modes.apiThreadCount * 4096);
if (Modes.api_fds_per_thread < 1) {
Modes.api_fds_per_thread = 1;
fprintf(stderr, "WARNING: Setting Modes.api_fds_per_thread = 1 because it was %d\n", Modes.api_fds_per_thread);
}
//fprintf(stderr, "Modes.api_fds_per_thread: %d\n", Modes.api_fds_per_thread);
for (int i = 0; i < Modes.apiThreadCount; i++) {
Modes.apiThread[i].index = i;
pthread_create(&Modes.apiThread[i].thread, NULL, apiThreadEntryPoint, &Modes.apiThread[i]);
}
}
void apiCleanup() {
for (int i = 0; i < Modes.apiThreadCount; i++) {
pthread_join(Modes.apiThread[i].thread, NULL);
}
struct net_service *service = &Modes.apiService;
for (int i = 0; i < service->listener_count; ++i) {
sfree(Modes.apiListeners[i]);
}
sfree(Modes.apiListeners);
sfree(service->listener_fds);
if (service->unixSocket) {
unlink(service->unixSocket);
sfree(service->unixSocket);
}
}
struct char_buffer apiGenerateAircraftJson(threadpool_buffer_t *pbuffer) {
struct char_buffer cb = { 0 };
int flip = atomic_load(&Modes.apiFlip[0]);
struct apiBuffer *buffer = &Modes.apiBuffer[flip];
ssize_t alloc = buffer->jsonLen + 8 * 1024;
char *buf = check_grow_threadpool_buffer_t(pbuffer, alloc);
char *p = buf;
char *end = buf + alloc;
if (!buf) {
return cb;
}
p = safe_snprintf(p, end,
"{ \"now\" : %.3f,\n"
" \"messages\" : %u,\n",
buffer->timestamp / 1000.0,
Modes.stats_current.messages_total + Modes.stats_alltime.messages_total);
//fprintf(stderr, "%.3f\n", ((double) mstime() - (double) buffer->timestamp) / 1000.0);
p = safe_snprintf(p, end, " \"aircraft\" : [");
memcpy(p, buffer->json, buffer->jsonLen);
p += buffer->jsonLen;
// json objects in cache are terminated by a comma: \n{ .... },
if (*(p-1) == ',')
p--;
p = safe_snprintf(p, end, "\n ]\n}\n");
cb.len = p - buf;
cb.buffer = buf;
return cb;
}
struct char_buffer apiGenerateGlobeJson(int globe_index, threadpool_buffer_t *pbuffer) {
assert (globe_index <= GLOBE_MAX_INDEX);
struct char_buffer cb = { 0 };
int flip = atomic_load(&Modes.apiFlip[0]);
struct apiBuffer *buffer = &Modes.apiBuffer[flip];
ssize_t alloc = 16 * 1024 + buffer->jsonLen;
char *buf = check_grow_threadpool_buffer_t(pbuffer, alloc);
char *p = buf;
char *end = buf + alloc;
p = safe_snprintf(p, end,
"{ \"now\" : %.3f,\n"
" \"messages\" : %u,\n",
buffer->timestamp / 1000.0,
Modes.stats_current.messages_total + Modes.stats_alltime.messages_total);
p = safe_snprintf(p, end,
" \"global_ac_count_withpos\" : %d,\n",
Modes.globalStatsCount.readsb_aircraft_with_position
);
p = safe_snprintf(p, end, " \"globeIndex\" : %d, ", globe_index);
if (globe_index >= GLOBE_MIN_INDEX) {
int grid = GLOBE_INDEX_GRID;
int lat = ((globe_index - GLOBE_MIN_INDEX) / GLOBE_LAT_MULT) * grid - 90;
int lon = ((globe_index - GLOBE_MIN_INDEX) % GLOBE_LAT_MULT) * grid - 180;
p = safe_snprintf(p, end,
"\"south\" : %d, "
"\"west\" : %d, "
"\"north\" : %d, "
"\"east\" : %d,\n",
lat,
lon,
lat + grid,
lon + grid);
} else {
struct tile *tiles = Modes.json_globe_special_tiles;
struct tile tile = tiles[globe_index];
p = safe_snprintf(p, end,
"\"south\" : %d, "
"\"west\" : %d, "
"\"north\" : %d, "
"\"east\" : %d,\n",
tile.south,
tile.west,
tile.north,
tile.east);
}
p = safe_snprintf(p, end, " \"aircraft\" : [");
for (int j = 0; j < buffer->len; j++) {
struct apiEntry *entry = &buffer->list[j];
if (entry->globe_index != globe_index)
continue;
// check if we have enough space
if (p + entry->jsonOffset.len >= end) {
fprintf(stderr, "apiGenerateGlobeJson buffer overrun\n");
break;
}
memcpy(p, buffer->json + entry->jsonOffset.offset, entry->jsonOffset.len);
p += entry->jsonOffset.len;
}
// json objects in cache are terminated by a comma: \n{ .... },
if (*(p - 1) == ',')
p--;
p = safe_snprintf(p, end, "\n ]\n}\n");
cb.len = p - buf;
cb.buffer = buf;
return cb;
}
readsb-3.16/api.h 0000664 0000000 0000000 00000006252 15050573076 0013642 0 ustar 00root root 0000000 0000000 #ifndef API_H
#define API_H
#define API_REQ_PADSTART (2048)
#define API_REQ_LIST_MAX 1024
#define API_ZSTD_LVL (2)
struct apiCon {
int fd;
int accept;
struct char_buffer reply;
size_t bytesSent;
uint32_t events;
int open;
int wakeups;
int keepalive;
int http_minor_version;
int include_version;
struct char_buffer request;
int64_t lastReset; // milliseconds
char *content_type;
};
struct apiCircle {
double lat;
double lon;
double radius; // in meters
bool onlyClosest;
};
struct apiOptions {
int64_t request_received; // microseconds
int64_t request_processed; // microseconds
double box[4];
struct apiCircle circle;
int is_box;
int is_circle;
int is_hexList;
int is_callsignList;
int is_regList;
int is_typeList;
int include_no_position;
int filter_typeList;
int closest;
int all;
int all_with_pos;
int jamesv2;
int filter_squawk;
int binCraft;
int zstd;
int zstd_encode;
unsigned squawk;
int filter_dbFlag;
int filter_mil;
int filter_interesting;
int filter_pia;
int filter_ladd;
int filter_with_pos;
int filter_callsign_exact;
char callsign_exact[9];
int filter_callsign_prefix;
char callsign_prefix[9];
int32_t filter_alt_baro;
int32_t above_alt_baro;
int32_t below_alt_baro;
int hexCount;
uint32_t hexList[API_REQ_LIST_MAX];
int callsignCount;
char callsignList[API_REQ_LIST_MAX * memberSize(struct binCraft, callsign) + 1];
int regCount;
char regList[API_REQ_LIST_MAX * memberSize(struct binCraft, registration) + 1];
int typeCount;
char typeList[API_REQ_LIST_MAX * memberSize(struct binCraft, typeCode) + 1];
};
struct offset {
int32_t offset;
int32_t len;
};
struct apiEntry {
struct offset jsonOffset;
struct binCraft bin;
struct apiEntry *nextHex;
struct apiEntry *nextReg;
struct apiEntry *nextCallsign;
float distance;
float direction;
int32_t globe_index;
};
struct range {
int from; // inclusive
int to; // exclusive
};
struct apiBuffer {
int len;
int len_flag;
int alloc;
int jsonLen;
char *json;
struct apiEntry *list;
struct apiEntry *list_flag;
struct range list_pos_range;
struct range list_flag_pos_range;
int64_t timestamp;
int hashBuckets;
int hashBits;
struct apiEntry **hexHash;
struct apiEntry **regHash;
struct apiEntry **callsignHash;
uint32_t focus;
int aircraftJsonCount;
};
struct apiThread {
pthread_t thread;
int index;
int epfd;
int eventfd;
int responseBytesBuffered;
uint32_t requestCount;
int conCount;
int stackCount;
struct apiCon *cons;
struct apiCon **stack;
ZSTD_CCtx* cctx;
// for producing average request len numbers
int64_t request_len_sum;
int64_t request_count;
int64_t next_bounce;
int64_t antiSpam[16];
};
void apiBufferInit();
void apiBufferCleanup();
void apiInit();
void apiCleanup();
struct char_buffer apiGenerateAircraftJson(threadpool_buffer_t *pbuffer);
struct char_buffer apiGenerateGlobeJson(int globe_index, threadpool_buffer_t *pbuffer);
#endif
readsb-3.16/argp.c 0000664 0000000 0000000 00000013127 15050573076 0014014 0 ustar 00root root 0000000 0000000 /*
* file: argp.c
* description: minimal replacement for GNU Argp library
* Copyright 2011 Peter Desnoyers, Northeastern University
* Copyright 2022 Matthias Wirth
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
#include
#include
#include
#include
#include "argp.h"
char *cleanarg(char *s)
{
char *v = strrchr(s, '/');
return v ? v+1 : s;
}
void argp_help(struct argp_state *state)
{
printf("Usage: %s [OPTIONS...] %s\n%s\n\n",
state->name, state->argp->arg_doc, state->argp->prog_doc);
struct argp_option *opt;
for (opt = state->argp->options; opt->name != NULL || opt->doc != NULL; opt++) {
if (opt->flags == OPTION_HIDDEN)
continue;
if (opt->name == NULL) {
printf("\n%s\n", opt->doc); // help category names
} else {
char tmp[80], *p = tmp;
p += sprintf(tmp, "--%s", opt->name);
if (opt->arg)
sprintf(p, "=%s", opt->arg);
printf(" %-*s%s\n", state->maxlen + 8, tmp, opt->doc);
}
}
printf(" --%-*s%s\n", state->maxlen+6, "help", "Give this help list");
printf(" --%-*s%s\n", state->maxlen+6, "usage",
"Give a short usage message");
printf("\nCredits:\n%s\n", argp_program_credits);
printf("\nReport bugs to %s\n", argp_program_bug_address);
}
void argp_usage(struct argp_state *state)
{
char buf[64 * 1024], *p = buf, *col0 = buf;
p += sprintf(p, "Usage: %s", state->name);
int indent = p-buf;
struct argp_option *opt;
for (opt = state->argp->options; opt->name != NULL || opt->doc != NULL; opt++) {
if (opt->flags == OPTION_HIDDEN)
continue;
if (opt->name != NULL) {
p += sprintf(p, " [--%s%s%s]", opt->name, opt->arg ? "=":"",
opt->arg ? opt->arg : "");
if (p-col0 > (78-state->maxlen)) {
p += sprintf(p, "\n");
col0 = p;
p += sprintf(p, "%*s", indent, "");
}
}
}
sprintf(p, " %s\n", state->argp->arg_doc);
printf("%s", buf);
}
int argp_parse(struct argp *argp, int argc, char **argv, int flags, int tmp, void *input)
{
__VARNOTUSED(flags);
__VARNOTUSED(tmp);
int n_opts = 0;
struct argp_state state = {.name = cleanarg(argv[0]),
.input = input, .argp = argp};
state.arg_num = 0;
/* calculate max "--opt=var" length */
int max = 0;
struct argp_option *opt;
for (opt = argp->options; opt->name != NULL || opt->doc != NULL; opt++) {
if (opt->name != NULL) {
int m = strlen(opt->name) + (opt->arg ? 1+strlen(opt->arg) : 0);
max = (max < m) ? m : max;
}
n_opts++;
}
state.maxlen = max+2;
struct option *long_opts = calloc((n_opts+3) * sizeof(*long_opts), 1);
int argp_opt_index;
int long_count = 0;
for (opt = argp->options; opt->name != NULL || opt->doc != NULL; opt++) {
if (opt->name != NULL) {
//fprintf(stderr, "%d %s\n", opt->key, opt->name);
int has_arg = opt->arg != NULL;
long_opts[long_count].name = opt->name;
long_opts[long_count].has_arg = has_arg ? required_argument : no_argument;
long_opts[long_count].flag = &argp_opt_index;
long_opts[long_count].val = (opt - argp->options); // opt index
long_count++;
}
}
// deal with version / usage / help stuff
if (argc >= 2) {
if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0) {
fprintf(stderr, "%s\n", argp_program_version);
exit(argc == 2 ? 0 : 1);
}
if (strcmp(argv[1], "-?") == 0 || strcmp(argv[1], "--help") == 0) {
argp_help(&state);
exit(argc == 2 ? 0 : 1);
}
if (strcmp(argv[1], "--usage") == 0) {
argp_usage(&state);
exit(argc == 2 ? 0 : 1);
}
}
/* we only accept long arguments - return value is zero, and 'long_index'
* gives us the index into 'long_opts[]'
*/
int long_index;
int c;
optind = 1;
while (argp_opt_index = -1, (c = getopt_long(argc, argv, "", long_opts, &long_index)) != -1) {
if (c == '?') {
fprintf(stderr, "Try `%s --help' or `%s --usage' for more information.\n", argv[0], argv[0]);
return 1;
}
if (c != 0) {
fprintf(stderr, "argp.c: unexpected getopt_long return value: %d %c\n", c, c);
fprintf(stderr, "Try `%s --help' or `%s --usage' for more information.\n", argv[0], argv[0]);
return 1;
}
if (argp_opt_index == -1) {
fprintf(stderr, "argp.c: unexpected code path re3Oovei\n");
fprintf(stderr, "Try `%s --help' or `%s --usage' for more information.\n", argv[0], argv[0]);
return 1;
}
//int index = optind - 1;
//fprintf(stderr, "option %d: %s %s\n", index, argv[index], optarg);
int res = argp->parser(argp->options[argp_opt_index].key, optarg, &state);
if (res == ARGP_ERR_UNKNOWN) {
return 1;
}
}
while (optind < argc) {
int res = argp->parser(ARGP_KEY_ARG, argv[optind++], &state);
if (res == ARGP_ERR_UNKNOWN) {
return 1;
}
}
argp->parser(ARGP_KEY_END, NULL, &state);
free(long_opts);
return 0;
}
readsb-3.16/argp.h 0000664 0000000 0000000 00000003335 15050573076 0014021 0 ustar 00root root 0000000 0000000 /*
* file: argp.h
* description: minimal replacement for GNU Argp library
* Copyright 2011 Peter Desnoyers, Northeastern University
* Copyright 2022 Matthias Wirth
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
#ifndef __ARGP_H__
/* This only includes the features I've used in my programs to date;
* in particular, it totally ignores any sort of flag.
*/
#define __VARNOTUSED(V) ((void) V)
#ifndef __error_t_defined
typedef int error_t;
# define __error_t_defined
#endif
// just for compat, this flag is default for this version
#define ARGP_NO_EXIT (0)
struct argp_option {
char *name;
int key;
char *arg;
int flags;
char *doc;
int group; /* ignored */
};
struct argp_state {
void *input;
char *name;
struct argp *argp;
int maxlen;
int arg_num;
};
struct argp {
struct argp_option *options;
error_t (*parser)(int key, char *arg, struct argp_state *state);
const char *arg_doc;
const char *prog_doc;
void *unused1;
void *unused2;
void *unused3;
};
void argp_help(struct argp_state *state);
void argp_usage(struct argp_state *state);
char *cleanarg(char *s);
enum {ARGP_KEY_ARG, ARGP_KEY_END, ARGP_ERR_UNKNOWN, ARGP_IN_ORDER};
enum {OPTION_NONE, OPTION_DOC, OPTION_HIDDEN};
int argp_parse(struct argp *argp, int argc, char **argv, int flags, int tmp, void *input);
extern const char *argp_program_version;
extern const char *argp_program_credits;
extern const char *argp_program_bug_address;
#endif /* __ARGP_H__ */
readsb-3.16/attach_gdb.sh 0000775 0000000 0000000 00000000622 15050573076 0015332 0 ustar 00root root 0000000 0000000 #!/bin/bash
if [[ -d /opt/rh/devtoolset-9 ]]; then
source scl_source enable devtoolset-9
fi
while true; do
date -u
date
sleep 5 &
gdb --pid "$(pgrep -f readsb)" \
-ex 'handle SIGTERM nostop print pass' \
-ex 'handle SIGINT nostop print pass' \
-ex 'handle SIGCONT nostop print pass' \
-batch -ex continue -ex 'bt full'
wait
done >> gdb.log 2>&1
readsb-3.16/changelog 0000664 0000000 0000000 00000000344 15050573076 0014566 0 ustar 00root root 0000000 0000000 readsb (3.16) stable; urgency=medium
* debian: cleanup package build / service file
* debian: autogenerate manpage during build using help2man
-- Matthias Wirth Mon, 18 Aug 2025 09:00:00 +0000
readsb-3.16/checkapi.sh 0000775 0000000 0000000 00000023613 15050573076 0015026 0 ustar 00root root 0000000 0000000 #!/bin/bash
hexlist1000="4bb18f,8832b5,4d0106,704015,75010a,7582f5,8003b3,8a060e,885970,88530c,3c4581,7503fd,880841,8815b4,881057,880c44,8840f5,770588,a9733c,880453,880849,7503db,884202,880845,4bb188,750042,884347,885175,76d1c4,88434e,76cdb6,7503f0,4242ff,76cef7,76bcc8,750324,7502de,06a10e,750480,75046e,76cdac,750220,8a04a8,4bb154,4ba956,710063,750466,7504c4,7bd008,884207,702092,885961,750244,899000,76b869,7503ec,8a04f7,8a07c9,76cc6a,7504f7,ad9e66,880450,7504aa,06a102,78084a,86e7a2,8a08a1,76e4c6,76e4cc,781153,76e4c4,76e4cb,76e4ce,76e4cd,76b444,7817e1,86ef06,68220d,06a03d,7813ba,8a0227,8a04f5,7bd014,8a03b1,7c531c,7805d0,7802d4,780d13,780b87,780399,8a0551,8a07b7,888191,8a02d5,75020f,8a08a0,8a02e9,8a0813,88815a,886289,750107,8a0261,88811c,7503f3,76cdae,76cda4,888169,8a03c1,781418,8881c6,888185,8881a5,76cc64,88816b,7503b1,78137e,8a0661,8881ac,888096,888171,8a0605,88805e,888129,8880ac,750500,8a04ce,8880b4,88817c,88808a,8881be,8a0603,8a02a3,70e048,8880df,7bd023,76cd09,8881c3,8013d6,88817a,8880a5,8a0451,8880ed,888137,8a05d5,88816e,8881ba,8a0893,8a088a,88819a,750502,888179,76cc65,888173,888167,888095,8a0643,88815f,888133,88816c,888174,88813e,8880f3,76bd47,42486a,8a044e,899013,75020a,888051,8990da,7812bd,780a28,7504e8,8a0827,8a040a,8991b5,7504b5,8a0831,8991bd,8a0823,899020,780a5b,8a0515,78010e,750475,750485,8a08a7,781c50,78027d,78018f,7805fa,89647d,7819de,780e7f,8a03f3,750266,780ad5,4ba9f6,8a0455,781145,7805ec,780769,76b862,7818f2,76cc62,780cce,78058e,780d8e,7815f8,7504b1,75010b,781929,79a066,06a0e7,899039,a137df,780a2b,76d248,78088e,780df3,78124e,780625,abba93,789209,780294,4d2307,7808a1,76cc63,7c44b8,78100d,7807d3,7812c1,750065,71c275,3fe81e,8a08c7,7c2fe7,780a6c,75021c,7c3119,75025f,7c1758,7c1b0f,7c4c67,7c19a0,7c6ce8,7c49c5,7504e3,76cd0a,7c42ce,7c0742,7cf65a,7c7796,7c4f13,750264,8a08b1,76e729,750215,7c4530,780fd1,7c80fb,7c1c70,7c2bf5,780b60,8a0751,7c6d38,750069,7c2be9,888139,7c2bf6,7c3f19,780b5c,780c45,7c683d,7816f5,780671,7c009f,7c49fb,7c5343,7c1bee,780d75,780901,7c7a36,7c6f94,7c6c33,7c4d44,8a06ec,7c42d6,7c4cac,7c42e1,76cd14,780d99,7c2539,7c2bcf,780ede,7c6ca2,7813dc,7801ca,781015,abb6b5,780e87,780eec,7c6843,7c4708,7c4f0a,7c77fe,7c77fa,780595,7c6c25,89505b,7c42dc,7c44ae,7c42cc,781939,88809e,a7df59,78160e,780d03,78086e,780f6b,7c1ac1,a01f37,7c7799,7c7534,7c1761,7802f1,7805b1,7816c9,89913a,89900d,8991b7,7c7aee,781601,780ba1,7c66cd,781871,781c11,7808c0,7c2bea,7817a2,7814d3,a4cb6f,781097,a7f7fc,781649,861b47,780476,78155a,76d1c3,780b99,780a4a,78088d,79a077,780c69,75839f,781949,71bd54,7801bd,899081,7810fc,899144,79a067,7c4a01,780465,780742,04008d,76cd13,780d56,780a43,899093,7811d1,780b4e,78088c,78070b,89902b,7812d5,789253,7813b5,899040,75840b,7813ab,8990d0,79a071,781676,7583d1,7819d2,4bb18a,781464,06a1cc,758598,7805fe,4d214a,780b75,758325,758532,7583fa,780f9a,7585ab,8990cf,780f35,7811cf,8990ce,7c2e2e,7c1c6f,758475,78185c,78091e,781437,780f0a,7cf9e3,86226a,899053,780376,76cee9,89901d,89902a,758404,75841b,899149,7804af,888188,758303,7c1b2d,861b20,899130,75869f,75824e,7803ae,71bf41,78060c,781d6d,7814b5,780a87,7c1473,7580b3,781363,a34291,7816a1,7585cc,7585e3,8990e3,a57e87,896473,7801e3,75860e,758306,7803b1,781685,758616,780af4,7802ac,7802fe,758610,71c285,86eaf2,06a0af,780928,758304,7582e7,758322,71c364,7803cc,a967c9,8991bc,789241,7582b4,abed10,758531,7583a7,7583e7,7583ae,86d9ae,718a07,71be16,76cc6b,86796c,885177,71c255,7586ca,71bd85,71c042,71bd07,71c365,71c345,71bf35,7c6bbf,71c397,71c015,718a93,a874bf,71bd51,71c273,780a5e,71d707,71c311,71c384,71c234,71c339,71ba01,71bc21,8990b9,71c356,89907e,71c039,71c396,ae1209,71c018,780ac8,71c334,ae10e2,71c277,71bf16,780da0,ae6212,8414a9,86ef28,ae620c,ae6b9c,888153,86960c,71c095,ae6b9b,71bf22,86d906,780dfc,71c245,851bba,71c501,89805e,76cd72,841115,868038,71ce49,71c256,71bf89,71c043,861f22,841ebc,7806a2,872f5c,a290f3,8681b9,8462c4,868088,86e488,71c304,88819b,76cda8,8465c0,71c326,7c01e4,84b83e,86d629,c04599,845bde,86cf5a,84715c,7c01e2,86d215,ae116c,84c43e,86d2cc,8681ac,86e518,8467a0,a7e1c2,789252,86cf6f,780a6d,c8196a,78922f,868041,aa7d2b,850e36,86d68f,86e86e,780abd,71c250,ae4a79,846748,84bb0e,71c359,86cec5,76cd08,846844,86e7c4,7808a8,861ae1,8511ca,71c081,861e78,84b42f,851914,3c70ca,86cee7,84bb74,851826,86dd88,899100,84b79c,aba7d9,abe1eb,7c806c,850df2,851936,841538,780963,8681b0,84bac2,84b982,a07bb3,86d61c,899137,86d602,841894,71c274,845c3b,85c5dc,84cb66,86d330,86ced2,861fa4,8417d6,8681ab,863766,841ae0,7812a1,841500,85d098,8681b6,86da16,84c214,846d80,846822,841bd1,846bfa,8463b4,424407,abc96f,86ddaa,87cc08,8515c4,7c668c,872968,841e74,84b772,868042,845d1c,84b7d8,8964c3,8518ae,86e02e,a7006f,7c5b4a,84c29c,85c55a,75827c,86eee4,87cd05,84659e,846954,851cca,7c810d,845f30,7c6d2a,84b860,7c6d90,86d943,86d607,7cf9cc,861ede,86e13e,8991c0,84657c,7c81de,86cf4d,847c18,872863,ae29cf,842250,ae5dfe,846adc,ae5dfd,ae1531,84183c,86e8ac,86cf91,861eb4,8674f0,8514f8,8510f6,86cea3,84cefa,850e7a,850d8c,84612d,8681b1,867d00,84bd16,862dd8,781ae9,850dae,634323,851c86,899125,868094,84c27a,c82337,86d98e,a65092,86d594,84c5ec,862d50,861f3c,846978,868ee4,86eea0,86e79a,86d668,85e27c,06a1bc,71c382,780a1d,7c8069,861e4e,86808a,84116c,84b940,a18cbb,a954ca,c0173f,845f5a,781941,86dd6e,846910,7c77f8,85cd04,86ce8e,7c0c9a,8470a0,84b5ac,8463b5,c82258,899124,846d0c,7c8068,aac2e2,1506c1,8991ac,7c7bce,8462ee,8694fa,7c627b,7c6bb8,86951c,4d233a,4b1a02,7c4e6b,4d2089,841e00,8682fc,7c6695,ae638d,750255,867fac,7c531f,867fce,781094,7c1c23,7c2baf,7c7c77,a4c34c,06a1ea,7c6dbb,7cf359,7c7a3f,7c77f9,7cf6cb,7cf353,7c7ccc,7c7ab5,800740,7c4ef5,7c6dea,7c6c92,7c07ad,7c2fe1,7c6685,7c7c16,77058c,7c6ca0,7c4878,8695c6,7c6d7f,7c6de5,7c77fc,7c16f1,7c1662,7c5342,7c5348,7c39f1,7c451d,7c6b36,7c335c,7c6d2f,7c6c52,7c6273,7c423e,7c7ab6,86d682,7c4515,7c4512,7c7caf,7c809a,86d930,7c4513,7c4518,7c7bcc,7c7621,7c29d4,7c6deb,7c7a38,7c6b0b,780da8,7c6d9e,7c7ab8,a31a57,750256,7c6d39,a21633,7c5e46,7c6319,76cd0c,7c7aa1,7c7ab2,7c530b,7c801e,7c6ded,4d0104,7c7a45,7c4487,7c5b4c,7c68a5,7c6ddd,7c498f,7c3316,7c29d8,7c5d71,7c5300,7c585f,7c7c9c,7c77fd,7c6d2e,7c3b3e,7cf8ed,a81f7b,7c6d9b,7c7bd6,7c1fbd,7c2590,7c0bda,7c5310,7c7f01,aa7468,7c6d30,7cf7cc,7cfa0d,abd6c6,7c3559,aa7f8d,7c47ce,780b7d,7c16de,7c6691,7c4d14,76bd48,7c43d9,7c6de4,867f68,7c6d24,7c6276,7c6d2b,7c1469,896209,899097,7c6d8c,ac0d21,7c5323,7c52fa,7c81e0,7c6b40,7c7a3e,7c6b18,7cf481,7cf4fd,7c5304,7c0012,7c7a47,7c7bc7,7cf43a,7cf4cf,7c617c,7cf4e7,7c495b,7cf7ca,7cf7cb,7c6c9b,71bd78,7c530e,7c6b3b,89916b,7c6ba1,7c6de8,7c7c98,7c01c2,7c77f6,7c6aec,7c5309,7c6182,7c6c55,7c6d32,7c39fc,7c7ab3,7c67b5,7c7aa9,7c6b30,7c7ab9,7c7800,7c6b12,7c1c4c,7c6b2f,7c8021,7c39fb,7c4877,7c52f8,7c6ca6,7c6699,76cd05,7c595c,7c4519,7c5307,7c0002,7c6d27,7c7599,7c6782,7c6ad3,7c083c,7c24be,7c6acc,7c1475,7c2e34,7c6d94,7c2ba8,7c7a48,7c6d8f,7c6a8d,7c4dcc,899134,7c6d7b,7c6c99,7c6db6,899121,7c7701,7cf864,a4c02d,71c076,780561,7cf831,7c1505,868db5,76cd42,7c1795,ac4d43,71ba08,86d624,76cd45,ac10d8,c87ed7,868078,71ba03,7580d5,76cee7,c87ed5,86e474,781346,c820cf,c822e9,c8222f,c87f31,86e778,7c6c95,c87ee1,c87e0c,c827e3,c87e61,c87ee2,8990ec,c81861,c81ce7,c81ce9,781009"
hexlist200="4BB566,8832b5,4d0106,704015,75010a,7582f5,8003b3,8a060e,885970,88530c,3c4581,7503fd,880841,8815b4,881057,880c44,8840f5,770588,a9733c,880453,880849,7503db,884202,880845,4bb188,750042,884347,885175,76d1c4,88434e,76cdb6,7503f0,4242ff,76cef7,76bcc8,750324,7502de,06a10e,750480,75046e,76cdac,750220,8a04a8,4bb154,4ba956,710063,750466,7504c4,7bd008,884207,702092,885961,750244,899000,76b869,7503ec,8a04f7,8a07c9,76cc6a,7504f7,ad9e66,880450,7504aa,06a102,78084a,86e7a2,8a08a1,76e4c6,76e4cc,781153,76e4c4,76e4cb,76e4ce,76e4cd,76b444,7817e1,86ef06,68220d,06a03d,7813ba,8a0227,8a04f5,7bd014,8a03b1,7c531c,7805d0,7802d4,780d13,780b87,780399,8a0551,8a07b7,888191,8a02d5,75020f,8a08a0,8a02e9,8a0813,88815a,886289,750107,8a0261,88811c,7503f3,76cdae,76cda4,888169,8a03c1,781418,8881c6,888185,8881a5,76cc64,88816b,7503b1,78137e,8a0661,8881ac,888096,888171,8a0605,88805e,888129,8880ac,750500,8a04ce,8880b4,88817c,88808a,8881be,8a0603,8a02a3,70e048,8880df,7bd023,76cd09,8881c3,8013d6,88817a,8880a5,8a0451,8880ed,888137,8a05d5,88816e,8881ba,8a0893,8a088a,88819a,750502,888179,76cc65,888173,888167,888095,8a0643,88815f,888133,88816c,888174,88813e,8880f3,76bd47,42486a,8a044e,899013,75020a,888051,8990da,7812bd,780a28,7504e8,8a0827,8a040a,8991b5,7504b5,8a0831,8991bd,8a0823,899020,780a5b,8a0515,78010e,750475,750485,8a08a7,781c50,78027d,78018f,7805fa,89647d,7819de,780e7f,8a03f3,750266,780ad5,4ba9f6,8a0455,781145,7805ec"
function curltime() {
request="$1"
curl -sS --compressed "$request" \
-w 'code: %{response_code}\tresolve: %{time_namelookup}\tfirst_byte: %{time_starttransfer}\ttotal: %{time_total}\n' \
-o /dev/null
}
function get() {
request="$1"
curl -sS --compressed "$request"
}
set -e
queries=()
queries+=("?hexlist=${hexlist200}&jv2")
queries+=("?circle=33,-118,300&jv2")
queries+=("?closest=33,-118,300&jv2")
queries+=("?box=50,60,-5,5&jv2")
queries+=("?all_with_pos&jv2")
queries+=("?all&jv2")
queries+=("?all&filter_callsign_exact=DLH7Le&jv2")
queries+=("?all&filter_callsign_prefix=DLH&jv2")
queries+=("?all_with_pos&filter_mil&jv2")
queries+=("?all_with_pos&filter_ladd&jv2")
queries+=("?all_with_pos&filter_squawk=1000&jv2")
queries+=("/re-api/")
queries+=("?box=50,60,-5,5")
#queries=()
queries+=("?all")
queries+=("?all_with_pos")
queries+=("?all&filter_with_pos")
queries+=("?hexlist=4853D4,498421")
queries+=("?find_callsign=N126CM,CEF05N")
queries+=("?find_reg=TC-RBJ,PH-HXK")
queries+=("?find_type=a320,b788")
queries+=("?box=10,80,-5,20&filter_type=a320,b788")
queries+=("?box=10,80,-5,20")
queries+=("?box=10,80,-5,20&find_hex=4BB267")
queries+=("?box=10,80,-5,20&above_alt_baro=30000&below_alt_baro=35000")
testhost() {
host=$1
for query in "${queries[@]}"; do
request="${host}${query}"
echo -e -n "checking: ${query:0:30}\t"
get "$request" | jq | tail -n4 | grep -e resultCount -e total -e ptime | tr '\n' '\t'
curltime "$request"
done
}
hosts=(\
"http://127.0.0.1:30152/" \
)
for host in "${hosts[@]}"; do
echo "testing host: $host"
testhost "$host" | column -t
echo
done
readsb-3.16/comm_b.c 0000664 0000000 0000000 00000060740 15050573076 0014322 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// comm_b.c: Comm-B message decoding
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2017 FlightAware, LLC
// Copyright (c) 2017 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#include "readsb.h"
#include "ais_charset.h"
typedef int (*CommBDecoderFn)(struct modesMessage *, bool);
static int decodeEmptyResponse(struct modesMessage *mm, bool store);
static int decodeBDS10(struct modesMessage *mm, bool store);
static int decodeBDS17(struct modesMessage *mm, bool store);
static int decodeBDS20(struct modesMessage *mm, bool store);
static int decodeBDS30(struct modesMessage *mm, bool store);
static int decodeBDS40(struct modesMessage *mm, bool store);
static int decodeBDS50(struct modesMessage *mm, bool store);
static int decodeBDS60(struct modesMessage *mm, bool store);
static int decodeBDS44(struct modesMessage *mm, bool store);
static CommBDecoderFn comm_b_decoders[] = {
&decodeEmptyResponse,
&decodeBDS10,
&decodeBDS20,
&decodeBDS30,
&decodeBDS17,
&decodeBDS40,
&decodeBDS50,
&decodeBDS60,
&decodeBDS44
};
void decodeCommB(struct modesMessage *mm) {
mm->commb_format = COMMB_UNKNOWN;
// If DR or UM are set, this message is _probably_ noise
// as nothing really seems to use the multisite broadcast stuff?
// Also skip anything that had errors corrected
if (mm->DR != 0 || mm->UM != 0 || mm->correctedbits > 0) {
return;
}
// This is a bit hairy as we don't know what the requested register was
int bestScore = 0;
CommBDecoderFn bestDecoder = NULL;
int ambiguous = 0;
for (unsigned i = 0; i < (sizeof (comm_b_decoders) / sizeof (comm_b_decoders[0])); ++i) {
int score = comm_b_decoders[i](mm, false);
if (score > bestScore) {
bestScore = score;
bestDecoder = comm_b_decoders[i];
ambiguous = 0;
} else if (score == bestScore) {
ambiguous = 1;
}
}
if (bestDecoder) {
if (ambiguous) {
mm->commb_format = COMMB_AMBIGUOUS;
} else {
// decode it
bestDecoder(mm, true);
}
}
}
static int decodeEmptyResponse(struct modesMessage *mm, bool store) {
for (unsigned i = 0; i < 7; ++i) {
if (mm->MB[i] != 0) {
return 0;
}
}
if (store) {
mm->commb_format = COMMB_EMPTY_RESPONSE;
}
return 56;
}
// BDS1,0 Datalink capabilities
static int decodeBDS10(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
// BDS identifier
if (msg[0] != 0x10) {
return 0;
}
// Reserved bits
if (getbits(msg, 10, 14) != 0) {
return 0;
}
// Looks plausible.
if (store) {
mm->commb_format = COMMB_DATALINK_CAPS;
}
return 56;
}
// BDS1,7 Common usage GICB capability report
static int decodeBDS17(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
// reserved bits
if (getbits(msg, 25, 56) != 0) {
return 0;
}
int score = 0;
if (getbit(msg, 7)) {
score += 1; // 2,0 aircraft identification
} else {
// BDS2,0 is on almost everything
score -= 2;
}
// unlikely bits
if (getbit(msg, 10)) { // 4,1 next waypoint identifier
score -= 2;
}
if (getbit(msg, 11)) { // 4,2 next waypoint position
score -= 2;
}
if (getbit(msg, 12)) { // 4,3 next waypoint information
score -= 2;
}
if (getbit(msg, 13)) { // 4,4 meterological routine report
score -= 2;
}
if (getbit(msg, 14)) { // 4,4 meterological hazard report
score -= 2;
}
if (getbit(msg, 20)) { // 5,4 waypoint 1
score -= 2;
}
if (getbit(msg, 21)) { // 5,5 waypoint 2
score -= 2;
}
if (getbit(msg, 22)) { // 5,6 waypoint 3
score -= 2;
}
if (getbit(msg, 1) && getbit(msg, 2) && getbit(msg, 3) && getbit(msg, 4) && getbit(msg, 5)) {
// looks like ES capable
score += 5;
if (getbit(msg, 6)) {
// ES EDI
score += 1;
}
} else if (!getbit(msg, 1) && !getbit(msg, 2) && !getbit(msg, 3) && !getbit(msg, 4) && !getbit(msg, 5) && !getbit(msg, 6)) {
// not ES capable
score += 1;
} else {
// partial ES support, unlikely
score -= 12;
}
if (getbit(msg, 16) && getbit(msg, 24)) {
// track/turn, heading/speed
score += 2;
if (getbit(msg, 9)) {
// vertical intent
score += 1;
}
} else if (!getbit(msg, 16) && !getbit(msg, 24) && !getbit(msg, 9)) {
// neither
score += 1;
} else {
// unlikely
score -= 6;
}
if (store) {
mm->commb_format = COMMB_GICB_CAPS;
}
return score;
}
// BDS2,0 Aircraft identification
static int decodeBDS20(struct modesMessage *mm, bool store) {
char callsign[sizeof(mm->callsign)];
unsigned char *msg = mm->MB;
// BDS identifier
if (msg[0] != 0x20) {
return 0;
}
callsign[0] = ais_charset[getbits(msg, 9, 14)];
callsign[1] = ais_charset[getbits(msg, 15, 20)];
callsign[2] = ais_charset[getbits(msg, 21, 26)];
callsign[3] = ais_charset[getbits(msg, 27, 32)];
callsign[4] = ais_charset[getbits(msg, 33, 38)];
callsign[5] = ais_charset[getbits(msg, 39, 44)];
callsign[6] = ais_charset[getbits(msg, 45, 50)];
callsign[7] = ais_charset[getbits(msg, 51, 56)];
callsign[8] = 0;
// score based on number of valid characters
int score = 8;
int valid = 1;
for (int i = 0; i < 8; ++i) {
if (
(callsign[i] >= 'A' && callsign[i] <= 'Z')
// -./0123456789
|| (callsign[i] >= '-' && callsign[i] <= '9')
|| callsign[i] == ' '
|| callsign[i] == '@'
) {
// valid chars
score += 6;
} else {
// Invalid
if (Modes.debug_callsign) {
fprintf(stderr, "%06x %8s (len: %d)\n", mm->addr, callsign, (int) strlen(callsign));
}
return 0;
}
}
if (store) {
mm->commb_format = COMMB_AIRCRAFT_IDENT;
if (valid) {
memcpy(mm->callsign, callsign, sizeof(mm->callsign));
mm->callsign_valid = 1;
}
}
return score;
}
// check if the payload is a valid ACAS payload
// https://mode-s.org/decode/book-the_1090mhz_riddle-junzi_sun.pdf
int checkAcasRaValid(unsigned char *msg, struct modesMessage *mm, int debug) {
bool ara = getbit(msg, 9);
bool rat = getbit(msg, 27);
bool mte = getbit(msg, 28);
// not a valid RA if none of the bits are set
if (!ara && !rat && !mte)
return 0;
if (getbits(msg, 9, 28) == 0)
return 0; // these are the bits that contain the info, all zero it's not an RA
if (getbit(msg, 23) && getbit(msg, 24))
return 0; // complementary bits, both set is invalid (above / below)
if (getbit(msg, 25) && getbit(msg, 26))
return 0; // complementary bits, both set is invalid (left / right)
if (mm->msgtype == 16) {
if (getbits(msg, 29, 56) != 0)
return 0; // in DF16 messages msg bits 29 to 56 are reserved
return 1;
}
// some extra restrictions for DF != 16 below
if (getbit(msg, 25) || getbit(msg, 26))
return 0; // left / right isn't used, require zero
// for COMMB messages let's check if the thread indicator makes sense
int tti = getbits(msg, 29, 30);
// thread type indicator
// 00 No identity data in threat identity data
if (tti == 0) {
if (getbits(msg, 31, 56) != 0)
return 0;
return 1;
}
// When the threat type indicator is 01 , MB bits 31-54 contain the 24-bit Mode S transponder address and the last two bits are set to zero.
if (tti == 1) {
if (getbits(msg, 55, 56) != 0)
return 0;
uint32_t addr = getbits(msg, 31, 54);
if (icaoFilterTest(addr))
return 1;
return debug; // zero unless debug
}
// 10 Threat identity data contains altitude, range, and bearing
if (tti == 2) {
if (mm->metype == 28)// allow for DF17
return 1;
// hard to tell if used and separate from garbage, don't mark valid for the moment
return debug; // zero unless debug
}
// 11 Not assigned
if (tti == 3) {
return 0;
}
return 0;
}
// BDS3,0 ACAS RA
static int decodeBDS30(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
// BDS identifier
if (msg[0] != 0x30) {
return 0;
}
if (store) {
mm->commb_format = COMMB_ACAS_RA;
mm->acas_ra_valid = 1;
}
// just accept it.
return 56;
}
// BDS4,0 Selected vertical intention
static int decodeBDS40(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
unsigned mcp_valid = getbit(msg, 1);
unsigned mcp_raw = getbits(msg, 2, 13);
unsigned fms_valid = getbit(msg, 14);
unsigned fms_raw = getbits(msg, 15, 26);
unsigned baro_valid = getbit(msg, 27);
unsigned baro_raw = getbits(msg, 28, 39);
unsigned reserved_1 = getbits(msg, 40, 47);
unsigned mode_valid = getbit(msg, 48);
unsigned mode_raw = getbits(msg, 49, 51);
unsigned reserved_2 = getbits(msg, 52, 53);
unsigned source_valid = getbit(msg, 54);
unsigned source_raw = getbits(msg, 55, 56);
if (!mcp_valid && !fms_valid && !baro_valid && !mode_valid && !source_valid) {
return 0;
}
int score = 0;
unsigned mcp_alt = 0;
if (mcp_valid && mcp_raw != 0) {
mcp_alt = mcp_raw * 16;
if (mcp_alt >= 1000 && mcp_alt <= 50000) {
score += 13;
} else {
// unlikely altitude
return 0;
}
} else if (!mcp_valid && mcp_raw == 0) {
score += 1;
} else {
return 0;
}
unsigned fms_alt = 0;
if (fms_valid && fms_raw != 0) {
fms_alt = fms_raw * 16;
if (fms_alt >= 1000 && fms_alt <= 50000) {
score += 13;
} else {
// unlikely altitude
return 0;
}
} else if (!fms_valid && fms_raw == 0) {
score += 1;
} else {
return 0;
}
float baro_setting = 0;
if (baro_valid && baro_raw != 0) {
baro_setting = 800 + baro_raw * 0.1;
if (baro_setting >= 900 && baro_setting <= 1100) {
score += 13;
} else {
// unlikely pressure setting
return 0;
}
} else if (!baro_valid && baro_raw == 0) {
score += 1;
} else {
return 0;
}
if (reserved_1 != 0) {
return 0;
}
if (mode_valid) {
score += 4;
} else if (!mode_valid && mode_raw == 0) {
score += 1;
} else {
return 0;
}
if (reserved_2 != 0) {
return 0;
}
if (source_valid) {
score += 3;
} else if (!source_valid && source_raw == 0) {
score += 1;
} else {
return 0;
}
// small penalty for inconsistent data
if (mcp_valid && fms_valid && mcp_alt != fms_alt) {
score -= 4;
}
if (mcp_valid) {
unsigned remainder = mcp_alt % 500;
if (!(remainder < 16 || remainder > 484)) {
// mcp altitude is not a multiple of 500
score -= 4;
}
}
if (fms_valid) {
unsigned remainder = fms_alt % 500;
if (!(remainder < 16 || remainder > 484)) {
// fms altitude is not a multiple of 500
score -= 4;
}
}
if (store) {
mm->commb_format = COMMB_VERTICAL_INTENT;
if (mcp_valid) {
mm->nav.mcp_altitude_valid = 1;
mm->nav.mcp_altitude = mcp_alt;
}
if (fms_valid) {
mm->nav.fms_altitude_valid = 1;
mm->nav.fms_altitude = fms_alt;
}
if (baro_valid) {
mm->nav.qnh_valid = 1;
mm->nav.qnh = baro_setting;
}
if (mode_valid) {
mm->nav.modes_valid = 1;
mm->nav.modes =
((mode_raw & 4) ? NAV_MODE_VNAV : 0) |
((mode_raw & 2) ? NAV_MODE_ALT_HOLD : 0) |
((mode_raw & 1) ? NAV_MODE_APPROACH : 0);
}
if (source_valid) {
switch (source_raw) {
case 0:
mm->nav.altitude_source = NAV_ALT_UNKNOWN;
break;
case 1:
mm->nav.altitude_source = NAV_ALT_AIRCRAFT;
break;
case 2:
mm->nav.altitude_source = NAV_ALT_MCP;
break;
case 3:
mm->nav.altitude_source = NAV_ALT_FMS;
break;
default:
mm->nav.altitude_source = NAV_ALT_INVALID;
break;
}
} else {
mm->nav.altitude_source = NAV_ALT_INVALID;
}
}
return score;
}
// BDS5,0 Track and turn report
static int decodeBDS50(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
unsigned roll_valid = getbit(msg, 1);
unsigned roll_sign = getbit(msg, 2);
unsigned roll_raw = getbits(msg, 3, 11);
unsigned track_valid = getbit(msg, 12);
unsigned track_sign = getbit(msg, 13);
unsigned track_raw = getbits(msg, 14, 23);
unsigned gs_valid = getbit(msg, 24);
unsigned gs_raw = getbits(msg, 25, 34);
unsigned track_rate_valid = getbit(msg, 35);
unsigned track_rate_sign = getbit(msg, 36);
unsigned track_rate_raw = getbits(msg, 37, 45);
unsigned tas_valid = getbit(msg, 46);
unsigned tas_raw = getbits(msg, 47, 56);
if (!roll_valid || !track_valid || !gs_valid || !tas_valid) {
return 0;
}
int score = 0;
float roll = 0;
if (roll_valid) {
roll = roll_raw * 45.0 / 256.0;
if (roll_sign) {
roll -= 90.0;
}
if (roll >= -40 && roll < 40) {
score += 11;
} else {
return 0;
}
} else if (!roll_valid && roll_raw == 0 && !roll_sign) {
score += 1;
} else {
return 0;
}
float track = 0;
if (track_valid) {
score += 12;
track = track_raw * 90.0 / 512.0;
if (track_sign) {
track += 180.0;
}
} else if (!track_valid && track_raw == 0 && !track_sign) {
score += 1;
} else {
return 0;
}
unsigned gs = 0;
if (gs_valid && gs_raw != 0) {
gs = gs_raw * 2;
if (gs >= 50 && gs <= 700) {
score += 11;
} else {
return 0;
}
} else if (!gs_valid && gs_raw == 0) {
score += 1;
} else {
return 0;
}
float track_rate = 0;
if (track_rate_valid) {
track_rate = track_rate_raw * 8.0 / 256.0;
if (track_rate_sign) {
track_rate -= 16;
}
if (track_rate >= -10.0 && track_rate <= 10.0) {
score += 11;
} else {
return 0;
}
} else if (!track_rate_valid && track_rate_raw == 0 && !track_rate_sign) {
score += 1;
} else {
return 0;
}
unsigned tas = 0;
if (tas_valid && tas_raw != 0) {
tas = tas_raw * 2;
if (tas >= 50 && tas <= 700) {
score += 11;
} else {
return 0;
}
} else if (!tas_valid && tas_raw == 0) {
score += 1;
} else {
return 0;
}
// small penalty for inconsistent data
if (gs_valid && tas_valid) {
int delta = abs((int)gs_valid - (int)tas_valid);
if (delta > 150) {
score -= 6;
}
}
// compute the theoretical turn rate and compare to track angle rate
if (roll_valid && tas_valid && tas > 0 && track_rate_valid) {
double turn_rate = 68625 * tan(roll * M_PI / 180.0) / (tas * 20 * M_PI);
double delta = fabs(turn_rate - track_rate);
if (delta > 2.0) {
score -= 6;
}
}
if (store) {
mm->commb_format = COMMB_TRACK_TURN;
if (roll_valid) {
mm->roll_valid = 1;
mm->roll = roll;
}
if (track_valid) {
mm->heading_valid = 1;
mm->heading = track;
mm->heading_type = HEADING_GROUND_TRACK;
}
if (gs_valid) {
mm->gs_valid = 1;
mm->gs.v0 = mm->gs.v2 = mm->gs.selected = gs;
}
if (track_rate_valid) {
mm->track_rate_valid = 1;
mm->track_rate = track_rate;
}
if (tas_valid) {
mm->tas_valid = 1;
mm->tas = tas;
}
}
return score;
}
// BDS6,0 Heading and speed report
static int decodeBDS60(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
unsigned heading_valid = getbit(msg, 1);
unsigned heading_sign = getbit(msg, 2);
unsigned heading_raw = getbits(msg, 3, 12);
unsigned ias_valid = getbit(msg, 13);
unsigned ias_raw = getbits(msg, 14, 23);
unsigned mach_valid = getbit(msg, 24);
unsigned mach_raw = getbits(msg, 25, 34);
unsigned baro_rate_valid = getbit(msg, 35);
unsigned baro_rate_sign = getbit(msg, 36);
unsigned baro_rate_raw = getbits(msg, 37, 45);
unsigned inertial_rate_valid = getbit(msg, 46);
unsigned inertial_rate_sign = getbit(msg, 47);
unsigned inertial_rate_raw = getbits(msg, 48, 56);
if (!heading_valid || !ias_valid || !mach_valid || (!baro_rate_valid && !inertial_rate_valid)) {
return 0;
}
int score = 0;
float heading = 0;
if (heading_valid) {
heading = heading_raw * 90.0 / 512.0;
if (heading_sign) {
heading += 180.0;
}
score += 12;
} else if (!heading_valid && heading_raw == 0 && !heading_sign) {
score += 1;
} else {
return 0;
}
unsigned ias = 0;
if (ias_valid && ias_raw != 0) {
ias = ias_raw;
if (ias >= 50 && ias <= 700) {
score += 11;
} else {
return 0;
}
} else if (!ias_valid && ias_raw == 0) {
score += 1;
} else {
return 0;
}
float mach = 0;
if (mach_valid && mach_raw != 0) {
mach = mach_raw * 2.048 / 512;
if (mach >= 0.1 && mach <= 0.9) {
score += 11;
} else {
return 0;
}
} else if (!mach_valid && mach_raw == 0) {
score += 1;
} else {
return 0;
}
int baro_rate = 0;
if (baro_rate_valid) {
baro_rate = baro_rate_raw * 32;
if (baro_rate_sign) {
baro_rate -= 16384;
}
if (baro_rate >= -6000 && baro_rate <= 6000) {
score += 11;
} else {
return 0;
}
} else if (!baro_rate_valid && baro_rate_raw == 0) {
score += 1;
} else {
return 0;
}
int inertial_rate = 0;
if (inertial_rate_valid) {
inertial_rate = inertial_rate_raw * 32;
if (inertial_rate_sign) {
inertial_rate -= 16384;
}
if (inertial_rate >= -6000 && inertial_rate <= 6000) {
score += 11;
} else {
return 0;
}
} else if (!inertial_rate_valid && inertial_rate_raw == 0) {
score += 1;
} else {
return 0;
}
// small penalty for inconsistent data
// Should check IAS vs Mach at given altitude, but the maths is a little involved
if (baro_rate_valid && inertial_rate_valid) {
int delta = abs(baro_rate - inertial_rate);
if (delta > 2000) {
score -= 12;
}
}
if (store) {
mm->commb_format = COMMB_HEADING_SPEED;
if (heading_valid) {
mm->heading_valid = 1;
mm->heading = heading;
mm->heading_type = HEADING_MAGNETIC;
}
if (ias_valid) {
mm->ias_valid = 1;
mm->ias = ias;
}
if (mach_valid) {
mm->mach_valid = 1;
mm->mach = mach;
}
if (baro_rate_valid) {
mm->baro_rate_valid = 1;
mm->baro_rate = baro_rate;
}
if (inertial_rate_valid) {
// INS-derived data is treated as a "geometric rate" / "geometric altitude"
// elsewhere, so do the same here.
mm->geom_rate_valid = 1;
mm->geom_rate = inertial_rate;
}
}
return score;
}
// BDS 4,4 Meteorological routine air report
static int decodeBDS44(struct modesMessage *mm, bool store) {
unsigned char *msg = mm->MB;
unsigned source = getbits(msg, 1, 4);
unsigned wind_valid = getbit(msg, 5);
unsigned wind_speed_raw = getbits(msg, 6, 14);
unsigned wind_direction_raw = getbits(msg, 15, 23);
unsigned temperature_sign = getbit(msg, 24);
unsigned static_air_temperature_raw = getbits(msg, 25, 34);
unsigned pressure_valid = getbit(msg, 35);
unsigned static_pressure_raw = getbits(msg, 36, 46);
unsigned turbulence_valid = getbit(msg, 47);
unsigned turbulence_raw = getbits(msg, 48, 49);
unsigned humidity_valid = getbit(msg, 50);
unsigned humidity_raw = getbits(msg, 51, 56);
/*
if (!wind_valid || !temperature_valid || !pressure_valid || !turbulence_valid && !humidity_valid){
return 0;
}
*/
int met_source = source;
int score = 0;
int wind_speed = 0;
float wind_direction = 0;
float temperature = 0;
int static_pressure = 0;
int turbulence = 0;
float humidity = 0;
if (met_source >= 0 && met_source <= 6) {
score += 4;
}
else {
return 0;
}
if (wind_valid){
wind_speed = (int)wind_speed_raw;
if (wind_speed <= 511 && wind_speed >= 0){
score += 9;
}
else {
return 0;
}
wind_direction = wind_direction_raw * (180 / 256);
if (wind_direction >= 0 && wind_direction <= 360){
score += 9;
}
else {
return 0;
}
}
else if (wind_speed == 0) {
score += 2;
}
if (temperature_sign){
temperature = (static_air_temperature_raw - pow(2, 10)) * 0.25;
}
else {
temperature = static_air_temperature_raw * 0.25;
}
if (temperature >= -128 && temperature <= 128){
score += 10;
}
else {
return 0;
}
if (pressure_valid){
static_pressure = (int)static_pressure_raw;
if (static_pressure >= 0 && static_pressure <= 2048){
score += 11;
return 0;
}
else {
}
}
else if (static_pressure == 0) {
score += 1;
}
if (turbulence_valid){
turbulence = (int)turbulence_raw;
if (turbulence >= 0 && turbulence <= 3) {
score += 2;
}
else {
return 0;
}
}
else if (turbulence == 0) {
score += 1;
}
if (humidity_valid) {
humidity = humidity_raw * (100.0f / 64);
if (humidity >= 0 && humidity <= 100){
score += 6;
}
else {
return 0;
}
}
else if (humidity == 0) {
score += 1;
}
if (store) {
mm->commb_format = COMMB_METEOROLOGICAL_ROUTINE;
mm->met_source_valid = 1;
mm->met_source = met_source;
if (wind_valid) {
mm->wind_valid = 1;
mm->wind_speed = wind_speed;
mm->wind_direction = wind_direction;
}
mm->oat_valid = 1;
mm->oat = temperature;
if (pressure_valid) {
mm->static_pressure_valid = 1;
mm->static_pressure = static_pressure;
}
if (turbulence_valid) {
mm->turbulence_valid = 1;
mm->turbulence = turbulence;
}
if (humidity_valid) {
mm->humidity_valid = 1;
mm->humidity = humidity;
}
}
return score;
}
readsb-3.16/comm_b.h 0000664 0000000 0000000 00000002140 15050573076 0014315 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// comm_b.h: Comm-B message decoding (header)
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2017 FlightAware, LLC
// Copyright (c) 2017 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#ifndef COMM_B_H
#define COMM_B_H
void decodeCommB (struct modesMessage *mm);
int checkAcasRaValid(unsigned char *MV, struct modesMessage *mm, int debug);
#endif
readsb-3.16/compat/ 0000775 0000000 0000000 00000000000 15050573076 0014176 5 ustar 00root root 0000000 0000000 readsb-3.16/compat/apple/ 0000775 0000000 0000000 00000000000 15050573076 0015277 5 ustar 00root root 0000000 0000000 readsb-3.16/compat/apple/clock_compat.h 0000664 0000000 0000000 00000004310 15050573076 0020104 0 ustar 00root root 0000000 0000000 #ifndef CLOCK_COMPAT_H
#define CLOCK_COMPAT_H
#ifdef __APPLE__
#include
#include
#include
#include
#include
/* Clock definitions */
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC 1
#endif
#ifndef TIMER_ABSTIME
#define TIMER_ABSTIME 1
#endif
/* Mach timebase info for conversion */
static mach_timebase_info_data_t __clock_timebase_info;
static pthread_once_t __clock_timebase_once = PTHREAD_ONCE_INIT;
static void __clock_timebase_init(void) {
mach_timebase_info(&__clock_timebase_info);
}
/* Clock compatibility functions */
static inline uint64_t clock_gettime_nsec(void) {
pthread_once(&__clock_timebase_once, __clock_timebase_init);
return (mach_absolute_time() * __clock_timebase_info.numer) / __clock_timebase_info.denom;
}
static inline int clock_nanosleep(clockid_t clock_id, int flags,
const struct timespec *request,
struct timespec *remain) {
(void)clock_id; // Only CLOCK_MONOTONIC supported
(void)remain; // remain not supported on macOS
pthread_once(&__clock_timebase_once, __clock_timebase_init);
if (flags & TIMER_ABSTIME) {
// For absolute time, calculate the relative delay
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
uint64_t now_ns = (uint64_t)now.tv_sec * 1000000000ULL + now.tv_nsec;
uint64_t target_ns = (uint64_t)request->tv_sec * 1000000000ULL + request->tv_nsec;
if (now_ns >= target_ns) {
return 0; // Target time already passed
}
uint64_t delay_ns = target_ns - now_ns;
struct timespec ts = {
.tv_sec = delay_ns / 1000000000ULL,
.tv_nsec = delay_ns % 1000000000ULL
};
while (nanosleep(&ts, &ts) == -1) {
if (errno != EINTR) {
return errno;
}
}
} else {
// For relative time, just use nanosleep directly
struct timespec ts = *request;
while (nanosleep(&ts, &ts) == -1) {
if (errno != EINTR) {
return errno;
}
}
}
return 0;
}
#endif /* __APPLE__ */
#endif /* CLOCK_COMPAT_H */
readsb-3.16/compat/apple/compat.h 0000664 0000000 0000000 00000001145 15050573076 0016734 0 ustar 00root root 0000000 0000000 #ifndef COMPAT_UTIL_H
#define COMPAT_UTIL_H
/*
* Platform-specific bits
*/
#if defined(__APPLE__)
/*
* Mach endian conversion
*/
# include
# define bswap_16 OSSwapInt16
# define bswap_32 OSSwapInt32
# define bswap_64 OSSwapInt64
# include
# define le16toh(x) OSSwapLittleToHostInt16(x)
# define le32toh(x) OSSwapLittleToHostInt32(x)
#else // other platforms
# include
#endif
#ifdef MISSING_NANOSLEEP
#include "clock_nanosleep/clock_nanosleep.h"
#endif
#ifdef MISSING_GETTIME
#include "clock_gettime/clock_gettime.h"
#endif
#endif //COMPAT_UTIL_H
readsb-3.16/compat/apple/cpu_compat.h 0000664 0000000 0000000 00000002416 15050573076 0017605 0 ustar 00root root 0000000 0000000 #ifndef CPU_COMPAT_H
#define CPU_COMPAT_H
#ifdef __APPLE__
#include
#include
#include
#include
/* CPU set definitions */
typedef uint64_t cpu_set_t;
#define CPU_SETSIZE 1024
#define CPU_COUNT(set) __builtin_popcountll(*(set))
#define CPU_ZERO(set) (*(set) = 0)
#define CPU_SET(cpu, set) (*(set) |= (1ULL << (cpu)))
#define CPU_CLR(cpu, set) (*(set) &= ~(1ULL << (cpu)))
#define CPU_ISSET(cpu, set) ((*(set) & (1ULL << (cpu))) != 0)
/* CPU affinity functions */
static inline int sched_getaffinity(pid_t pid, size_t cpu_size, cpu_set_t *mask) {
(void)pid; // Suppress unused parameter warning
(void)cpu_size; // Suppress unused parameter warning
int32_t core_count = 0;
size_t len = sizeof(core_count);
if (sysctlbyname("hw.logicalcpu", &core_count, &len, NULL, 0) == 0) {
CPU_ZERO(mask);
for (int i = 0; i < core_count; i++) {
CPU_SET(i, mask);
}
return 0;
}
return -1;
}
static inline int sched_setaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask) {
/* On macOS, we can't actually set CPU affinity, so we just pretend it worked */
(void)pid;
(void)cpusetsize;
(void)mask;
return 0;
}
#endif /* __APPLE__ */
#endif /* CPU_COMPAT_H */
readsb-3.16/compat/apple/epoll_shim.c 0000664 0000000 0000000 00000003615 15050573076 0017603 0 ustar 00root root 0000000 0000000 #ifdef __APPLE__
#include "epoll_shim.h"
#include
#include
int epoll_create1(int flags) {
(void)flags; // Suppress unused parameter warning
return kqueue();
}
int epoll_create(int size) {
(void)size; // Suppress unused parameter warning
return epoll_create1(0);
}
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event) {
struct kevent ke;
if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_MOD) {
uint16_t flags = EV_ADD;
if (event->events & EPOLLIN)
EV_SET(&ke, fd, EVFILT_READ, flags, 0, 0, event->data.ptr);
if (event->events & EPOLLOUT)
EV_SET(&ke, fd, EVFILT_WRITE, flags, 0, 0, event->data.ptr);
return kevent(epfd, &ke, 1, NULL, 0, NULL);
} else if (op == EPOLL_CTL_DEL) {
EV_SET(&ke, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
kevent(epfd, &ke, 1, NULL, 0, NULL);
EV_SET(&ke, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
return kevent(epfd, &ke, 1, NULL, 0, NULL);
}
return -1;
}
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout) {
struct kevent kevents[maxevents];
struct timespec ts;
if (timeout >= 0) {
ts.tv_sec = timeout / 1000;
ts.tv_nsec = (timeout % 1000) * 1000000;
}
int nev = kevent(epfd, NULL, 0, kevents, maxevents,
timeout >= 0 ? &ts : NULL);
for (int i = 0; i < nev; i++) {
events[i].events = 0;
if (kevents[i].filter == EVFILT_READ)
events[i].events |= EPOLLIN;
if (kevents[i].filter == EVFILT_WRITE)
events[i].events |= EPOLLOUT;
if (kevents[i].flags & EV_ERROR)
events[i].events |= EPOLLERR;
if (kevents[i].flags & EV_EOF)
events[i].events |= EPOLLHUP;
events[i].data.ptr = kevents[i].udata;
}
return nev;
}
#endif /* __APPLE__ */
readsb-3.16/compat/apple/epoll_shim.h 0000664 0000000 0000000 00000001704 15050573076 0017605 0 ustar 00root root 0000000 0000000 #ifndef EPOLL_SHIM_H
#define EPOLL_SHIM_H
#ifdef __APPLE__
#include
#include
#include
#include
#include "cpu_compat.h"
/* epoll definitions */
#define EPOLLIN 0x001
#define EPOLLOUT 0x004
#define EPOLLERR 0x008
#define EPOLLHUP 0x010
#define EPOLLPRI 0x002
#define EPOLLRDHUP 0x020
#define EPOLL_CTL_ADD 1
#define EPOLL_CTL_DEL 2
#define EPOLL_CTL_MOD 3
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct epoll_event {
uint32_t events;
epoll_data_t data;
};
#ifdef __cplusplus
extern "C" {
#endif
/* Function declarations */
int epoll_create(int size);
int epoll_create1(int flags);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout);
#ifdef __cplusplus
}
#endif
#endif /* __APPLE__ */
#endif /* EPOLL_SHIM_H */
readsb-3.16/compat/apple/net_compat.h 0000664 0000000 0000000 00000005021 15050573076 0017577 0 ustar 00root root 0000000 0000000 #ifndef NET_COMPAT_H
#define NET_COMPAT_H
#ifdef __APPLE__
#include
#include
#include
#include
#include
#include
/* Socket flags */
#ifndef SOCK_NONBLOCK
#define SOCK_NONBLOCK 0x00004000 /* Match Linux's value */
#endif
#ifndef SOCK_CLOEXEC
#define SOCK_CLOEXEC FD_CLOEXEC
#endif
/* TCP socket options */
#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif
/* TCP keepalive options */
#ifndef TCP_KEEPIDLE
#define TCP_KEEPIDLE TCP_KEEPALIVE
#endif
#ifndef TCP_KEEPINTVL
#define TCP_KEEPINTVL 0x101 /* Time between keepalive probes */
#endif
#ifndef TCP_KEEPCNT
#define TCP_KEEPCNT 0x102 /* Number of keepalive probes before disconnect */
#endif
/* Basic socket operations */
static inline int set_socket_nonblock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return -1;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
static inline int create_socket_nonblock(int domain, int type, int protocol) {
int fd = socket(domain, type & ~SOCK_NONBLOCK, protocol);
if (fd < 0) return fd;
if (type & SOCK_NONBLOCK) {
if (set_socket_nonblock(fd) < 0) {
close(fd);
return -1;
}
}
return fd;
}
/* accept4 compatibility */
static inline int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) {
int fd = accept(sockfd, addr, addrlen);
if (fd < 0) return fd;
if (flags & SOCK_NONBLOCK) {
if (set_socket_nonblock(fd) < 0) {
close(fd);
return -1;
}
}
if (flags & SOCK_CLOEXEC) {
int current = fcntl(fd, F_GETFD);
if (current < 0 || fcntl(fd, F_SETFD, current | FD_CLOEXEC) < 0) {
close(fd);
return -1;
}
}
return fd;
}
/* Socket creation override */
#ifdef socket
#undef socket
#endif
#define socket(domain, type, protocol) create_socket_nonblock(domain, type, protocol)
/* TCP keepalive compatibility */
static inline int set_tcp_keepalive(int fd, int idle, int interval, int count) {
int ret = 0;
/* Enable keepalive */
int yes = 1;
ret |= setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));
/* On macOS, TCP_KEEPALIVE is in seconds */
ret |= setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &idle, sizeof(idle));
/* macOS doesn't support changing the interval and count directly */
(void)interval;
(void)count;
return ret;
}
#endif /* __APPLE__ */
#endif /* NET_COMPAT_H */
readsb-3.16/compat/apple/sendfile_compat.h 0000664 0000000 0000000 00000003736 15050573076 0020615 0 ustar 00root root 0000000 0000000 #ifndef SENDFILE_COMPAT_H
#define SENDFILE_COMPAT_H
#ifdef __APPLE__
#include
#include
#include
#include
#include
/* sendfile compatibility for macOS */
static inline ssize_t linux_sendfile(int out_fd, int in_fd, off_t *offset, size_t count) {
off_t len = count;
/* Use native macOS sendfile if possible */
if (sendfile(in_fd, out_fd, *offset, &len, NULL, 0) == 0) {
*offset += len;
return len;
}
/* Fall back to read/write if sendfile fails */
char buffer[8192];
size_t remaining = count;
ssize_t total = 0;
if (offset && lseek(in_fd, *offset, SEEK_SET) == -1) {
return -1;
}
while (remaining > 0) {
size_t to_read = (remaining < sizeof(buffer)) ? remaining : sizeof(buffer);
ssize_t bytes_read = read(in_fd, buffer, to_read);
if (bytes_read <= 0) {
if (bytes_read == 0) break; /* EOF */
if (errno == EINTR) continue;
if (total > 0) break; /* Return partial success */
return -1;
}
size_t to_write = bytes_read;
size_t written = 0;
while (written < to_write) {
ssize_t ret = write(out_fd, buffer + written, to_write - written);
if (ret <= 0) {
if (ret == -1 && errno == EINTR) continue;
if (total > 0 || written > 0) {
/* Return partial success */
total += written;
if (offset) *offset += total;
return total;
}
return -1;
}
written += ret;
}
total += written;
remaining -= written;
}
if (offset) *offset += total;
return total;
}
#define sendfile(out_fd, in_fd, offset, count) linux_sendfile(out_fd, in_fd, offset, count)
#endif /* __APPLE__ */
#endif /* SENDFILE_COMPAT_H */
readsb-3.16/compat/apple/serial_compat.h 0000664 0000000 0000000 00000001576 15050573076 0020303 0 ustar 00root root 0000000 0000000 #ifndef SERIAL_COMPAT_H
#define SERIAL_COMPAT_H
#ifdef __APPLE__
#include
#include
#include
/* Define missing baud rates for macOS */
#ifndef B460800
#define B460800 460800
#endif
#ifndef B500000
#define B500000 500000
#endif
#ifndef B576000
#define B576000 576000
#endif
#ifndef B921600
#define B921600 921600
#endif
#ifndef B1000000
#define B1000000 1000000
#endif
#ifndef B1152000
#define B1152000 1152000
#endif
#ifndef B1500000
#define B1500000 1500000
#endif
#ifndef B2000000
#define B2000000 2000000
#endif
#ifndef B2500000
#define B2500000 2500000
#endif
#ifndef B3000000
#define B3000000 3000000
#endif
#ifndef B3500000
#define B3500000 3500000
#endif
#ifndef B4000000
#define B4000000 4000000
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* __APPLE__ */
#endif /* SERIAL_COMPAT_H */
readsb-3.16/compat/apple/stat_compat.h 0000664 0000000 0000000 00000000326 15050573076 0017767 0 ustar 00root root 0000000 0000000 #ifndef STAT_COMPAT_H
#define STAT_COMPAT_H
#ifdef __APPLE__
#include
/* macOS uses st_mtimespec instead of st_mtim */
#define st_mtim st_mtimespec
#endif /* __APPLE__ */
#endif /* STAT_COMPAT_H */
readsb-3.16/compat/apple/thread_compat.h 0000664 0000000 0000000 00000003233 15050573076 0020263 0 ustar 00root root 0000000 0000000 #ifndef THREAD_COMPAT_H
#define THREAD_COMPAT_H
#ifdef __APPLE__
#include
#include
#include
#include
#include "cpu_compat.h"
/* Forward declarations */
static inline int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime);
/* pthread_tryjoin_np implementation for macOS */
static inline int pthread_tryjoin_np(pthread_t thread, void **retval) {
struct timespec ts = { 0, 0 }; // Zero timeout
return pthread_timedjoin_np(thread, retval, &ts);
}
/* pthread_timedjoin_np implementation for macOS */
static inline int pthread_timedjoin_np(pthread_t thread, void **retval, const struct timespec *abstime) {
int res;
struct timespec ts_start;
/* Try joining immediately first */
res = pthread_kill(thread, 0);
if (res != 0) {
return res;
}
if (clock_gettime(CLOCK_REALTIME, &ts_start) != 0) {
return EINVAL;
}
while ((res = pthread_join(thread, retval)) == EBUSY) {
struct timespec ts_now;
if (clock_gettime(CLOCK_REALTIME, &ts_now) != 0) {
return EINVAL;
}
/* Check if we've exceeded the timeout */
if (ts_now.tv_sec > ts_start.tv_sec + abstime->tv_sec ||
(ts_now.tv_sec == ts_start.tv_sec + abstime->tv_sec &&
ts_now.tv_nsec >= ts_start.tv_nsec + abstime->tv_nsec)) {
return ETIMEDOUT;
}
/* Sleep for a short time before trying again */
struct timespec ts_sleep = { 0, 1000000 }; /* 1ms */
nanosleep(&ts_sleep, NULL);
}
return res;
}
#endif /* __APPLE__ */
#endif /* THREAD_COMPAT_H */
readsb-3.16/compat/clock_gettime/ 0000775 0000000 0000000 00000000000 15050573076 0017007 5 ustar 00root root 0000000 0000000 readsb-3.16/compat/clock_gettime/LICENSE 0000664 0000000 0000000 00000003050 15050573076 0020012 0 ustar 00root root 0000000 0000000 /*
* Copyright (c), MM Weiss
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 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.
*
* 3. Neither the name of the MM Weiss nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/ readsb-3.16/compat/clock_gettime/clock_gettime.c 0000664 0000000 0000000 00000011277 15050573076 0021774 0 ustar 00root root 0000000 0000000 /*
* Copyright (c), MM Weiss
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 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.
*
* 3. Neither the name of the MM Weiss nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
/*
* clock_gettime_stub.c
* gcc -Wall -c clock_gettime_stub.c
* posix realtime functions; MacOS user space glue
*/
/* @comment
* other possible implementation using intel builtin rdtsc
* rdtsc-workaround: http://www.mcs.anl.gov/~kazutomo/rdtsc.html
*
* we could get the ticks by doing this
*
* __asm __volatile("mov %%ebx, %%esi\n\t"
* "cpuid\n\t"
* "xchg %%esi, %%ebx\n\t"
* "rdtsc"
* : "=a" (a),
* "=d" (d)
* );
* we could even replace our tricky sched_yield call by assembly code to get a better accurency,
* anyway the following C stub will satisfy 99% of apps using posix clock_gettime call,
* moreover, the setter version (clock_settime) could be easly written using mach primitives:
* http://www.opensource.apple.com/source/xnu/xnu-${VERSION}/osfmk/man/ (clock_[set|get]_time)
*
* hackers don't be crackers, don't you use a flush toilet?
*
*
* @see draft: ./posix-realtime-stub/posix-realtime-stub.c
*
*/
#include "clock_gettime.h"
#include // for clock_get_time
#include // for mach_timespec_t, CALENDAR_CLOCK, etc
#include // for KERN_SUCCESS, kern_return_t
#include // for host_get_clock_service
#include // for mach_host_self
#include // for clock_serv_t
#include // for sched_yield
#include // for EINVAL, errno
#include // for getpid
int clock_gettime(clockid_t clk_id, struct timespec *tp)
{
kern_return_t ret;
clock_serv_t clk;
clock_id_t clk_serv_id;
mach_timespec_t tm;
uint64_t start, end, delta, nano;
/*
task_basic_info_data_t tinfo;
task_thread_times_info_data_t ttinfo;
mach_msg_type_number_t tflag;
*/
int retval = -1;
switch (clk_id)
{
case CLOCK_REALTIME:
case CLOCK_MONOTONIC:
clk_serv_id = clk_id == CLOCK_REALTIME ? CALENDAR_CLOCK : SYSTEM_CLOCK;
if (KERN_SUCCESS == (ret = host_get_clock_service(mach_host_self(), clk_serv_id, &clk)))
{
if (KERN_SUCCESS == (ret = clock_get_time(clk, &tm)))
{
tp->tv_sec = tm.tv_sec;
tp->tv_nsec = tm.tv_nsec;
retval = 0;
}
}
if (KERN_SUCCESS != ret)
{
errno = EINVAL;
retval = -1;
}
break;
case CLOCK_PROCESS_CPUTIME_ID:
case CLOCK_THREAD_CPUTIME_ID:
start = mach_absolute_time();
if (clk_id == CLOCK_PROCESS_CPUTIME_ID)
{
getpid();
}
else
{
sched_yield();
}
end = mach_absolute_time();
delta = end - start;
if (0 == __clock_gettime_inf.denom)
{
mach_timebase_info(&__clock_gettime_inf);
}
nano = delta * __clock_gettime_inf.numer / __clock_gettime_inf.denom;
tp->tv_sec = nano * 1e-9;
tp->tv_nsec = nano - (tp->tv_sec * 1e9);
retval = 0;
break;
default:
errno = EINVAL;
retval = -1;
}
return retval;
}
readsb-3.16/compat/clock_gettime/clock_gettime.h 0000664 0000000 0000000 00000001024 15050573076 0021766 0 ustar 00root root 0000000 0000000 #ifndef CLOCK_GETTIME_H
#define CLOCK_GETTIME_H
#include // Apple-only, but this isn't inclued on other BSDs
#ifdef _CLOCKID_T_DEFINED_
#define CLOCKID_T
#endif
#ifndef CLOCKID_T
#define CLOCKID_T
typedef enum
{
CLOCK_REALTIME,
CLOCK_MONOTONIC,
CLOCK_PROCESS_CPUTIME_ID,
CLOCK_THREAD_CPUTIME_ID
} clockid_t;
#endif // ifndef CLOCKID_T
struct timespec;
static mach_timebase_info_data_t __clock_gettime_inf;
int clock_gettime(clockid_t clk_id, struct timespec *tp);
#endif // CLOCK_GETTIME_H
readsb-3.16/compat/clock_nanosleep/ 0000775 0000000 0000000 00000000000 15050573076 0017335 5 ustar 00root root 0000000 0000000 readsb-3.16/compat/clock_nanosleep/LICENSE 0000664 0000000 0000000 00000002222 15050573076 0020340 0 ustar 00root root 0000000 0000000 /***********************************************************************
* Copyright © 2006 Rémi Denis-Courmont. *
* This program is free software; you can redistribute and/or modify *
* it under the terms of the GNU General Public License as published *
* by the Free Software Foundation; version 2 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, you can get it from: *
* http://www.gnu.org/copyleft/gpl.html *
***********************************************************************/ readsb-3.16/compat/clock_nanosleep/clock_nanosleep.c 0000664 0000000 0000000 00000004573 15050573076 0022651 0 ustar 00root root 0000000 0000000 /*
* clock_nanosleep.c - clock_nanosleep() replacement
*/
/***********************************************************************
* Copyright © 2006 Rémi Denis-Courmont. *
* This program is free software; you can redistribute and/or modify *
* it under the terms of the GNU General Public License as published *
* by the Free Software Foundation; version 2 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, you can get it from: *
* http://www.gnu.org/copyleft/gpl.html *
***********************************************************************/
#include // for errno, EINVAL
#include // for nanosleep, NULL
#include "clock_nanosleep.h"
#ifdef MISSING_GETTIME
#include "../clock_gettime/clock_gettime.h" // for clock_gettime
#endif
int clock_nanosleep(clockid_t id, int flags, const struct timespec *ts,
struct timespec *ots) {
int ret;
if (id != CLOCK_REALTIME)
return EINVAL;
if (flags & TIMER_ABSTIME) {
struct timespec mine;
if (clock_gettime(id, &mine))
return errno;
if (mine.tv_sec > ts->tv_sec)
return 0; // behind schedule
if (mine.tv_nsec > ts->tv_nsec) {
if (mine.tv_sec == ts->tv_sec)
return 0; // behind schedule too
mine.tv_nsec = 1000000000 + ts->tv_nsec - mine.tv_nsec;
mine.tv_sec++;
}
else
mine.tv_nsec = ts->tv_nsec - mine.tv_nsec;
mine.tv_sec = ts->tv_sec - mine.tv_sec;
/* With TIMER_ABSTIME, clock_nanosleep ignores */
ret = nanosleep(&mine, NULL);
}
else
ret = nanosleep(ts, ots);
return ret ? errno : 0;
}
readsb-3.16/compat/clock_nanosleep/clock_nanosleep.h 0000664 0000000 0000000 00000001024 15050573076 0022642 0 ustar 00root root 0000000 0000000 #ifndef CLOCK_NANOSLEEP_H
#define CLOCK_NANOSLEEP_H
#ifdef _CLOCKID_T_DEFINED_
#define CLOCKID_T
#endif
#ifndef CLOCKID_T
#define CLOCKID_T
typedef enum
{
CLOCK_REALTIME,
CLOCK_MONOTONIC,
CLOCK_PROCESS_CPUTIME_ID,
CLOCK_THREAD_CPUTIME_ID
} clockid_t;
#endif // ifndef CLOCKID_T
#ifndef TIMER_ABSTIME
#define TIMER_ABSTIME 1
#endif // TIMER_ABSTIME
struct timespec;
int clock_nanosleep (clockid_t id, int flags, const struct timespec *ts,
struct timespec *ots);
#endif //CLOCK_NANOSLEEP_H
readsb-3.16/compat/compat.h 0000664 0000000 0000000 00000001623 15050573076 0015634 0 ustar 00root root 0000000 0000000 #ifndef COMPAT_UTIL_H
#define COMPAT_UTIL_H
/*
* Platform-specific bits
*/
#if defined(__APPLE__)
#define NO_EVENT_FD
/*
* Mach endian conversion
*/
# include
# define bswap_16 OSSwapInt16
# define bswap_32 OSSwapInt32
# define bswap_64 OSSwapInt64
# include
# define le16toh(x) OSSwapLittleToHostInt16(x)
# define le32toh(x) OSSwapLittleToHostInt32(x)
#include "apple/clock_compat.h"
#include "apple/compat.h"
#include "apple/cpu_compat.h"
#include "apple/epoll_shim.h"
#include "apple/net_compat.h"
#include "apple/sendfile_compat.h"
#include "apple/serial_compat.h"
#include "apple/stat_compat.h"
#include "apple/thread_compat.h"
#else // other platforms
# include
#endif
#ifdef MISSING_NANOSLEEP
#include "clock_nanosleep/clock_nanosleep.h"
#endif
#ifdef MISSING_GETTIME
#include "clock_gettime/clock_gettime.h"
#endif
#endif //COMPAT_UTIL_H
readsb-3.16/convert.c 0000664 0000000 0000000 00000031705 15050573076 0014545 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// convert.c: support for various IQ -> magnitude conversions
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#include "readsb.h"
struct converter_state {
float dc_a;
float dc_b;
float z1_I;
float z1_Q;
};
static uint16_t *uc8_lookup;
static bool init_uc8_lookup() {
if (uc8_lookup)
return true;
uc8_lookup = cmalloc(sizeof (uint16_t) * 256 * 256);
if (!uc8_lookup) {
fprintf(stderr, "can't allocate UC8 conversion lookup table\n");
return false;
}
for (int i = 0; i <= 255; i++) {
for (int q = 0; q <= 255; q++) {
float fI, fQ, magsq;
fI = (i - 127.5) / 127.5;
fQ = (q - 127.5) / 127.5;
magsq = fI * fI + fQ * fQ;
//fprintf(stderr, "%d %d %.2f\n", i, q, magsq);
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
uc8_lookup[le16toh((i * 256) + q)] = (uint16_t) (mag * 65535.0f + 0.5f);
}
}
return true;
}
static void convert_uc8_nodc(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
uint16_t *in = iq_data;
unsigned i;
uint64_t sum_level = 0;
uint64_t sum_power = 0;
uint16_t mag;
MODES_NOTUSED(state);
// Increases readability but no optimization
#define DO_ONE_SAMPLE \
do { \
mag = uc8_lookup[*in++]; \
*mag_data++ = mag; \
sum_level += mag; \
sum_power += (uint32_t)mag * (uint32_t)mag; \
} while(0)
// unroll this a bit
for (i = 0; i < (nsamples / 4); ++i) {
DO_ONE_SAMPLE;
DO_ONE_SAMPLE;
DO_ONE_SAMPLE;
DO_ONE_SAMPLE;
}
for (i = 0; i < (nsamples % 4); ++i) {
DO_ONE_SAMPLE;
}
#undef DO_ONE_SAMPLE
if (out_mean_level) {
*out_mean_level = sum_level / 65536.0 / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / 65535.0 / 65535.0 / nsamples;
}
}
static void convert_uc8_generic(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
uint8_t *in = iq_data;
float z1_I = state->z1_I;
float z1_Q = state->z1_Q;
const float dc_a = state->dc_a;
const float dc_b = state->dc_b;
unsigned i;
uint8_t I, Q;
float fI, fQ, magsq;
float sum_level = 0, sum_power = 0;
for (i = 0; i < nsamples; ++i) {
I = *in++;
Q = *in++;
fI = (I - 127.5f) / 127.5f;
fQ = (Q - 127.5f) / 127.5f;
// DC block
z1_I = fI * dc_a + z1_I * dc_b;
z1_Q = fQ * dc_a + z1_Q * dc_b;
fI -= z1_I;
fQ -= z1_Q;
magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
sum_power += magsq;
sum_level += mag;
*mag_data++ = (uint16_t) (mag * 65535.0f + 0.5f);
}
state->z1_I = z1_I;
state->z1_Q = z1_Q;
if (out_mean_level) {
*out_mean_level = sum_level / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / nsamples;
}
}
static void convert_sc16_generic(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
uint16_t *in = iq_data;
float z1_I = state->z1_I;
float z1_Q = state->z1_Q;
const float dc_a = state->dc_a;
const float dc_b = state->dc_b;
unsigned i;
int16_t I, Q;
float fI, fQ, magsq;
float sum_level = 0, sum_power = 0;
for (i = 0; i < nsamples; ++i) {
I = (int16_t) le16toh(*in++);
Q = (int16_t) le16toh(*in++);
fI = I / 32768.0f;
fQ = Q / 32768.0f;
// DC block
z1_I = fI * dc_a + z1_I * dc_b;
z1_Q = fQ * dc_a + z1_Q * dc_b;
fI -= z1_I;
fQ -= z1_Q;
magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
sum_power += magsq;
sum_level += mag;
*mag_data++ = (uint16_t) (mag * 65535.0f + 0.5f);
}
state->z1_I = z1_I;
state->z1_Q = z1_Q;
if (out_mean_level) {
*out_mean_level = sum_level / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / nsamples;
}
}
static void convert_sc16_nodc(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
MODES_NOTUSED(state);
uint16_t *in = iq_data;
unsigned i;
int16_t I, Q;
float fI, fQ, magsq;
float sum_level = 0, sum_power = 0;
for (i = 0; i < nsamples; ++i) {
I = (int16_t) le16toh(*in++);
Q = (int16_t) le16toh(*in++);
fI = I / 32768.0f;
fQ = Q / 32768.0f;
magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
sum_power += magsq;
sum_level += mag;
*mag_data++ = (uint16_t) (mag * 65535.0f + 0.5f);
}
if (out_mean_level) {
*out_mean_level = sum_level / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / nsamples;
}
}
// SC16Q11_TABLE_BITS controls the size of the lookup table
// for SC16Q11 data. The size of the table is 2 * (1 << (2*BITS))
// bytes. Reducing the number of bits reduces precision but
// can run substantially faster by staying in cache.
// See convert_benchmark.c for some numbers.
// Leaving SC16QQ_TABLE_BITS undefined will disable the table lookup and always use
// the floating-point path, which may be faster on some systems
#if defined(SC16Q11_TABLE_BITS)
#define USE_BITS SC16Q11_TABLE_BITS
#define LOSE_BITS (11 - SC16Q11_TABLE_BITS)
static uint16_t *sc16q11_lookup;
static bool init_sc16q11_lookup() {
if (sc16q11_lookup)
return true;
sc16q11_lookup = cmalloc(sizeof (uint16_t) * (1 << (USE_BITS * 2)));
if (!sc16q11_lookup) {
fprintf(stderr, "can't allocate SC16Q11 conversion lookup table\n");
return false;
}
for (int i = 0; i < 2048; i += (1 << LOSE_BITS)) {
for (int q = 0; q < 2048; q += (1 << LOSE_BITS)) {
float fI = i / 2048.0, fQ = q / 2048.0;
float magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
unsigned index = ((i >> LOSE_BITS) << USE_BITS) | (q >> LOSE_BITS);
sc16q11_lookup[index] = (uint16_t) (mag * 65535.0f + 0.5f);
}
}
return true;
}
static void convert_sc16q11_table(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
uint16_t *in = iq_data;
unsigned i;
uint16_t I, Q;
uint64_t sum_level = 0;
uint64_t sum_power = 0;
uint16_t mag;
MODES_NOTUSED(state);
for (i = 0; i < nsamples; ++i) {
I = abs((int16_t) le16toh(*in++)) & 2047;
Q = abs((int16_t) le16toh(*in++)) & 2047;
mag = sc16q11_lookup[((I >> LOSE_BITS) << USE_BITS) | (Q >> LOSE_BITS)];
*mag_data++ = mag;
sum_level += mag;
sum_power += (uint32_t) mag * (uint32_t) mag;
}
if (out_mean_level) {
*out_mean_level = sum_level / 65536.0 / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / 65535.0 / 65535.0 / nsamples;
}
}
#else /* ! defined(SC16Q11_TABLE_BITS) */
static void convert_sc16q11_nodc(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
MODES_NOTUSED(state);
uint16_t *in = iq_data;
unsigned i;
int16_t I, Q;
float fI, fQ, magsq;
float sum_level = 0, sum_power = 0;
for (i = 0; i < nsamples; ++i) {
I = (int16_t) le16toh(*in++);
Q = (int16_t) le16toh(*in++);
fI = I / 2048.0f;
fQ = Q / 2048.0f;
magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
sum_power += magsq;
sum_level += mag;
*mag_data++ = (uint16_t) (mag * 65535.0f + 0.5f);
}
if (out_mean_level) {
*out_mean_level = sum_level / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / nsamples;
}
}
#endif /* defined(SC16Q11_TABLE_BITS) */
static void convert_sc16q11_generic(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power) {
uint16_t *in = iq_data;
float z1_I = state->z1_I;
float z1_Q = state->z1_Q;
const float dc_a = state->dc_a;
const float dc_b = state->dc_b;
unsigned i;
int16_t I, Q;
float fI, fQ, magsq;
float sum_level = 0, sum_power = 0;
for (i = 0; i < nsamples; ++i) {
I = (int16_t) le16toh(*in++);
Q = (int16_t) le16toh(*in++);
fI = I / 2048.0f;
fQ = Q / 2048.0f;
// DC block
z1_I = fI * dc_a + z1_I * dc_b;
z1_Q = fQ * dc_a + z1_Q * dc_b;
fI -= z1_I;
fQ -= z1_Q;
magsq = fI * fI + fQ * fQ;
if (magsq > 1)
magsq = 1;
float mag = sqrtf(magsq);
sum_power += magsq;
sum_level += mag;
*mag_data++ = (uint16_t) (mag * 65535.0f + 0.5f);
}
state->z1_I = z1_I;
state->z1_Q = z1_Q;
if (out_mean_level) {
*out_mean_level = sum_level / nsamples;
}
if (out_mean_power) {
*out_mean_power = sum_power / nsamples;
}
}
static struct {
input_format_t format;
int can_filter_dc;
iq_convert_fn fn;
const char *description;
bool(*init)();
} converters_table[] = {
// In order of preference
{ INPUT_UC8, 0, convert_uc8_nodc, "UC8, integer/table path", init_uc8_lookup},
{ INPUT_UC8, 1, convert_uc8_generic, "UC8, float path", NULL},
{ INPUT_SC16, 0, convert_sc16_nodc, "SC16, float path, no DC", NULL},
{ INPUT_SC16, 1, convert_sc16_generic, "SC16, float path", NULL},
#if defined(SC16Q11_TABLE_BITS)
{ INPUT_SC16Q11, 0, convert_sc16q11_table, "SC16Q11, integer/table path", init_sc16q11_lookup},
#else
{ INPUT_SC16Q11, 0, convert_sc16q11_nodc, "SC16Q11, float path, no DC", NULL},
#endif
{ INPUT_SC16Q11, 1, convert_sc16q11_generic, "SC16Q11, float path", NULL},
{ 0, 0, NULL, NULL, NULL}
};
iq_convert_fn init_converter(input_format_t format,
double sample_rate,
int filter_dc,
struct converter_state **out_state) {
int i;
for (i = 0; converters_table[i].fn; ++i) {
if (converters_table[i].format != format)
continue;
if (filter_dc && !converters_table[i].can_filter_dc)
continue;
break;
}
if (!converters_table[i].fn) {
fprintf(stderr, "no suitable converter for format=%d dc=%d\n",
format, filter_dc);
return NULL;
}
if (converters_table[i].init) {
if (!converters_table[i].init())
return NULL;
}
*out_state = cmalloc(sizeof (struct converter_state));
if (! *out_state) {
fprintf(stderr, "can't allocate converter state\n");
return NULL;
}
(*out_state)->z1_I = 0;
(*out_state)->z1_Q = 0;
if (filter_dc) {
// init DC block @ 1Hz
(*out_state)->dc_b = exp(-2.0 * M_PI * 1.0 / sample_rate);
(*out_state)->dc_a = 1.0 - (*out_state)->dc_b;
} else {
// if the converter does filtering, make sure it has no effect
(*out_state)->dc_b = 1.0;
(*out_state)->dc_a = 0.0;
}
if (Modes.sdr_type == SDR_IFILE) {
fprintf(stderr, "init_converter: using %s\n", converters_table[i].description);
}
return converters_table[i].fn;
}
void cleanup_converter(struct converter_state **state) {
sfree(uc8_lookup);
#if defined(SC16Q11_TABLE_BITS)
sfree(sc16q11_lookup);
#endif
sfree(*state);
}
readsb-3.16/convert.h 0000664 0000000 0000000 00000003230 15050573076 0014542 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// convert.h: support for various IQ -> magnitude conversions
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#ifndef DUMP1090_CONVERT_H
#define DUMP1090_CONVERT_H
struct converter_state;
typedef enum
{
INPUT_UC8 = 0, INPUT_SC16, INPUT_SC16Q11
} input_format_t;
typedef void (*iq_convert_fn)(void *iq_data,
uint16_t *mag_data,
unsigned nsamples,
struct converter_state *state,
double *out_mean_level,
double *out_mean_power);
iq_convert_fn init_converter (input_format_t format,
double sample_rate,
int filter_dc,
struct converter_state **out_state);
void cleanup_converter (struct converter_state **state);
#endif
readsb-3.16/cpr.c 0000664 0000000 0000000 00000032343 15050573076 0013650 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// cpr.c - Compact Position Reporting decoder and tests
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014,2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
//
// This file incorporates work covered by the following copyright and
// license:
//
// Copyright (C) 2012 by Salvatore Sanfilippo
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT
// HOLDER 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.
#include
#include
//
//=========================================================================
//
// Always positive MOD operation, used for CPR decoding.
//
static int cprModInt(int a, int b) {
int res = a % b;
if (res < 0) res += b;
return res;
}
static double cprModDouble(double a, double b) {
double res = fmod(a, b);
if (res < 0) res += b;
return res;
}
//
//=========================================================================
//
// The NL function uses the precomputed table from 1090-WP-9-14
//
static int cprNLFunction(double lat) {
if (lat < 0) lat = -lat; // Table is simmetric about the equator
if (lat > 60) goto L60;
if (lat > 44.2) goto L442;
if (lat > 30) goto L30;
if (lat < 10.47047130) return 59;
if (lat < 14.82817437) return 58;
if (lat < 18.18626357) return 57;
if (lat < 21.02939493) return 56;
if (lat < 23.54504487) return 55;
if (lat < 25.82924707) return 54;
if (lat < 27.93898710) return 53;
if (lat < 29.91135686) return 52;
L30:
if (lat < 31.77209708) return 51;
if (lat < 33.53993436) return 50;
if (lat < 35.22899598) return 49;
if (lat < 36.85025108) return 48;
if (lat < 38.41241892) return 47;
if (lat < 39.92256684) return 46;
if (lat < 41.38651832) return 45;
if (lat < 42.80914012) return 44;
if (lat < 44.19454951) return 43;
L442:
if (lat < 45.54626723) return 42;
if (lat < 46.86733252) return 41;
if (lat < 48.16039128) return 40;
if (lat < 49.42776439) return 39;
if (lat < 50.67150166) return 38;
if (lat < 51.89342469) return 37;
if (lat < 53.09516153) return 36;
if (lat < 54.27817472) return 35;
if (lat < 55.44378444) return 34;
if (lat < 56.59318756) return 33;
if (lat < 57.72747354) return 32;
if (lat < 58.84763776) return 31;
if (lat < 59.95459277) return 30;
L60:
if (lat < 61.04917774) return 29;
if (lat < 62.13216659) return 28;
if (lat < 63.20427479) return 27;
if (lat < 64.26616523) return 26;
if (lat < 65.31845310) return 25;
if (lat < 66.36171008) return 24;
if (lat < 67.39646774) return 23;
if (lat < 68.42322022) return 22;
if (lat < 69.44242631) return 21;
if (lat < 70.45451075) return 20;
if (lat < 71.45986473) return 19;
if (lat < 72.45884545) return 18;
if (lat < 73.45177442) return 17;
if (lat < 74.43893416) return 16;
if (lat < 75.42056257) return 15;
if (lat < 76.39684391) return 14;
if (lat < 77.36789461) return 13;
if (lat < 78.33374083) return 12;
if (lat < 79.29428225) return 11;
if (lat < 80.24923213) return 10;
if (lat < 81.19801349) return 9;
if (lat < 82.13956981) return 8;
if (lat < 83.07199445) return 7;
if (lat < 83.99173563) return 6;
if (lat < 84.89166191) return 5;
if (lat < 85.75541621) return 4;
if (lat < 86.53536998) return 3;
if (lat < 87.00000000) return 2;
else return 1;
}
//
//=========================================================================
//
static int cprNFunction(double lat, int fflag) {
int nl = cprNLFunction(lat) - (fflag ? 1 : 0);
if (nl < 1) nl = 1;
return nl;
}
//
//=========================================================================
//
static double cprDlonFunction(double lat, int fflag, int surface) {
return (surface ? 90.0 : 360.0) / cprNFunction(lat, fflag);
}
//
//=========================================================================
//
// This algorithm comes from:
// http://www.lll.lu/~edward/edward/adsb/DecodingADSBposition.html.
//
// A few remarks:
// 1) 131072 is 2^17 since CPR latitude and longitude are encoded in 17 bits.
//
int decodeCPRairborne(int even_cprlat, int even_cprlon,
int odd_cprlat, int odd_cprlon,
int fflag,
double *out_lat, double *out_lon) {
double AirDlat0 = 360.0 / 60.0;
double AirDlat1 = 360.0 / 59.0;
double lat0 = even_cprlat;
double lat1 = odd_cprlat;
double lon0 = even_cprlon;
double lon1 = odd_cprlon;
double rlat, rlon;
// Compute the Latitude Index "j"
int j = (int) floor(((59 * lat0 - 60 * lat1) / 131072) + 0.5);
double rlat0 = AirDlat0 * (cprModInt(j, 60) + lat0 / 131072);
double rlat1 = AirDlat1 * (cprModInt(j, 59) + lat1 / 131072);
if (rlat0 >= 270) rlat0 -= 360;
if (rlat1 >= 270) rlat1 -= 360;
// Check to see that the latitude is in range: -90 .. +90
if (rlat0 < -90 || rlat0 > 90 || rlat1 < -90 || rlat1 > 90)
return (-2); // bad data
// Check that both are in the same latitude zone, or abort.
if (cprNLFunction(rlat0) != cprNLFunction(rlat1))
return (-1); // positions crossed a latitude zone, try again later
// Compute ni and the Longitude Index "m"
if (fflag) { // Use odd packet.
int ni = cprNFunction(rlat1, 1);
int m = (int) floor((((lon0 * (cprNLFunction(rlat1) - 1)) -
(lon1 * cprNLFunction(rlat1))) / 131072.0) + 0.5);
rlon = cprDlonFunction(rlat1, 1, 0) * (cprModInt(m, ni) + lon1 / 131072);
rlat = rlat1;
} else { // Use even packet.
int ni = cprNFunction(rlat0, 0);
int m = (int) floor((((lon0 * (cprNLFunction(rlat0) - 1)) -
(lon1 * cprNLFunction(rlat0))) / 131072) + 0.5);
rlon = cprDlonFunction(rlat0, 0, 0) * (cprModInt(m, ni) + lon0 / 131072);
rlat = rlat0;
}
// Renormalize to -180 .. +180
rlon -= floor((rlon + 180) / 360) * 360;
*out_lat = rlat;
*out_lon = rlon;
return 0;
}
int decodeCPRsurface(double reflat, double reflon,
int even_cprlat, int even_cprlon,
int odd_cprlat, int odd_cprlon,
int fflag,
double *out_lat, double *out_lon) {
double AirDlat0 = 90.0 / 60.0;
double AirDlat1 = 90.0 / 59.0;
double lat0 = even_cprlat;
double lat1 = odd_cprlat;
double lon0 = even_cprlon;
double lon1 = odd_cprlon;
double rlon, rlat;
// Compute the Latitude Index "j"
int j = (int) floor(((59 * lat0 - 60 * lat1) / 131072) + 0.5);
double rlat0 = AirDlat0 * (cprModInt(j, 60) + lat0 / 131072);
double rlat1 = AirDlat1 * (cprModInt(j, 59) + lat1 / 131072);
// Pick the quadrant that's closest to the reference location -
// this is not necessarily the same quadrant that contains the
// reference location.
//
// There are also only two valid quadrants: -90..0 and 0..90;
// no correct message would try to encoding a latitude in the
// ranges -180..-90 and 90..180.
//
// If the computed latitude is more than 45 degrees north of
// the reference latitude (using the northern hemisphere
// solution), then the southern hemisphere solution will be
// closer to the refernce latitude.
//
// e.g. reflat=0, rlat=44, use rlat=44
// reflat=0, rlat=46, use rlat=46-90 = -44
// reflat=40, rlat=84, use rlat=84
// reflat=40, rlat=86, use rlat=86-90 = -4
// reflat=-40, rlat=4, use rlat=4
// reflat=-40, rlat=6, use rlat=6-90 = -84
// As a special case, -90, 0 and +90 all encode to zero, so
// there's a little extra work to do there.
if (rlat0 == 0) {
if (reflat < -45)
rlat0 = -90;
else if (reflat > 45)
rlat0 = 90;
} else if ((rlat0 - reflat) > 45) {
rlat0 -= 90;
}
if (rlat1 == 0) {
if (reflat < -45)
rlat1 = -90;
else if (reflat > 45)
rlat1 = 90;
} else if ((rlat1 - reflat) > 45) {
rlat1 -= 90;
}
// Check to see that the latitude is in range: -90 .. +90
if (rlat0 < -90 || rlat0 > 90 || rlat1 < -90 || rlat1 > 90)
return (-2); // bad data
// Check that both are in the same latitude zone, or abort.
if (cprNLFunction(rlat0) != cprNLFunction(rlat1))
return (-1); // positions crossed a latitude zone, try again later
// Compute ni and the Longitude Index "m"
if (fflag) { // Use odd packet.
int ni = cprNFunction(rlat1, 1);
int m = (int) floor((((lon0 * (cprNLFunction(rlat1) - 1)) -
(lon1 * cprNLFunction(rlat1))) / 131072.0) + 0.5);
rlon = cprDlonFunction(rlat1, 1, 1) * (cprModInt(m, ni) + lon1 / 131072);
rlat = rlat1;
} else { // Use even packet.
int ni = cprNFunction(rlat0, 0);
int m = (int) floor((((lon0 * (cprNLFunction(rlat0) - 1)) -
(lon1 * cprNLFunction(rlat0))) / 131072) + 0.5);
rlon = cprDlonFunction(rlat0, 0, 1) * (cprModInt(m, ni) + lon0 / 131072);
rlat = rlat0;
}
// Pick the quadrant that's closest to the reference location -
// this is not necessarily the same quadrant that contains the
// reference location. Unlike the latitude case, all four
// quadrants are valid.
// if reflon is more than 45 degrees away, move some multiple of 90 degrees towards it
rlon += floor((reflon - rlon + 45) / 90) * 90; // this might move us outside (-180..+180), we fix this below
// Renormalize to -180 .. +180
rlon -= floor((rlon + 180) / 360) * 360;
*out_lat = rlat;
*out_lon = rlon;
return 0;
}
//
//=========================================================================
//
// This algorithm comes from:
// 1090-WP29-07-Draft_CPR101 (which also defines decodeCPR() )
//
// Despite what the earlier comment here said, we should *not* be using trunc().
// See Figure 5-5 / 5-6 and note that floor is applied to (0.5 + fRP - fEP), not
// directly to (fRP - fEP). Eq 38 is correct.
//
int decodeCPRrelative(double reflat, double reflon,
int cprlat, int cprlon,
int fflag, int surface,
double *out_lat, double *out_lon) {
double AirDlat;
double AirDlon;
double fractional_lat = cprlat / 131072.0;
double fractional_lon = cprlon / 131072.0;
double rlon, rlat;
int j, m;
AirDlat = (surface ? 90.0 : 360.0) / (fflag ? 59.0 : 60.0);
// Compute the Latitude Index "j"
j = (int) (floor(reflat / AirDlat) +
floor(0.5 + cprModDouble(reflat, AirDlat) / AirDlat - fractional_lat));
rlat = AirDlat * (j + fractional_lat);
if (rlat >= 270) rlat -= 360;
// Check to see that the latitude is in range: -90 .. +90
if (rlat < -90 || rlat > 90) {
return (-1); // Time to give up - Latitude error
}
// Check to see that answer is reasonable - ie no more than 1/2 cell away
if (fabs(rlat - reflat) > (AirDlat / 2)) {
return (-1); // Time to give up - Latitude error
}
// Compute the Longitude Index "m"
AirDlon = cprDlonFunction(rlat, fflag, surface);
m = (int) (floor(reflon / AirDlon) +
floor(0.5 + cprModDouble(reflon, AirDlon) / AirDlon - fractional_lon));
rlon = AirDlon * (m + fractional_lon);
if (rlon > 180) rlon -= 360;
// Check to see that answer is reasonable - ie no more than 1/2 cell away
if (fabs(rlon - reflon) > (AirDlon / 2))
return (-1); // Time to give up - Longitude error
*out_lat = rlat;
*out_lon = rlon;
return (0);
}
readsb-3.16/cpr.h 0000664 0000000 0000000 00000003153 15050573076 0013652 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// cpr.h - Compact Position Reporting prototypes
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014,2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#ifndef DUMP1090_CPR_H
#define DUMP1090_CPR_H
int decodeCPRairborne (int even_cprlat, int even_cprlon,
int odd_cprlat, int odd_cprlon,
int fflag,
double *out_lat, double *out_lon);
int decodeCPRsurface (double reflat, double reflon,
int even_cprlat, int even_cprlon,
int odd_cprlat, int odd_cprlon,
int fflag,
double *out_lat, double *out_lon);
int decodeCPRrelative (double reflat, double reflon,
int cprlat, int cprlon,
int fflag, int surface,
double *out_lat, double *out_lon);
#endif
readsb-3.16/cpreadsb.sh 0000775 0000000 0000000 00000000163 15050573076 0015035 0 ustar 00root root 0000000 0000000 #!/bin/bash
set -e
rm -f /usr/bin/readsb /usr/bin/viewadsb
cp readsb /usr/bin/readsb
cp viewadsb /usr/bin/viewadsb
readsb-3.16/cprtests.c 0000664 0000000 0000000 00000040023 15050573076 0014725 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// cprtests.c - tests for CPR decoder
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014,2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#include
#include
#include "cpr.h"
// Global, airborne CPR test data:
static const struct {
int even_cprlat, even_cprlon; // input: raw CPR values, even message
int odd_cprlat, odd_cprlon; // input: raw CPR values, odd message
int even_result; // verify: expected result from decoding with fflag=0 (even message is latest)
double even_rlat, even_rlon; // verify: expected position from decoding with fflag=0 (even message is latest)
int odd_result; // verify: expected result from decoding with fflag=1 (odd message is latest)
double odd_rlat, odd_rlon; // verify: expected position from decoding with fflag=1 (odd message is latest)
} cprGlobalAirborneTests[] = {
{ 80536, 9432, 61720, 9192, 0, 51.686646, 0.700156, 0, 51.686763, 0.701294},
{ 80534, 9413, 61714, 9144, 0, 51.686554, 0.698745, 0, 51.686484, 0.697632},
// todo: more positions, bad data
};
// Global, surface CPR test data:
static const struct {
double reflat, reflon; // input: reference location for decoding
int even_cprlat, even_cprlon; // input: raw CPR values, even message
int odd_cprlat, odd_cprlon; // input: raw CPR values, odd message
int even_result; // verify: expected result from decoding with fflag=0 (even message is latest)
double even_rlat, even_rlon; // verify: expected position from decoding with fflag=0 (even message is latest)
int odd_result; // verify: expected result from decoding with fflag=1 (odd message is latest)
double odd_rlat, odd_rlon; // verify: expected position from decoding with fflag=1 (odd message is latest)
} cprGlobalSurfaceTests[] = {
// The real position received here was on the Cambridge (UK) airport apron at 52.21N 0.177E
// We mess with the reference location to check that the right quadrant is used.
// longitude quadrants:
{ 52.00, -180.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 - 180.0, 0, 52.209976, 0.176507 - 180.0},
{ 52.00, -140.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 - 180.0, 0, 52.209976, 0.176507 - 180.0},
{ 52.00, -130.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 - 90.0, 0, 52.209976, 0.176507 - 90.0},
{ 52.00, -50.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 - 90.0, 0, 52.209976, 0.176507 - 90.0},
{ 52.00, -40.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 52.00, -10.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 52.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 52.00, 10.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 52.00, 40.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 52.00, 50.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 + 90.0, 0, 52.209976, 0.176507 + 90.0},
{ 52.00, 130.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 + 90.0, 0, 52.209976, 0.176507 + 90.0},
{ 52.00, 140.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 - 180.0, 0, 52.209976, 0.176507 - 180.0},
{ 52.00, 180.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601 - 180.0, 0, 52.209976, 0.176507 - 180.0},
// latitude quadrants (but only 2). The decoded longitude also changes because the cell size changes with latitude
{ 90.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 52.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 8.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984, 0.176601, 0, 52.209976, 0.176507},
{ 7.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984 - 90.0, 0.135269, 0, 52.209976 - 90.0, 0.134299},
{ -52.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984 - 90.0, 0.135269, 0, 52.209976 - 90.0, 0.134299},
{ -90.00, 0.00, 105730, 9259, 29693, 8997, 0, 52.209984 - 90.0, 0.135269, 0, 52.209976 - 90.0, 0.134299},
// poles/equator cases
{ -46.00, -180.00, 0, 0, 0, 0, 0, -90.0, -180.000000, 0, -90.0, -180.0}, // south pole
{ -44.00, -180.00, 0, 0, 0, 0, 0, 0.0, -180.000000, 0, 0.0, -180.0}, // equator
{ 44.00, -180.00, 0, 0, 0, 0, 0, 0.0, -180.000000, 0, 0.0, -180.0}, // equator
{ 46.00, -180.00, 0, 0, 0, 0, 0, 90.0, -180.000000, 0, 90.0, -180.0}, // north pole
};
// Relative CPR test data:
static const struct {
double reflat, reflon; // input: reference location for decoding
int cprlat, cprlon; // input: raw CPR values, even or odd message
int fflag; // input: fflag in raw message
int surface; // input: decode as air (0) or surface (1) position
int result; // verify: expected result
double rlat, rlon; // verify: expected position
} cprRelativeTests[] = {
//
// AIRBORNE
//
{ 52.00, 0.00, 80536, 9432, 0, 0, 0, 51.686646, 0.700156}, // even, airborne
{ 52.00, 0.00, 61720, 9192, 1, 0, 0, 51.686763, 0.701294}, // odd, airborne
{ 52.00, 0.00, 80534, 9413, 0, 0, 0, 51.686554, 0.698745}, // even, airborne
{ 52.00, 0.00, 61714, 9144, 1, 0, 0, 51.686484, 0.697632}, // odd, airborne
// test moving the receiver around a bit
// We cannot move it more than 1/2 cell away before ambiguity happens.
// latitude must be within about 3 degrees (cell size is 360/60 = 6 degrees)
{ 48.70, 0.00, 80536, 9432, 0, 0, 0, 51.686646, 0.700156}, // even, airborne
{ 48.70, 0.00, 61720, 9192, 1, 0, 0, 51.686763, 0.701294}, // odd, airborne
{ 48.70, 0.00, 80534, 9413, 0, 0, 0, 51.686554, 0.698745}, // even, airborne
{ 48.70, 0.00, 61714, 9144, 1, 0, 0, 51.686484, 0.697632}, // odd, airborne
{ 54.60, 0.00, 80536, 9432, 0, 0, 0, 51.686646, 0.700156}, // even, airborne
{ 54.60, 0.00, 61720, 9192, 1, 0, 0, 51.686763, 0.701294}, // odd, airborne
{ 54.60, 0.00, 80534, 9413, 0, 0, 0, 51.686554, 0.698745}, // even, airborne
{ 54.60, 0.00, 61714, 9144, 1, 0, 0, 51.686484, 0.697632}, // odd, airborne
// longitude must be within about 4.8 degrees at this latitude
{ 52.00, 5.40, 80536, 9432, 0, 0, 0, 51.686646, 0.700156}, // even, airborne
{ 52.00, 5.40, 61720, 9192, 1, 0, 0, 51.686763, 0.701294}, // odd, airborne
{ 52.00, 5.40, 80534, 9413, 0, 0, 0, 51.686554, 0.698745}, // even, airborne
{ 52.00, 5.40, 61714, 9144, 1, 0, 0, 51.686484, 0.697632}, // odd, airborne
{ 52.00, -4.10, 80536, 9432, 0, 0, 0, 51.686646, 0.700156}, // even, airborne
{ 52.00, -4.10, 61720, 9192, 1, 0, 0, 51.686763, 0.701294}, // odd, airborne
{ 52.00, -4.10, 80534, 9413, 0, 0, 0, 51.686554, 0.698745}, // even, airborne
{ 52.00, -4.10, 61714, 9144, 1, 0, 0, 51.686484, 0.697632}, // odd, airborne
//
// SURFACE
//
// Surface position on the Cambridge (UK) airport apron at 52.21N 0.18E
{ 52.00, 0.00, 105730, 9259, 0, 1, 0, 52.209984, 0.176601}, // even, surface
{ 52.00, 0.00, 29693, 8997, 1, 1, 0, 52.209976, 0.176507}, // odd, surface
// test moving the receiver around a bit
// We cannot move it more than 1/2 cell away before ambiguity happens.
// latitude must be within about 0.75 degrees (cell size is 90/60 = 1.5 degrees)
{ 51.46, 0.00, 105730, 9259, 0, 1, 0, 52.209984, 0.176601}, // even, surface
{ 51.46, 0.00, 29693, 8997, 1, 1, 0, 52.209976, 0.176507}, // odd, surface
{ 52.95, 0.00, 105730, 9259, 0, 1, 0, 52.209984, 0.176601}, // even, surface
{ 52.95, 0.00, 29693, 8997, 1, 1, 0, 52.209976, 0.176507}, // odd, surface
// longitude must be within about 1.25 degrees at this latitude
{ 52.00, 1.40, 105730, 9259, 0, 1, 0, 52.209984, 0.176601}, // even, surface
{ 52.00, 1.40, 29693, 8997, 1, 1, 0, 52.209976, 0.176507}, // odd, surface
{ 52.00, -1.05, 105730, 9259, 0, 1, 0, 52.209984, 0.176601}, // even, surface
{ 52.00, -1.05, 29693, 8997, 1, 1, 0, 52.209976, 0.176507}, // odd, surface
};
static int testCPRGlobalAirborne() {
int ok = 1;
unsigned i;
for (i = 0; i < sizeof (cprGlobalAirborneTests) / sizeof (cprGlobalAirborneTests[0]); ++i) {
double rlat = 0, rlon = 0;
int res;
res = decodeCPRairborne(cprGlobalAirborneTests[i].even_cprlat, cprGlobalAirborneTests[i].even_cprlon,
cprGlobalAirborneTests[i].odd_cprlat, cprGlobalAirborneTests[i].odd_cprlon,
0,
&rlat, &rlon);
if (res != cprGlobalAirborneTests[i].even_result
|| fabs(rlat - cprGlobalAirborneTests[i].even_rlat) > 1e-6
|| fabs(rlon - cprGlobalAirborneTests[i].even_rlon) > 1e-6) {
ok = 0;
fprintf(stderr,
"testCPRGlobalAirborne[%u,EVEN]: FAIL: decodeCPRairborne(%d,%d,%d,%d,EVEN) failed:\n"
" result %d (expected %d)\n"
" lat %.6f (expected %.6f)\n"
" lon %.6f (expected %.6f)\n",
i,
cprGlobalAirborneTests[i].even_cprlat, cprGlobalAirborneTests[i].even_cprlon,
cprGlobalAirborneTests[i].odd_cprlat, cprGlobalAirborneTests[i].odd_cprlon,
res, cprGlobalAirborneTests[i].even_result,
rlat, cprGlobalAirborneTests[i].even_rlat,
rlon, cprGlobalAirborneTests[i].even_rlon);
} else {
fprintf(stderr, "testCPRGlobalAirborne[%u,EVEN]: PASS\n", i);
}
res = decodeCPRairborne(cprGlobalAirborneTests[i].even_cprlat, cprGlobalAirborneTests[i].even_cprlon,
cprGlobalAirborneTests[i].odd_cprlat, cprGlobalAirborneTests[i].odd_cprlon,
1,
&rlat, &rlon);
if (res != cprGlobalAirborneTests[i].odd_result
|| fabs(rlat - cprGlobalAirborneTests[i].odd_rlat) > 1e-6
|| fabs(rlon - cprGlobalAirborneTests[i].odd_rlon) > 1e-6) {
ok = 0;
fprintf(stderr,
"testCPRGlobalAirborne[%u,ODD]: FAIL: decodeCPRairborne(%d,%d,%d,%d,ODD) failed:\n"
" result %d (expected %d)\n"
" lat %.6f (expected %.6f)\n"
" lon %.6f (expected %.6f)\n",
i,
cprGlobalAirborneTests[i].even_cprlat, cprGlobalAirborneTests[i].even_cprlon,
cprGlobalAirborneTests[i].odd_cprlat, cprGlobalAirborneTests[i].odd_cprlon,
res, cprGlobalAirborneTests[i].odd_result,
rlat, cprGlobalAirborneTests[i].odd_rlat,
rlon, cprGlobalAirborneTests[i].odd_rlon);
} else {
fprintf(stderr, "testCPRGlobalAirborne[%u,ODD]: PASS\n", i);
}
}
return ok;
}
static int testCPRGlobalSurface() {
int ok = 1;
unsigned i;
for (i = 0; i < sizeof (cprGlobalSurfaceTests) / sizeof (cprGlobalSurfaceTests[0]); ++i) {
double rlat = 0, rlon = 0;
int res;
res = decodeCPRsurface(cprGlobalSurfaceTests[i].reflat, cprGlobalSurfaceTests[i].reflon,
cprGlobalSurfaceTests[i].even_cprlat, cprGlobalSurfaceTests[i].even_cprlon,
cprGlobalSurfaceTests[i].odd_cprlat, cprGlobalSurfaceTests[i].odd_cprlon,
0,
&rlat, &rlon);
if (res != cprGlobalSurfaceTests[i].even_result
|| fabs(rlat - cprGlobalSurfaceTests[i].even_rlat) > 1e-6
|| fabs(rlon - cprGlobalSurfaceTests[i].even_rlon) > 1e-6) {
ok = 0;
fprintf(stderr,
"testCPRGlobalSurface[%u,EVEN]: FAIL: decodeCPRsurface(%.6f,%.6f,%d,%d,%d,%d,EVEN) failed:\n"
" result %d (expected %d)\n"
" lat %.6f (expected %.6f)\n"
" lon %.6f (expected %.6f)\n",
i,
cprGlobalSurfaceTests[i].reflat, cprGlobalSurfaceTests[i].reflon,
cprGlobalSurfaceTests[i].even_cprlat, cprGlobalSurfaceTests[i].even_cprlon,
cprGlobalSurfaceTests[i].odd_cprlat, cprGlobalSurfaceTests[i].odd_cprlon,
res, cprGlobalSurfaceTests[i].even_result,
rlat, cprGlobalSurfaceTests[i].even_rlat,
rlon, cprGlobalSurfaceTests[i].even_rlon);
} else {
fprintf(stderr, "testCPRGlobalSurface[%u,EVEN]: PASS\n", i);
}
res = decodeCPRsurface(cprGlobalSurfaceTests[i].reflat, cprGlobalSurfaceTests[i].reflon,
cprGlobalSurfaceTests[i].even_cprlat, cprGlobalSurfaceTests[i].even_cprlon,
cprGlobalSurfaceTests[i].odd_cprlat, cprGlobalSurfaceTests[i].odd_cprlon,
1,
&rlat, &rlon);
if (res != cprGlobalSurfaceTests[i].odd_result
|| fabs(rlat - cprGlobalSurfaceTests[i].odd_rlat) > 1e-6
|| fabs(rlon - cprGlobalSurfaceTests[i].odd_rlon) > 1e-6) {
ok = 0;
fprintf(stderr,
"testCPRGlobalSurface[%u,ODD]: FAIL: decodeCPRsurface(%.6f,%.6f,%d,%d,%d,%d,ODD) failed:\n"
" result %d (expected %d)\n"
" lat %.6f (expected %.6f)\n"
" lon %.6f (expected %.6f)\n",
i,
cprGlobalSurfaceTests[i].reflat, cprGlobalSurfaceTests[i].reflon,
cprGlobalSurfaceTests[i].even_cprlat, cprGlobalSurfaceTests[i].even_cprlon,
cprGlobalSurfaceTests[i].odd_cprlat, cprGlobalSurfaceTests[i].odd_cprlon,
res, cprGlobalSurfaceTests[i].odd_result,
rlat, cprGlobalSurfaceTests[i].odd_rlat,
rlon, cprGlobalSurfaceTests[i].odd_rlon);
} else {
fprintf(stderr, "testCPRGlobalSurface[%u,ODD]: PASS\n", i);
}
}
return ok;
}
static int testCPRRelative() {
int ok = 1;
unsigned i;
for (i = 0; i < sizeof (cprRelativeTests) / sizeof (cprRelativeTests[0]); ++i) {
double rlat = 0, rlon = 0;
int res;
res = decodeCPRrelative(cprRelativeTests[i].reflat, cprRelativeTests[i].reflon,
cprRelativeTests[i].cprlat, cprRelativeTests[i].cprlon,
cprRelativeTests[i].fflag, cprRelativeTests[i].surface,
&rlat, &rlon);
if (res != cprRelativeTests[i].result
|| fabs(rlat - cprRelativeTests[i].rlat) > 1e-6
|| fabs(rlon - cprRelativeTests[i].rlon) > 1e-6) {
ok = 0;
fprintf(stderr,
"testCPRRelative[%u]: FAIL: decodeCPRrelative(%.6f,%.6f,%d,%d,%d,%d) failed:\n"
" result %d (expected %d)\n"
" lat %.6f (expected %.6f)\n"
" lon %.6f (expected %.6f)\n",
i,
cprRelativeTests[i].reflat, cprRelativeTests[i].reflon,
cprRelativeTests[i].cprlat, cprRelativeTests[i].cprlon,
cprRelativeTests[i].fflag, cprRelativeTests[i].surface,
res, cprRelativeTests[i].result,
rlat, cprRelativeTests[i].rlat,
rlon, cprRelativeTests[i].rlon);
} else {
fprintf(stderr, "testCPRRelative[%u]: PASS\n", i);
}
}
return ok;
}
int main(int __attribute__ ((unused)) argc, char __attribute__ ((unused)) **argv) {
int ok = 1;
ok = testCPRGlobalAirborne() && ok;
ok = testCPRGlobalSurface() && ok;
ok = testCPRRelative() && ok;
return ok ? 0 : 1;
}
readsb-3.16/crc.c 0000664 0000000 0000000 00000042601 15050573076 0013631 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// crc.h: Mode S CRC calculation and error correction.
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014,2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#include "readsb.h"
#include
// Errorinfo for "no errors"
static struct errorinfo NO_ERRORS;
// Generator polynomial for the Mode S CRC:
#define MODES_GENERATOR_POLY 0xfff409U
// CRC values for all single-byte messages;
// used to speed up CRC calculation.
ALIGNED static uint32_t crc_table[256];
// Syndrome values for all single-bit errors;
// used to speed up construction of error-
// correction tables.
ALIGNED static uint32_t single_bit_syndrome[112];
static void initLookupTables() {
int i;
uint8_t msg[112 / 8];
for (i = 0; i < 256; ++i) {
uint32_t c = i << 16;
int j;
for (j = 0; j < 8; ++j) {
if (c & 0x800000)
c = (c << 1) ^ MODES_GENERATOR_POLY;
else
c = (c << 1);
}
crc_table[i] = c & 0x00ffffff;
}
memset(msg, 0, sizeof (msg));
for (i = 0; i < 112; ++i) {
msg[i / 8] ^= 1 << (7 - (i & 7));
single_bit_syndrome[i] = modesChecksum(msg, 112);
msg[i / 8] ^= 1 << (7 - (i & 7));
}
}
uint32_t modesChecksum(uint8_t *message, int bits) {
uint32_t rem = 0;
int i;
int n = bits / 8;
assert(bits % 8 == 0);
assert(n >= 3);
for (i = 0; i < n - 3; ++i) {
rem = (rem << 8) ^ crc_table[message[i] ^ ((rem & 0xff0000) >> 16)];
rem = rem & 0xffffff;
}
rem = rem ^ (message[n - 3] << 16) ^ (message[n - 2] << 8) ^ (message[n - 1]);
return rem;
}
static struct errorinfo *bitErrorTable_short;
static int bitErrorTableSize_short;
static struct errorinfo *bitErrorTable_long;
static int bitErrorTableSize_long;
// compare two errorinfo structures
static int syndrome_compare(const void *x, const void *y) {
struct errorinfo *ex = (struct errorinfo*) x;
struct errorinfo *ey = (struct errorinfo*) y;
return (int) ex->syndrome - (int) ey->syndrome;
}
// (n k), the number of ways of selecting k distinct items from a set of n items
static int combinations(int n, int k) {
int result = 1, i;
if (k == 0 || k == n)
return 1;
if (k > n)
return 0;
for (i = 1; i <= k; ++i) {
result = result * n / i;
n = n - 1;
}
return result;
}
// Recursively populates an errorinfo table with error syndromes
//
// in:
// table: the table to fill
// n: first entry to fill
// maxSize: max size of table
// offset: start bit offset for checksum calculation
// startbit: first bit to introduce errors into
// endbit: (one past) last bit to introduce errors info
// base_entry: template entry to start from
// error_bit: how many error bits have already been set
// max_errors: maximum total error bits to set
// out:
// returns: the next free entry in the table
// table: has been populated between [n, return value)
static int prepareSubtable(struct errorinfo *table, int n, int maxsize, int offset, int startbit, int endbit, struct errorinfo *base_entry, int error_bit, int max_errors) {
int i = 0;
if (error_bit >= max_errors)
return n;
for (i = startbit; i < endbit; ++i) {
assert(n < maxsize);
table[n] = *base_entry;
table[n].syndrome ^= single_bit_syndrome[i + offset];
table[n].errors = error_bit + 1;
table[n].bit[error_bit] = i;
++n;
n = prepareSubtable(table, n, maxsize, offset, i + 1, endbit, &table[n - 1], error_bit + 1, max_errors);
}
return n;
}
static int flagCollisions(struct errorinfo *table, int tablesize, int offset, int startbit, int endbit, uint32_t base_syndrome, int error_bit, int first_error, int last_error) {
int i = 0;
int count = 0;
if (error_bit > last_error)
return 0;
for (i = startbit; i < endbit; ++i) {
struct errorinfo ei;
ei.syndrome = base_syndrome ^ single_bit_syndrome[i + offset];
if (error_bit >= first_error) {
struct errorinfo *collision = bsearch(&ei, table, tablesize, sizeof (struct errorinfo), syndrome_compare);
if (collision != NULL && collision->errors != -1) {
++count;
collision->errors = -1;
}
}
count += flagCollisions(table, tablesize, offset, i + 1, endbit, ei.syndrome, error_bit + 1, first_error, last_error);
}
return count;
}
// Allocate and build an error table for messages of length "bits" (max 112)
// returns a pointer to the new table and sets *size_out to the table length
static struct errorinfo *prepareErrorTable(int bits, int max_correct, int max_detect, int *size_out) {
int maxsize, usedsize;
struct errorinfo *table;
struct errorinfo base_entry;
int i, j;
assert(bits >= 0 && bits <= 112);
assert(max_correct >= 0 && max_correct <= MODES_MAX_BITERRORS);
assert(max_detect >= max_correct);
if (!max_correct) {
*size_out = 0;
return NULL;
}
maxsize = 0;
for (i = 1; i <= max_correct; ++i) {
maxsize += combinations(bits - 5, i); // space needed for all i-bit errors
}
#ifdef CRCDEBUG
fprintf(stderr, "Preparing syndrome table to correct up to %d-bit errors (detecting %d-bit errors) in a %d-bit message (max %d entries)\n", max_correct, max_detect, bits, maxsize);
#endif
table = cmalloc(maxsize * sizeof (struct errorinfo));
base_entry.syndrome = 0;
base_entry.errors = 0;
for (i = 0; i < MODES_MAX_BITERRORS; ++i)
base_entry.bit[i] = -1;
// ignore the first 5 bits (DF type)
usedsize = prepareSubtable(table, 0, maxsize, 112 - bits, 5, bits, &base_entry, 0, max_correct);
#ifdef CRCDEBUG
fprintf(stderr, "%d syndromes (expected %d).\n", usedsize, maxsize);
fprintf(stderr, "Sorting syndromes..\n");
#endif
qsort(table, usedsize, sizeof (struct errorinfo), syndrome_compare);
#ifdef CRCDEBUG
{
// Show the table stats
fprintf(stderr, "Undetectable errors:\n");
for (i = 1; i <= max_correct; ++i) {
int j, count;
count = 0;
for (j = 0; j < usedsize; ++j)
if (table[j].errors == i && table[j].syndrome == 0)
++count;
fprintf(stderr, " %d undetectable %d-bit errors\n", count, i);
}
}
#endif
// Handle ambiguous cases, where there is more than one possible error pattern
// that produces a given syndrome (this happens with >2 bit errors).
#ifdef CRCDEBUG
fprintf(stderr, "Finding collisions..\n");
#endif
for (i = 0, j = 0; i < usedsize; ++i) {
if (i < usedsize - 1 && table[i + 1].syndrome == table[i].syndrome) {
// skip over this entry and all collisions
while (i < usedsize && table[i + 1].syndrome == table[i].syndrome)
++i;
// now table[i] is the last duplicate
continue;
}
if (i != j)
table[j] = table[i];
++j;
}
if (j < usedsize) {
#ifdef CRCDEBUG
fprintf(stderr, "Discarded %d collisions.\n", usedsize - j);
#endif
usedsize = j;
}
// Flag collisions we want to detect but not correct
if (max_detect > max_correct) {
int flagged;
#ifdef CRCDEBUG
fprintf(stderr, "Flagging collisions between %d - %d bits..\n", max_correct + 1, max_detect);
#endif
flagged = flagCollisions(table, usedsize, 112 - bits, 5, bits, 0, 1, max_correct + 1, max_detect);
#ifdef CRCDEBUG
fprintf(stderr, "Flagged %d collisions for removal.\n", flagged);
#else
#endif
if (flagged > 0) {
for (i = 0, j = 0; i < usedsize; ++i) {
if (table[i].errors != -1) {
if (i != j)
table[j] = table[i];
++j;
}
}
#ifdef CRCDEBUG
fprintf(stderr, "Discarded %d flagged collisions.\n", usedsize - j);
#endif
usedsize = j;
}
}
if (usedsize < maxsize) {
#ifdef CRCDEBUG
fprintf(stderr, "Shrinking table from %d to %d..\n", maxsize, usedsize);
table = realloc(table, usedsize * sizeof (struct errorinfo));
#endif
}
*size_out = usedsize;
#ifdef CRCDEBUG
{
// Check the table.
unsigned char *msg = cmalloc(bits / 8);
for (i = 0; i < usedsize; ++i) {
int j;
struct errorinfo *ei;
uint32_t result;
memset(msg, 0, bits / 8);
ei = &table[i];
for (j = 0; j < ei->errors; ++j) {
msg[ei->bit[j] >> 3] ^= 1 << (7 - (ei->bit[j]&7));
}
result = modesChecksum(msg, bits);
if (result != ei->syndrome) {
fprintf(stderr, "PROBLEM: entry %6d/%6d syndrome %06x errors %d bits ", i, usedsize, ei->syndrome, ei->errors);
for (j = 0; j < ei->errors; ++j)
fprintf(stderr, "%3d ", ei->bit[j]);
fprintf(stderr, " checksum %06x\n", result);
}
}
free(msg);
// Show the table stats
fprintf(stderr, "Syndrome table summary:\n");
for (i = 1; i <= max_correct; ++i) {
int j, count, possible;
count = 0;
for (j = 0; j < usedsize; ++j)
if (table[j].errors == i)
++count;
possible = combinations(bits - 5, i);
fprintf(stderr, " %d entries for %d-bit errors (%d possible, %d%% coverage)\n", count, i, possible, 100 * count / possible);
}
fprintf(stderr, " %d entries total\n", usedsize);
}
#endif
return table;
}
// Precompute syndrome tables for 56- and 112-bit messages.
void modesChecksumInit(int fixBits) {
initLookupTables();
switch (fixBits) {
case 0:
bitErrorTable_short = bitErrorTable_long = NULL;
bitErrorTableSize_short = bitErrorTableSize_long = 0;
break;
case 1:
// For 1 bit correction, we have 100% coverage up to 4 bit detection, so don't bother
// with flagging collisions there.
bitErrorTable_short = prepareErrorTable(MODES_SHORT_MSG_BITS, 1, 1, &bitErrorTableSize_short);
bitErrorTable_long = prepareErrorTable(MODES_LONG_MSG_BITS, 1, 1, &bitErrorTableSize_long);
break;
default:
// Detect out to 4 bit errors; this reduces our 2-bit coverage to about 65%.
// This can take a little while - tell the user.
fprintf(stderr, "Preparing error correction tables.. ");
bitErrorTable_short = prepareErrorTable(MODES_SHORT_MSG_BITS, 2, 4, &bitErrorTableSize_short);
bitErrorTable_long = prepareErrorTable(MODES_LONG_MSG_BITS, 2, 4, &bitErrorTableSize_long);
fprintf(stderr, "done.\n");
break;
}
}
// Given an error syndrome and message length, return
// an error-correction descriptor, or NULL if the
// syndrome is uncorrectable
struct errorinfo *modesChecksumDiagnose(uint32_t syndrome, int bitlen) {
struct errorinfo *table;
int tablesize;
struct errorinfo ei;
if (syndrome == 0)
return &NO_ERRORS;
assert(bitlen == 56 || bitlen == 112);
if (bitlen == 56) {
table = bitErrorTable_short;
tablesize = bitErrorTableSize_short;
} else {
table = bitErrorTable_long;
tablesize = bitErrorTableSize_long;
}
if (!table)
return NULL;
ei.syndrome = syndrome;
return bsearch(&ei, table, tablesize, sizeof (struct errorinfo), syndrome_compare);
}
// Given a message and an error-correction descriptor,
// apply the error correction to the given message.
void modesChecksumFix(uint8_t *msg, struct errorinfo *info) {
int i;
if (!info)
return;
for (i = 0; i < info->errors; ++i)
msg[info->bit[i] >> 3] ^= 1 << (7 - (info->bit[i] & 7));
}
/*
* Clean CRC LUTs on exit.
*
*/
void crcCleanupTables(void) {
if (bitErrorTable_short != NULL)
free(bitErrorTable_short);
if (bitErrorTable_long != NULL)
free(bitErrorTable_long);
}
#ifdef CRCDEBUG
int main(int argc, char **argv) {
int shortlen, longlen;
int i;
struct errorinfo *shorttable, *longtable;
if (argc < 3) {
fprintf(stderr, "syntax: crctests \n");
return 1;
}
initLookupTables();
shorttable = prepareErrorTable(MODES_SHORT_MSG_BITS, atoi(argv[1]), atoi(argv[2]), &shortlen);
longtable = prepareErrorTable(MODES_LONG_MSG_BITS, atoi(argv[1]), atoi(argv[2]), &longlen);
// check for DF11 correction syndromes where there is a syndrome with lower 7 bits all zero
// (which would be used for DF11 error correction), but there's also a syndrome which has
// the same upper 17 bits but nonzero lower 7 bits.
// empirically, with ncorrect=1 ndetect=2 we get no ambiguous syndromes;
// for ncorrect=2 ndetect=4 we get 11 ambiguous syndromes:
/*
syndrome 1 = 000C00 bits=[ 44 45 ]
syndrome 2 = 000C1B bits=[ 30 43 ]
syndrome 1 = 001400 bits=[ 43 45 ]
syndrome 2 = 00141B bits=[ 30 44 ]
syndrome 1 = 001800 bits=[ 43 44 ]
syndrome 2 = 00181B bits=[ 30 45 ]
syndrome 1 = 001800 bits=[ 43 44 ]
syndrome 2 = 001836 bits=[ 29 42 ]
syndrome 1 = 002400 bits=[ 42 45 ]
syndrome 2 = 00242D bits=[ 29 30 ]
syndrome 1 = 002800 bits=[ 42 44 ]
syndrome 2 = 002836 bits=[ 29 43 ]
syndrome 1 = 003000 bits=[ 42 43 ]
syndrome 2 = 003036 bits=[ 29 44 ]
syndrome 1 = 003000 bits=[ 42 43 ]
syndrome 2 = 00306C bits=[ 28 41 ]
syndrome 1 = 004800 bits=[ 41 44 ]
syndrome 2 = 00485A bits=[ 28 29 ]
syndrome 1 = 005000 bits=[ 41 43 ]
syndrome 2 = 00506C bits=[ 28 42 ]
syndrome 1 = 006000 bits=[ 41 42 ]
syndrome 2 = 00606C bits=[ 28 43 ]
*/
// So in the DF11 correction logic, we just discard messages that require more than a 1 bit fix.
fprintf(stderr, "checking %d syndromes for DF11 collisions..\n", shortlen);
for (i = 0; i < shortlen; ++i) {
if ((shorttable[i].syndrome & 0xFF) == 0) {
int j;
// all syndromes with the same first 17 bits should sort immediately after entry i,
// so this is fairly easy
for (j = i + 1; j < shortlen; ++j) {
if ((shorttable[i].syndrome & 0xFFFF80) == (shorttable[j].syndrome & 0xFFFF80)) {
int k;
int mismatch = 0;
// we don't care if the only differences are in bits that lie in the checksum
for (k = 0; k < shorttable[i].errors; ++k) {
int l, matched = 0;
if (shorttable[i].bit[k] >= 49)
continue; // bit is in the final 7 bits, we don't care
for (l = 0; l < shorttable[j].errors; ++l) {
if (shorttable[i].bit[k] == shorttable[j].bit[l]) {
matched = 1;
break;
}
}
if (!matched)
mismatch = 1;
}
for (k = 0; k < shorttable[j].errors; ++k) {
int l, matched = 0;
if (shorttable[j].bit[k] >= 49)
continue; // bit is in the final 7 bits, we don't care
for (l = 0; l < shorttable[i].errors; ++l) {
if (shorttable[j].bit[k] == shorttable[i].bit[l]) {
matched = 1;
break;
}
}
if (!matched)
mismatch = 1;
}
if (mismatch) {
fprintf(stderr,
"DF11 correction collision: \n"
" syndrome 1 = %06X bits=[",
shorttable[i].syndrome);
for (k = 0; k < shorttable[i].errors; ++k)
fprintf(stderr, " %d", shorttable[i].bit[k]);
fprintf(stderr, " ]\n");
fprintf(stderr,
" syndrome 2 = %06X bits=[",
shorttable[j].syndrome);
for (k = 0; k < shorttable[j].errors; ++k)
fprintf(stderr, " %d", shorttable[j].bit[k]);
fprintf(stderr, " ]\n");
}
} else {
break;
}
}
}
}
free(shorttable);
free(longtable);
return 0;
}
#endif
readsb-3.16/crc.h 0000664 0000000 0000000 00000002742 15050573076 0013640 0 ustar 00root root 0000000 0000000 // Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// crc.h: Mode S checksum prototypes.
//
// Copyright (c) 2019 Michael Wolf
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014,2015 Oliver Jowett
//
// This file 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
// any later version.
//
// This file 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 .
#ifndef DUMP1090_CRC_H
#define DUMP1090_CRC_H
#include
// Global max for fixable bit erros
#define MODES_MAX_BITERRORS 2
struct errorinfo
{
uint32_t syndrome; // CRC syndrome
int errors; // number of errors
int8_t bit[MODES_MAX_BITERRORS]; // bit positions to fix (-1 = no bit)
uint16_t padding;
};
void modesChecksumInit (int fixBits);
uint32_t modesChecksum (uint8_t *msg, int bitlen);
struct errorinfo *modesChecksumDiagnose (uint32_t syndrome, int bitlen);
void modesChecksumFix (uint8_t *msg, struct errorinfo *info);
void crcCleanupTables (void);
#endif
readsb-3.16/debian/ 0000775 0000000 0000000 00000000000 15050573076 0014135 5 ustar 00root root 0000000 0000000 readsb-3.16/debian/README.librtlsdr 0000664 0000000 0000000 00000001616 15050573076 0017021 0 ustar 00root root 0000000 0000000 This package includes binaries that are statically linked against librtlsdr,
which is licensed under the GPL:
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The upstream source is available at https://github.com/steve-m/librtlsdr
readsb-3.16/debian/changelog 0000664 0000000 0000000 00000000344 15050573076 0016010 0 ustar 00root root 0000000 0000000 readsb (3.16) stable; urgency=medium
* debian: cleanup package build / service file
* debian: autogenerate manpage during build using help2man
-- Matthias Wirth Mon, 18 Aug 2025 09:00:00 +0000
readsb-3.16/debian/compat 0000664 0000000 0000000 00000000002 15050573076 0015333 0 ustar 00root root 0000000 0000000 10 readsb-3.16/debian/control 0000664 0000000 0000000 00000002305 15050573076 0015540 0 ustar 00root root 0000000 0000000 Source: readsb
Section: net
Priority: optional
Maintainer: Matthias Wirth
Build-Depends: debhelper(>=9), libncurses-dev, zlib1g-dev, pkg-config, libzstd-dev, help2man,
libusb-1.0-0-dev ,
librtlsdr-dev ,
libsoapysdr-dev ,
libhackrf-dev ,
libbladerf-dev