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

## Building
Download the repository and invoke `make` (`make release` for optimized build - *reccomended* when you want to use it properly and not degbugging/experimenting with it).
Please note you need to have some dependencies satisfied (see following).
### libpcap
nettop relies on *libpacap* to intercept all packets and deliver a copy to the application. On Ubuntu and Debian derivatives you should install the *-dev* version (i.e. `sudo apt install libpcap-dev`).
### ncurses
nettop relies on *ncurses* to facilitate the UI drawing on console; on Ubuntu-like systems please install `libncurses5-dev` or more recent to allow compiling.
## Running
### All commands
```
Usage: ./nettop [options]
Executes nettop 0.5
-r, --refresh s sets the refresh rate in 's' seconds (default 3)
-c, --capture (a|s|r) Capture mode for 'a'll, 's'end and 'r'ecv only (default 'a')
-o, --order (a|d) Ordering of results, 'a'scending, 'd'escending (default 'd')
--filter-zero Set to filter all zero results (default not set)
--tcp-udp-split Displays split of TCP and UDP traffic in % (default not set)
-n, --no-resolve Do not resolve addresses, leave IPs to be displayed
-a, --async-log-file (file) Sets an output file where to store the packets attribued to the 'kernel' (default not set)
-l, --limit-hosts-rows Limits maximum number of hosts rows per pid (default no limit)
--help prints this help and exit
Press 'q' or 'ESC' inside nettop to quit, 'SPACE' or 'p' to pause nettop
```
### Sample usage
```
sudo ./nettop --tcp-udp-split --limit-hosts-rows 20
```
This will start nettop and split between TCP and UDP usage, limiting how many hosts to display by the topmost 20.
### *sudo* requirements
Please note nettop needs to have *root* privileges to intercept all packets incoming and outgoing from current computer. Without *root* access it's unlikely to run.
## F.A.Q.
### Why did you build this?
I wanted to have a simple utility to monitor the network usage of all my processes, especially trying to understand where my data was coming from and going to.
I couldn't find anything which would just do this out of the box, so I wrote a utility.
### Is it safe to run as *root*?
I would think so - anyhow, look at the sources. If you don't trust what I'm doing, download the repo, inspect the code, compile, play around and let me know!
### what are the *5* numbers between brackets on top left?
They do represent the following:
- Total packets intercepted by libpcap (not only TCP and UDP, but potentially other IP types and non IP - rare these days)
- Total packets which were not processed by nettop (i.e. all the non TCP nor UDP packets)
- Undetermined packets - i.e. packets sent *from* **and** *to* the local computer (i.e. not touching the network *card*s), or also when packets have got both remote sources and destinations (i.e. applications spoofing IP address?)
- Total unmapped received packets: nettop could not attribute these packets to any current *PID*, hence it will assing them to *PID* 0. This might be due to the fact that for current interval we took a *snapshot* of running processes after parsing the packets, hence we could not link the *PID*s - or also, when you use APIs such as *gethostbyname*, the kernel will resolve and use the network for you, hence PID 0.
- Total unmapped sent packets; as above but for sent packets
## Credits
Thanks to Linux for being open source and to:
- [libpcap](https://sourceforge.net/projects/libpcap/) For providing this awesome tool to intercept packets host wide
- [ncurses](https://en.wikipedia.org/wiki/Ncurses) Without whom I wouldn't be able to draw a single element on the screen without *pain and agony*!
================================================
FILE: src/addr_t.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _ADDR_T_H_
#define _ADDR_T_H_
#include <netdb.h>
#include <cstring>
#include <string>
class addr_t {
typedef union {
in_addr ipv4;
in6_addr ipv6;
} ip_data;
int af_type_;
ip_data ip_data_;
static ip_data get_ip4_data(const void* b) {
ip_data ret;
ret.ipv4 = *(in_addr*)b;
return ret;
}
static ip_data get_ip6_data(const void* b) {
ip_data ret;
ret.ipv6 = *(in6_addr*)b;
return ret;
}
public:
addr_t() : af_type_(0) {
std::memset(&ip_data_, 0x00, sizeof(ip_data));
}
addr_t(const int af_type) : af_type_(af_type) {
std::memset(&ip_data_, 0x00, sizeof(ip_data));
switch(af_type_) {
case AF_INET:
ip_data_.ipv4.s_addr = INADDR_ANY;
break;
case AF_INET6:
ip_data_.ipv6 = IN6ADDR_ANY_INIT;
break;
}
}
addr_t(const in_addr& ipv4) : af_type_(AF_INET), ip_data_(get_ip4_data(&ipv4)) {
}
addr_t(const in6_addr& ipv6) : af_type_(AF_INET6), ip_data_(get_ip6_data(&ipv6)) {
}
addr_t(const addr_t& rhs) : af_type_(rhs.af_type_), ip_data_(rhs.ip_data_) {
}
int get_af_type(void) const {
return af_type_;
}
addr_t& operator=(const addr_t& rhs) {
if(this != &rhs) {
af_type_ = rhs.af_type_;
ip_data_ = rhs.ip_data_;
}
return *this;
}
inline bool is_ipv6(void) const {
return af_type_ == AF_INET6;
}
std::string to_str(const bool full_name = false, const int rec_calls = 0) const {
const int gni_flags = (full_name) ? 0 : NI_NUMERICHOST;
if(af_type_ == AF_INET) {
struct sockaddr_in in;
in.sin_family = AF_INET;
in.sin_port = 123;
in.sin_addr = ip_data_.ipv4;
char hbuf[NI_MAXHOST];
if(const int rv = getnameinfo((const sockaddr*)&in, sizeof(struct sockaddr_in), hbuf, sizeof(hbuf), 0, 0, gni_flags)) {
if(rec_calls > 1)
return "<invalid host>";
if(EAI_AGAIN == rv)
return to_str(false, rec_calls+1);
}
return hbuf;
}
struct sockaddr_in6 in;
in.sin6_family = AF_INET6;
in.sin6_port = 123;
in.sin6_flowinfo = 0;
in.sin6_addr = ip_data_.ipv6;
in.sin6_scope_id = 0;
char hbuf[NI_MAXHOST];
if(const int rv = getnameinfo((const sockaddr*)&in, sizeof(struct sockaddr_in6), hbuf, sizeof(hbuf), 0, 0, gni_flags)) {
if(rec_calls > 1)
return "<invalid host>";
if(EAI_AGAIN == rv)
return to_str(false, rec_calls+1);
}
return hbuf;
}
friend bool operator==(const addr_t& lhs, const addr_t& rhs);
friend bool operator<(const addr_t& lhs, const addr_t& rhs);
};
inline bool operator==(const addr_t& lhs, const addr_t& rhs) {
if(lhs.af_type_ == rhs.af_type_) {
if(lhs.af_type_ == AF_INET) {
return lhs.ip_data_.ipv4.s_addr == rhs.ip_data_.ipv4.s_addr;
}
return !std::memcmp(&lhs.ip_data_.ipv6, &rhs.ip_data_.ipv6, sizeof(in6_addr));
}
return false;
}
inline bool operator<(const addr_t& lhs, const addr_t& rhs) {
if(lhs.af_type_ == rhs.af_type_) {
if(lhs.af_type_ == AF_INET) {
return lhs.ip_data_.ipv4.s_addr < rhs.ip_data_.ipv4.s_addr;
}
return std::memcmp(&lhs.ip_data_.ipv6, &rhs.ip_data_.ipv6, sizeof(in6_addr)) < 0;
}
return lhs.af_type_ < rhs.af_type_;
}
#endif //_ADDR_T_H_
================================================
FILE: src/async_log.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include "async_log.h"
#include <fstream>
#include <thread>
#include <ctime>
#include "utils.h"
void nettop::async_log::thread_proc(void) {
while(!exit_) {
// sleep for a bit
std::this_thread::sleep_for(std::chrono::milliseconds(250));
// get the current list
std::list<sp_async_line> cur_list;
list_.swap(cur_list);
if (!*ostr_)
continue;
for(const auto& i : cur_list) {
const std::time_t now_c = std::chrono::system_clock::to_time_t(i->get_tp());
const size_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(i->get_tp().time_since_epoch()).count()%1000;
std::tm now_tm;
localtime_r(&now_c, &now_tm);
char tm_str[64];
std::strftime(tm_str, 128, "%Y-%m-%d %H:%M:%S.%%03d", &now_tm);
char tm_full_str[64];
std::snprintf(tm_full_str, 64, tm_str, now_ms);
(*ostr_) << tm_full_str << " " << i->log(nr_) << std::endl;
}
}
}
nettop::async_log::async_log(volatile bool& e, name_res& nr, const std::string& fname, nettop::async_log_list& list) : exit_(e), nr_(nr), ostr_(new std::ofstream(fname.c_str(), std::ios_base::app)), list_(list) {
if(!fname.empty()) {
if(!*ostr_)
throw runtime_error("Can't open file \"") << fname << "\" to write async_log";
(*ostr_) << "Log opened/appended" << std::endl;
}
thrd_ = std::shared_ptr<std::thread>(new std::thread(&async_log::thread_proc, this));
}
nettop::async_log::~async_log() {
if(thrd_)
thrd_->join();
}
================================================
FILE: src/async_log.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _ASYNC_LOG_H_
#define _ASYNC_LOG_H_
#include "mt_list.h"
#include <memory>
#include <chrono>
#include <string>
#include <fstream>
#include <thread>
#include "name_res.h"
namespace nettop {
class async_line {
const std::chrono::system_clock::time_point tp_;
async_line(const async_line&) = delete;
async_line& operator=(const async_line&) = delete;
public:
async_line() : tp_(std::chrono::system_clock::now()) {
}
const std::chrono::system_clock::time_point& get_tp(void) {
return tp_;
}
virtual std::string log(name_res& nr) const = 0;
virtual ~async_line() {
};
};
typedef std::shared_ptr<async_line> sp_async_line;
typedef mt_list<sp_async_line> async_log_list;
class async_log {
async_log(const async_log&) = delete;
async_log& operator=(const async_log&) = delete;
volatile bool& exit_;
name_res& nr_;
std::shared_ptr<std::ostream> ostr_;
async_log_list& list_;
std::shared_ptr<std::thread> thrd_;
void thread_proc(void);
public:
async_log(volatile bool& e, name_res& nr, const std::string& fname, async_log_list& list);
~async_log();
};
}
#endif //_ASYNC_LOG_H_
================================================
FILE: src/cap_mgr.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cap_mgr.h"
#include "utils.h"
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <chrono>
#include <thread>
#include <atomic>
#include "addr_t.h"
namespace {
typedef std::list<nettop::packet_stats> st_pkt_list;
// linux cooked header
// glanced from libpcap/ssl.h
#define SLL_ADDRLEN (8) /* length of address field */
#define SLL_PROTOCOL_IP (0x0008)
#define SLL_PROTOCOL_IP6 (0xDD86)
struct sll_header {
u_int16_t sll_pkttype; /* packet type */
u_int16_t sll_hatype; /* link-layer address type */
u_int16_t sll_halen; /* link-layer address length */
u_int8_t sll_addr[SLL_ADDRLEN]; /* link-layer address */
u_int16_t sll_protocol; /* protocol */
};
inline void process_tcp(const u_char *data, st_pkt_list& p_list, const double ts, const size_t len, const addr_t& src, const addr_t& dst) {
const struct tcphdr *tcp = (struct tcphdr*)data;
const uint16_t p_src = ntohs(tcp->source),
p_dst = ntohs(tcp->dest);
p_list.push_back(nettop::packet_stats(src, dst, p_src, p_dst, len, nettop::packet_stats::type::PACKET_TCP, ts));
}
inline void process_udp(const u_char *data, st_pkt_list& p_list, const double ts, const size_t len, const addr_t& src, const addr_t& dst) {
const struct udphdr *udp = (struct udphdr*)data;
const uint16_t p_src = ntohs(udp->source),
p_dst = ntohs(udp->dest);
p_list.push_back(nettop::packet_stats(src, dst, p_src, p_dst, len, nettop::packet_stats::type::PACKET_UDP, ts));
}
inline void process_ip(const u_char *data, st_pkt_list& p_list, const double ts, const size_t len) {
const struct ip *ip = (struct ip*)data;
const addr_t src(ip->ip_src),
dst(ip->ip_dst);
switch(ip->ip_p) {
case IPPROTO_TCP:
process_tcp(data + sizeof(struct ip), p_list, ts, len, src, dst);
break;
case IPPROTO_UDP:
process_udp(data + sizeof(struct ip), p_list, ts, len, src, dst);
break;
default:
//std::cerr << "Unknown ip protocol " << (int)ip->ip_p << ", skipping packet" << std::endl;
break;
}
}
inline void process_ip6(const u_char *data, st_pkt_list& p_list, const double ts, const size_t len) {
const struct ip6_hdr *ip6 = (struct ip6_hdr*)data;
const addr_t src(ip6->ip6_src),
dst(ip6->ip6_dst);
switch(ip6->ip6_nxt) {
case IPPROTO_TCP:
process_tcp(data + sizeof(struct ip6_hdr), p_list, ts, len, src, dst);
break;
case IPPROTO_UDP:
process_udp(data + sizeof(struct ip6_hdr), p_list, ts, len, src, dst);
break;
default:
//std::cerr << "Unknown ip protocol " << (int)ip6->ip6_nxt << ", skipping packet" << std::endl;
break;
}
}
void p_handler(u_char *user, const struct pcap_pkthdr *header, const u_char *data) {
const struct sll_header *sll = (struct sll_header*)data;
st_pkt_list& p_list = *(st_pkt_list*)user;
const double ts = nettop::tv_to_sec(header->ts);
switch(sll->sll_protocol) {
case SLL_PROTOCOL_IP:
process_ip(data + sizeof(struct sll_header), p_list, ts, header->len);
break;
case SLL_PROTOCOL_IP6:
process_ip6(data + sizeof(struct sll_header), p_list, ts, header->len);
break;
default:
//std::cerr << "Unknown SLL protocol " << (int)sll->sll_protocol << ", skipping packet" << std::endl;
break;
}
}
}
nettop::cap_mgr::cap_mgr() : p_(0) {
// open all network devices
char err[PCAP_ERRBUF_SIZE+1];
p_ = pcap_open_live(NULL, BUFSIZ, 0, 250, err);
if(!p_)
throw runtime_error(err);
// only support Linux Cooked Socket link!
const int link_type = pcap_datalink(p_);
if(DLT_LINUX_SLL != link_type) {
pcap_close(p_);
throw runtime_error("Link type: ") << link_type << ", only DLT_LINUX_SLL (" << DLT_LINUX_SLL << ") supported!";
}
}
nettop::cap_mgr::~cap_mgr() {
pcap_close(p_);
}
void nettop::cap_mgr::capture_dispatch(packet_list& p_list) {
st_pkt_list lcl_list;
const int dres = pcap_dispatch(p_, -1, p_handler, (u_char*)&lcl_list);
// we never call pcap_breakloop
if(-1 == dres)
throw runtime_error(pcap_geterr(p_));
p_list.push_many(lcl_list);
p_list.total_pkts += dres;
}
void nettop::cap_mgr::async_cap(packet_list& p_list, volatile bool& quit) {
while(!quit) {
capture_dispatch(p_list);
}
}
================================================
FILE: src/cap_mgr.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CAP_MGR_H_
#define _CAP_MGR_H_
#include <pcap.h>
#include <atomic>
#include "mt_list.h"
#include "packet_stats.h"
namespace nettop {
struct packet_list : public mt_list<packet_stats> {
std::atomic<size_t> total_pkts;
packet_list() : total_pkts(0) {
}
};
class cap_mgr {
cap_mgr(const cap_mgr&) = delete;
cap_mgr& operator=(const cap_mgr&) = delete;
pcap_t *p_;
public:
cap_mgr();
~cap_mgr();
void capture_dispatch(packet_list& p_list);
void async_cap(packet_list& p_list, volatile bool& quit);
};
}
#endif //_CAP_MGR_H_
================================================
FILE: src/epoll_stdin.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _EPOLL_STDIN_
#define _EPOLL_STDIN_
#include <sys/epoll.h>
#include <unistd.h>
#include "utils.h"
namespace utils {
class epoll_stdin {
int efd_;
public:
epoll_stdin() : efd_(epoll_create1(0)) {
if(-1 == efd_)
throw nettop::runtime_error("Can't created epoll fd: ") << strerror(errno);
// add stdin
struct epoll_event event = {0};
event.events = EPOLLIN|EPOLLPRI|EPOLLERR;
event.data.fd = STDIN_FILENO;
if(epoll_ctl(efd_, EPOLL_CTL_ADD, STDIN_FILENO, &event)) {
close(efd_);
throw nettop::runtime_error("Can't add STDIN to epoll fd: ") << strerror(errno);
}
}
// return true when need to do a refresh
bool do_io(const size_t msec_tmout) {
struct epoll_event event = {0};
const int fds = epoll_wait(efd_, &event, 1, msec_tmout);
if(0 == fds) return false;
else if (0 > fds) {
if(EINTR == errno)
return false;
throw nettop::runtime_error("Error in epoll_wait: ") << strerror(errno);
}
// we can only get 1 event at max...
if (event.data.fd == STDIN_FILENO) {
char buf[128];
// read input line
const int rb = read(STDIN_FILENO, &buf, 128);
if(rb > 0) {
return on_data(buf, rb);
} else throw nettop::runtime_error("Error in reading STDIN: ") << strerror(errno);
}
return false;
}
virtual bool on_data(const char* p, const size_t sz) const = 0;
virtual ~epoll_stdin() {
close(efd_);
}
};
}
#endif //_EPOLL_STDIN_
================================================
FILE: src/gpl_v3
================================================
/*
* nettop (C) 2014 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
================================================
FILE: src/main.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <chrono>
#include <thread>
#include <algorithm>
#include <curses.h>
#include <csignal>
#include "utils.h"
#include "cap_mgr.h"
#include "proc.h"
#include "name_res.h"
#include "settings.h"
#include "epoll_stdin.h"
namespace {
volatile bool quit = false,
skip_sleep_time = true,
paused = false;
void sign_onexit(int param) {
quit = true;
}
const char* __version__ = "0.5";
struct ps_sorted_iter {
nettop::ps_vec::const_iterator it_p_vec;
std::vector<nettop::proc_stats::addr_st_map::const_iterator> v_it_addr;
ps_sorted_iter(nettop::ps_vec::const_iterator it_p_vec_) : it_p_vec(it_p_vec_) {
}
};
typedef std::vector<std::shared_ptr<ps_sorted_iter> > sorted_p_vec;
void sort_filter_data(const nettop::ps_vec& p_vec, sorted_p_vec& out) {
// copy the iterators into output vector
out.resize(0);
out.reserve(p_vec.size());
for(nettop::ps_vec::const_iterator it = p_vec.begin(); it != p_vec.end(); ++it) {
std::shared_ptr<ps_sorted_iter> el(new ps_sorted_iter(it));
el->v_it_addr.reserve(it->addr_rs_map.size());
for(nettop::proc_stats::addr_st_map::const_iterator it_m = it->addr_rs_map.begin(); it_m != it->addr_rs_map.end(); ++it_m)
el->v_it_addr.push_back(it_m);
out.push_back(el);
}
// filter data if needed
if(nettop::settings::FILTER_ZERO) {
sorted_p_vec::iterator it_erase = std::remove_if(out.begin(), out.end(), [](const std::shared_ptr<ps_sorted_iter>& ps){ return (ps->it_p_vec->total_rs.first + ps->it_p_vec->total_rs.second) == 0; });
out.erase(it_erase, out.end());
}
// sort it (external)
struct sort_fctr {
bool operator()(const std::shared_ptr<ps_sorted_iter>& lhs, const std::shared_ptr<ps_sorted_iter>& rhs) {
const size_t lhs_sz = lhs->it_p_vec->total_rs.first + lhs->it_p_vec->total_rs.second,
rhs_sz = rhs->it_p_vec->total_rs.first + rhs->it_p_vec->total_rs.second;
return (nettop::settings::ORDER_TOP) ? lhs_sz > rhs_sz : lhs_sz < rhs_sz;
}
};
std::sort(out.begin(), out.end(), sort_fctr());
// sort it (internal)
struct sort_fctr_int {
bool operator()(const nettop::proc_stats::addr_st_map::const_iterator& lhs, const nettop::proc_stats::addr_st_map::const_iterator& rhs) {
const size_t lhs_sz = lhs->second.recv + lhs->second.sent,
rhs_sz = rhs->second.recv + rhs->second.sent;
return (nettop::settings::ORDER_TOP) ? lhs_sz > rhs_sz : lhs_sz < rhs_sz;
}
};
for(auto& i : out) {
std::sort(i->v_it_addr.begin(), i->v_it_addr.end(), sort_fctr_int());
}
}
class curses_setup {
WINDOW *w_;
nettop::name_res& nr_;
const size_t limit_hosts_;
static char BPS[],
KBPS[],
MBPS[],
GBPS[];
static void recv_send_format(const std::chrono::nanoseconds& tm_elapsed, const size_t recv, const size_t sent, double& recv_d, double& sent_d, const char* & fmt) {
const double tm_fct = 1000000000.0/tm_elapsed.count();
const size_t max_bytes = tm_fct*((recv > sent) ? recv : sent);
if(max_bytes >= 1024*1024*1024) {
const double cnv_fct = 1.0/(1024.0*1024.0*1024.0);
recv_d = cnv_fct*recv*tm_fct;
sent_d = cnv_fct*sent*tm_fct;
fmt = GBPS;
} else if(max_bytes >= 1024*1024) {
const double cnv_fct = 1.0/(1024.0*1024.0);
recv_d = cnv_fct*recv*tm_fct;
sent_d = cnv_fct*sent*tm_fct;
fmt = MBPS;
} else if(max_bytes >= 1024) {
const double cnv_fct = 1.0/1024.0;
recv_d = cnv_fct*recv*tm_fct;
sent_d = cnv_fct*sent*tm_fct;
fmt = KBPS;
} else {
recv_d = tm_fct*recv;
sent_d = tm_fct*sent;
fmt = BPS;
}
}
public:
curses_setup(nettop::name_res& nr, const size_t limit_hosts = 0) : w_(initscr()), nr_(nr), limit_hosts_(limit_hosts) {
}
~curses_setup() {
endwin();
}
void draw_paused(void) {
int row = 0; // number of terminal rows
int col = 0; // number of terminal columns
getmaxyx(stdscr, row, col); /* find the boundaries of the screeen */
if(col < 60 || row < 5) {
refresh();
return;
}
static const char PAUSED[] = "--- PAUSED ---";
const size_t p_offset = (col - std::strlen(PAUSED))/2;
attron(A_BOLD);
mvprintw(1, p_offset, "%s", PAUSED);
attroff(A_BOLD);
refresh();
}
void redraw(const std::chrono::nanoseconds& tm_elapsed, const sorted_p_vec& s_v, const size_t total_pkts, const nettop::proc_mgr::stats& st) {
clear();
int row = 0; // number of terminal rows
int col = 0; // number of terminal columns
getmaxyx(stdscr, row, col); /* find the boundaries of the screeen */
// UI coordinates:
// 6 2 23 2 9 2 9 2 5
// PIDXXX cmdlineXXXXXXXXXXXXXXXX recvXXXXX sentXXXXX KiB/s
if(col < 60 || row < 5) {
mvprintw(0, 0, "Need at least a screen of 60x5 (%d/%d)", col, row);
refresh();
return;
}
const size_t cmdline_len = col - (6+2+9+2+9+2+6+3);
int cur_row = 2;
size_t tot_recv = 0,
tot_sent = 0;
// print header
attron(A_REVERSE);
mvprintw(cur_row++, 0, "%-6s %-*s %-9s %-9s ", "PID", cmdline_len, "CMDLINE", "RECV", "SENT");
attroff(A_REVERSE);
// print each entity
for(const auto& sp_i : s_v) {
// print each process row
const auto& i = *(sp_i->it_p_vec);
std::string r_cmd = i.cmd; r_cmd.resize(cmdline_len);
double r_d = 0.0,
s_d = 0.0;
const char* fmt = "";
recv_send_format(tm_elapsed, i.total_rs.first, i.total_rs.second, r_d, s_d, fmt);
tot_recv += i.total_rs.first;
tot_sent += i.total_rs.second;
// if we don't have more UI space, don't bother printing this row..
if(cur_row >= row-1)
continue;
attron(A_BOLD);
mvprintw(cur_row++, 0, "%6d %-*s %10.2f %10.2f %-5s", i.pid, cmdline_len, r_cmd.c_str(), r_d, s_d, fmt);
attroff(A_BOLD);
// print each server txn
size_t cur_hosts = 0;
for(const auto& sp_j : sp_i->v_it_addr) {
if(limit_hosts_ && cur_hosts >= limit_hosts_) {
attron(A_DIM);
mvprintw(cur_row++, 0, " ...");
attroff(A_DIM);
break;
}
const auto& j = *sp_j;
const size_t host_line = cmdline_len-3,
tot_t = j.second.udp_t + j.second.tcp_t,
udp_p = (tot_t) ? 100.0*j.second.udp_t/(j.second.udp_t + j.second.tcp_t) : 0,
tcp_p = (tot_t) ? 100 - udp_p : 0;
char tcp_udp_buf[32] = "[ na/ na] ";
if(tot_t) {
std::snprintf(tcp_udp_buf, 32, "[%3lu/%3lu] ", tcp_p, udp_p);
}
char buf[256];
std::snprintf(buf, 256, "%s%s", (nettop::settings::TCP_UDP_TRAFFIC) ? tcp_udp_buf : "", nr_.to_str(j.first).c_str());
std::string r_host = buf; r_host.resize(host_line);
recv_send_format(tm_elapsed, j.second.recv, j.second.sent, r_d, s_d, fmt);
attron(A_DIM);
mvprintw(cur_row++, 0, " %-*s %10.2f %10.2f %-5s", host_line, r_host.c_str(), r_d, s_d, fmt);
attroff(A_DIM);
++cur_hosts;
}
}
// print the totals and header
double r_d = 0.0,
s_d = 0.0;
const char* fmt = "";
recv_send_format(tm_elapsed, tot_recv, tot_sent, r_d, s_d, fmt);
char total_buf[128];
snprintf(total_buf, 128, "%s [%5.2fs (%5lu/%5lu/%5lu/%5lu/%5lu)]",
__version__, 1.0*tm_elapsed.count()/1000000000.0, st.total_pkts, st.total_pkts-st.proc_pkts, st.undet_pkts, st.unmap_r_pkts, st.unmap_s_pkts);
mvprintw(0, 0, "nettop %-*s", cmdline_len-6, total_buf);
mvprintw(0, cmdline_len+1, " Total %10.2f %10.2f %-5s", r_d, s_d, fmt);
refresh();
}
};
char curses_setup::BPS[] = "Byte/s",
curses_setup::KBPS[] = "KiB/s ",
curses_setup::MBPS[] = "MiB/s ",
curses_setup::GBPS[] = "GiB/s ";
struct stdin_exit : public utils::epoll_stdin {
virtual bool on_data(const char* p, const size_t sz) const {
for(size_t i = 0; i < sz; ++i) {
switch(p[i]) {
case 27: // ESC key
case 'q':
quit = true;
break;
case ' ':
case 'p':
paused = !paused;
return true; // do refresh after this!
break;
default:
break;
}
}
return false;
}
};
struct auto_quit {
auto_quit() {}
~auto_quit() { quit = true; }
};
}
int main(int argc, char *argv[]) {
try {
using namespace std::chrono;
// setup signal functions
std::signal(SIGINT, sign_onexit);
std::signal(SIGTERM, sign_onexit);
// parse settings and params
nettop::parse_args(argc, argv, argv[0], __version__);
nettop::packet_list p_list;
nettop::cap_mgr c;
nettop::local_addr_mgr lam;
nettop::async_log_list log_list;
nettop::name_res nr(quit, nettop::settings::NO_RESOLVE);
nettop::async_log al(quit, nr, nettop::settings::ASYNC_LOG_FILE, log_list);
// create cap thread
std::thread cap_th(&nettop::cap_mgr::async_cap, &c, std::ref(p_list), std::ref(quit));
cap_th.detach();
// init curses
curses_setup c_window(nr, nettop::settings::LIMIT_HOSTS_ROWS);
system_clock::time_point latest_time = std::chrono::system_clock::now();
// initi epoll_stdin
stdin_exit ep_exit;
// automatically set quit to true when
// exiting this scope
auto_quit aq_;
while(!quit) {
// initialize all required structures and the processes too
nettop::proc_mgr p_mgr;
nettop::proc_mgr::stats mgr_st;
nettop::ps_vec p_vec;
// wait for some time
if(skip_sleep_time) {
skip_sleep_time = false;
} else {
size_t total_msec_slept = 0;
while(!quit && !skip_sleep_time) {
const size_t sleep_interval = 250;
if(ep_exit.do_io(sleep_interval))
break;
total_msec_slept += sleep_interval;
if(nettop::settings::REFRESH_SECS <= total_msec_slept/1000)
break;
}
}
// bind to known processes
const system_clock::time_point cur_time = std::chrono::system_clock::now();
// bind to local list and stats
std::list<nettop::packet_stats> ps_list;
p_list.swap(ps_list);
mgr_st.total_pkts = p_list.total_pkts.exchange(0);
// get new packets (for the real total counter, we are using an atomic type)
// _mostly_ accurate
if(!paused) {
// bind to known processes
p_mgr.bind_packets(ps_list, lam, p_vec, mgr_st, log_list);
// sort
sorted_p_vec s_v;
sort_filter_data(p_vec, s_v);
// redraw now
c_window.redraw(cur_time - latest_time, s_v, ps_list.size(), mgr_st);
} else {
c_window.draw_paused();
}
// set latest time
latest_time = cur_time;
}
} catch(const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
} catch(...) {
std::cerr << "Unknown exception" << std::endl;
}
}
================================================
FILE: src/mt_list.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MT_LIST_H_
#define _MT_LIST_H_
#include <mutex>
#include <list>
#include <algorithm>
template<typename T>
class mt_list {
mt_list(const mt_list&) = delete;
mt_list& operator=(const mt_list&) = delete;
std::mutex mtx_;
std::list<T> list_;
public:
mt_list() {}
~mt_list() {}
void push(const T& in) {
std::lock_guard<std::mutex> lg(mtx_);
list_.push_back(in);
}
void push_many(const std::list<T>& in) {
std::lock_guard<std::mutex> lg(mtx_);
std::for_each(in.begin(), in.end(), [&](const T& t){ list_.push_back(t); });
}
void swap(std::list<T>& out) {
std::lock_guard<std::mutex> lg(mtx_);
list_.swap(out);
}
};
#endif //_MT_LIST_H_
================================================
FILE: src/name_res.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include <memory>
#include "name_res.h"
void nettop::name_res::thread_proc(void) {
while(!exit_) {
std::list<addr_t> lcl_list;
list_.swap(lcl_list);
for(const auto& i : lcl_list) {
const std::string full_nm = i.to_str(true);
// add into the map
{
std::lock_guard<std::mutex> lg(mtx_);
addr_map_[i] = full_nm;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
nettop::name_res::name_res(volatile bool& e, bool do_not_resolve) : exit_(e) {
thrd_ = std::shared_ptr<std::thread>(do_not_resolve ? 0 : new std::thread(&name_res::thread_proc, this));
}
std::string nettop::name_res::to_str(const addr_t& in) {
// if we don't have a running thread
// just return the IP address
if (!thrd_)
return in.to_str();
// try to find if we have it
std::lock_guard<std::mutex> lg(mtx_);
auto it = addr_map_.find(in);
if(addr_map_.end() == it) {
const std::string nm = in.to_str();
addr_map_[in] = nm;
list_.push(in);
return nm;
}
return it->second;
}
nettop::name_res::~name_res() {
if(thrd_)
thrd_->join();
}
================================================
FILE: src/name_res.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _NAME_RES_H_
#define _NAME_RES_H_
#include "addr_t.h"
#include "mt_list.h"
#include <thread>
#include <string>
#include <mutex>
#include <map>
namespace nettop {
typedef mt_list<addr_t> async_addr_list;
class name_res {
name_res(const name_res&) = delete;
name_res& operator=(const name_res&) = delete;
volatile bool& exit_;
async_addr_list list_;
std::shared_ptr<std::thread> thrd_;
std::mutex mtx_;
std::map<addr_t, std::string> addr_map_;
void thread_proc(void);
public:
name_res(volatile bool& e, bool do_not_resolve);
std::string to_str(const addr_t& in);
~name_res();
};
}
#endif //_NAME_RES_H_
================================================
FILE: src/packet_stats.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include "packet_stats.h"
#include <algorithm>
#include <ifaddrs.h>
#include <list>
#include "utils.h"
nettop::local_addr_mgr::local_addr_mgr() {
struct ifaddrs *ifaddr = 0,
*ifa = 0;
int n = 0;
if(-1 == getifaddrs(&ifaddr))
throw runtime_error("Failure in getifaddrs");
for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
if (ifa->ifa_addr == NULL)
continue;
const int family = ifa->ifa_addr->sa_family;
if (family == AF_INET) {
const struct sockaddr_in *sa = (struct sockaddr_in*)ifa->ifa_addr;
local_addrs_.insert(addr_t(sa->sin_addr));
} else if(family == AF_INET6) {
const struct sockaddr_in6 *sa = (struct sockaddr_in6*)ifa->ifa_addr;
local_addrs_.insert(addr_t(sa->sin6_addr));
}
}
freeifaddrs(ifaddr);
}
bool nettop::local_addr_mgr::is_local(const addr_t& in) const {
return local_addrs_.find(in) != local_addrs_.end();
}
================================================
FILE: src/packet_stats.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PACKET_STATS_H_
#define _PACKET_STATS_H_
#include "addr_t.h"
#include <set>
namespace nettop {
class packet_stats {
packet_stats& operator=(const packet_stats&) = delete;
public:
enum type {
PACKET_TCP = 0,
PACKET_UDP
};
const addr_t src,
dst;
const uint16_t p_src,
p_dst;
const size_t len;
const enum type t;
const double ts;
packet_stats(const addr_t& src_, const addr_t& dst_, const uint16_t p_src_, const uint16_t p_dst_, const size_t len_, const enum type t_, const double ts_) : src(src_), dst(dst_), p_src(p_src_), p_dst(p_dst_), len(len_), t(t_), ts(ts_) {
}
packet_stats(const packet_stats& rhs) : src(rhs.src), dst(rhs.dst), p_src(rhs.p_src), p_dst(rhs.p_dst), len(rhs.len), t(rhs.t), ts(rhs.ts) {
}
};
class local_addr_mgr {
std::set<addr_t> local_addrs_;
public:
local_addr_mgr();
bool is_local(const addr_t& in) const;
};
}
#endif //_PACKET_STATS_H_
================================================
FILE: src/proc.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include "proc.h"
#include "utils.h"
#include "settings.h"
#include <algorithm>
#include <dirent.h>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <map>
#include <set>
#include <sstream>
namespace {
/* Parses /proc/<pid>/cmdline */
std::string get_cmd_line(const pid_t pid) {
char cur_fd[64];
std::snprintf(cur_fd, 64, "/proc/%i/cmdline", pid);
// need to use C APIs...
int fd = open(cur_fd, O_RDONLY);
if(-1 == fd)
return "(no cmd line)";
char buf[1024] = "";
const int rb = read(fd, buf, 1024);
if(rb >= 0) {
const size_t max_rb = (1024 > rb) ? rb : 1024;
for(size_t i = 0; i < max_rb; ++i) {
if(buf[i] == '\0')
buf[i] = ' ';
}
buf[max_rb-1] = '\0';
}
close(fd);
return buf;
}
typedef std::vector<unsigned long> v_inodes;
// get the inodes for sockets only
void get_sockets_inodes(const pid_t pid, v_inodes& out) {
char cur_fd[64];
std::snprintf(cur_fd, 64, "/proc/%i/fd", pid);
DIR* dir = opendir(cur_fd);
if(!dir)
return;
for(struct dirent *entry = readdir(dir); entry; entry = readdir(dir)) {
// skip . and ..
if(!std::strcmp(entry->d_name, ".") || !std::strcmp(entry->d_name, ".."))
continue;
// we're not interested in directories
if (entry->d_type == DT_DIR)
continue;
// prepare and read the sym link
char cur_sd[128],
buf_sd[128];
std::snprintf(cur_sd, 128, "/proc/%i/fd/%s", pid, entry->d_name);
const size_t rb = readlink(cur_sd, buf_sd, 128);
if(rb >= 128)
buf_sd[127] = '\0';
// check if it's a socket or not
unsigned long inode = 0;
if(1 != std::sscanf(buf_sd, "socket:[%ld]", &inode))
continue;
// else add it ot the vector
out.push_back(inode);
}
closedir(dir);
std::sort(out.begin(), out.end());
}
// get an address from hex string
inline const addr_t get_addr_hexstr(const char* addr_s) {
const size_t str_len = std::strlen(addr_s);
addr_t ret;
switch(str_len) {
case 8: {
struct in_addr in_local;
if(1 != std::sscanf(addr_s, "%08X", &in_local.s_addr))
throw nettop::runtime_error("Invalid ipv4 hex network address: \"") << addr_s << "\"";
ret = addr_t(in_local);
} break;
case 32: {
struct in6_addr in6_local;
if(4 != std::sscanf(addr_s, "%08X%08X%08X%08X", &in6_local.s6_addr32[0], &in6_local.s6_addr32[1], &in6_local.s6_addr32[2], &in6_local.s6_addr32[3]))
throw nettop::runtime_error("Invalid ipv6 hex network address: \"") << addr_s << "\"";
ret = addr_t(in6_local);
} break;
default:
throw nettop::runtime_error("Invalid hex network address: \"") << addr_s << "\"";
break;
}
return ret;
}
/* Parses /proc/<pid>/net/(tc|ud)p(6) lines of the following form:
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 0100007F:0035 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 15850 1 0000000000000000 100 0 0 10 0
1: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 11154 1 0000000000000000 100 0 0 10 0
2: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 34652 1 0000000000000000 100 0 0 10 0
3: 00000000:7199 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 79489 1 0000000000000000 100 0 0 10 0
4: 00000000:01BD 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 727 1 0000000000000000 100 0 0 10 0
5: 00000000:008B 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 729 1 0000000000000000 100 0 0 10 0
6: 0800A8C0:7199 24F63F4E:7CFC 01 00000000:00000000 00:00000000 00000000 1000 0 203505 1 0000000000000000 26 4 8 10 -1
7: 0800A8C0:7199 24F63F4E:7D4E 01 00000000:00000000 00:00000000 00000000 1000 0 202262 1 0000000000000000 25 4 24 10 -1
8: 0800A8C0:AB65 51480D1F:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 201391 1 0000000000000000 22 4 28 10 -1
9: 0800A8C0:E347 AB29C2AD:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 203276 1 0000000000000000 23 4 28 10 -1
10: 0800A8C0:C813 51480D1F:0050 06 00000000:00000000 03:00001662 00000000 0 0 0 3 0000000000000000
11: 0800A8C0:A8CE 5442C2AD:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 198523 1 0000000000000000 22 4 30 10 -1
12: 0800A8C0:D66A D8B178D5:0050 06 00000000:00000000 03:00001662 00000000 0 0 0 3 0000000000000000
13: 0800A8C0:9FCD AF29C2AD:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 198480 1 0000000000000000 20 4 26 10 -1
14: 0800A8C0:AF33 BB29C2AD:0050 06 00000000:00000000 03:000016C6 00000000 0 0 0 3 0000000000000000
Remember, multiple inodes can be mapped to same local <host>:<port>!
*/
typedef std::map<nettop::ext_sd, std::vector<unsigned long> > m_inodes;
void get_sockets_raw(const bool tcp, const bool v6, m_inodes& out) {
// open /proc directories and scan for all processes
char cur_fd[64];
std::snprintf(cur_fd, 64, "/proc/net/%s%s", tcp ? "tcp" : "udp", v6 ? "6" : "");
std::ifstream istr(cur_fd);
std::set<int> lcl_ports;
while(istr) {
std::string cur_line;
std::getline(istr, cur_line);
char rem_addr[128],
local_addr[128];
int local_port = -1,
rem_port = -1;
unsigned long inode = 0;
const int matches = std::sscanf(cur_line.c_str(), "%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n", local_addr, &local_port, rem_addr, &rem_port, &inode);
if(5 != matches || lcl_ports.end() != lcl_ports.find(local_port))
continue;
// get the address
const addr_t lcl_addr = get_addr_hexstr(local_addr);
const nettop::ext_sd esd(lcl_addr, local_port, tcp ? nettop::packet_stats::type::PACKET_TCP : nettop::packet_stats::type::PACKET_UDP);
out[esd].push_back(inode);
lcl_ports.insert(local_port);
}
}
void get_all_sockets(m_inodes& out) {
get_sockets_raw(true, false, out);
get_sockets_raw(false, false, out);
get_sockets_raw(true, true, out);
get_sockets_raw(false, true, out);
// now we need to sort all vectors of inodes
for(auto& i : out)
std::sort(i.second.begin(), i.second.end());
}
// async log events
struct log_evt : public nettop::async_line {
enum type {
UNDET = 0,
UNMAP_R,
UNMAP_S
};
const nettop::packet_stats ps;
const type t;
log_evt(const nettop::packet_stats& ps_, const enum type t_) : ps(ps_), t(t_) {
}
virtual std::string log(nettop::name_res& nr) const {
std::ostringstream oss;
switch(t) {
case type::UNDET:
oss << "UNDET :";
break;
case type::UNMAP_R:
oss << "UNMAP_R:";
break;
case type::UNMAP_S:
oss << "UNMAP_S:";
break;
}
oss << nr.to_str(ps.src) << ":" << ps.p_src << " --> " << nr.to_str(ps.dst) << ":" << ps.p_dst;
return oss.str();
}
};
nettop::sp_async_line gen_log(const nettop::packet_stats& ps, const enum log_evt::type t) {
return nettop::sp_async_line(new log_evt(ps, t));
}
}
nettop::proc_mgr::proc_mgr() {
// get all the links between ext_sd --> inode
m_inodes inodes_link;
get_all_sockets(inodes_link);
// create reverse map
std::map<unsigned long, m_inodes::const_iterator> link_inodes;
for(m_inodes::const_iterator it = inodes_link.begin(); it != inodes_link.end(); ++it)
for(const auto& i : it->second)
link_inodes[i] = it;
// open /proc directories and scan for all processes
DIR* dir = opendir("/proc");
if(!dir)
throw runtime_error("Can't open /proc directory!");
for(struct dirent *entry = readdir(dir); entry; entry = readdir(dir)) {
// skip . and ..
if(!std::strcmp(entry->d_name, ".") || !std::strcmp(entry->d_name, ".."))
continue;
// we're only interested in directories
if (entry->d_type != DT_DIR)
continue;
// get the pid (again, has to be a precise number!)
errno = 0;
char *endptr = 0;
const pid_t pid = std::strtol(entry->d_name, &endptr, 10);
if(errno || *endptr != '\0')
continue;
// get all inodes
v_inodes inodes;
get_sockets_inodes(pid, inodes);
if(inodes.empty())
continue;
// find links to esd
sd_vec sds;
for(const auto& i : inodes) {
const auto p_link_inodes = link_inodes.find(i);
if(p_link_inodes == link_inodes.end())
continue;
sds.push_back(p_link_inodes->second->first);
}
if(sds.empty())
continue;
// get the command line
const std::string cmd_line = get_cmd_line(pid);
// sort the vector
std::sort(sds.begin(), sds.end());
// initialize the map
p_map_[proc_info(pid, cmd_line, sds)];
}
closedir(dir);
}
//#include <iostream>
void nettop::proc_mgr::bind_packets(const std::list<packet_stats>& p_list, const local_addr_mgr& lam, ps_vec& out, stats& st, async_log_list& log_list) {
// create a utility map from port/proto/ipv --> pid
std::map<ext_sd, proc_map::iterator> sd_pid_map;
for(proc_map::iterator it = p_map_.begin(); it != p_map_.end(); ++it) {
//std::cout << it->first.pid << "(" << it->first.cmd << ")\t";
for(const auto& i : it->first.sd_v) {
//std::cout << "(" << i.t << ")" << i.addr.to_str() << ":" << i.port << "\t";
if(sd_pid_map.end() != sd_pid_map.find(i)) {
//std::cout << __FUNCTION__ << " " << i.addr.to_str() << ":" << i.port << "(" << i.t << ") local address is already mapped to another process!" << std::endl;
continue;
}
sd_pid_map[i] = it;
}
//std::cout << std::endl;
}
// Identify the process 0 (as kernel). All unmapped packet will go there...
proc_map::iterator it_kernel = p_map_.find(proc_info(-1, "(kernel)", sd_vec()));
if(it_kernel == p_map_.end()) {
it_kernel = p_map_.insert(std::make_pair<proc_info, std::pair<ps_list, ps_list> >(proc_info(-1, "(kernel)", sd_vec()), std::pair<ps_list, ps_list>())).first;
}
// first assign packets to processes
for(const auto& i : p_list) {
// refresh timestamp stats - this is a coarse measurement
if(st.min_ts < 0.0 || st.min_ts > i.ts)
st.min_ts = i.ts;
if(st.max_ts < 0.0 || st.max_ts < i.ts)
st.max_ts = i.ts;
// exclude packets where src and dst are the same (they should not impact over the network)
// the kernel should be smart enough to let them "live" on shared memory only when those are
// localhost --> localhost...
if(i.dst == i.src)
continue;
const bool is_recv = lam.is_local(i.dst),
is_sent = lam.is_local(i.src);
if(!(is_recv ^ is_sent)) {
log_list.push(gen_log(i, log_evt::type::UNDET));
++st.undet_pkts;
continue;
}
// from this point we're sure about a packet has been sent or received...
if(is_recv && (settings::CAPTURE_ASR & CAPTURE_RECV)) {
const ext_sd cur_sd(i.dst, i.p_dst, i.t);
auto it = sd_pid_map.find(cur_sd);
if(it == sd_pid_map.end()) {
// last resort, if we can't find it, we should try with the default ANY address (0.0.0.0)
const ext_sd cur_sd_ANY(addr_t(i.dst.get_af_type()), i.p_dst, i.t);
it = sd_pid_map.find(cur_sd_ANY);
if(it == sd_pid_map.end()) {
log_list.push(gen_log(i, log_evt::type::UNMAP_R));
++st.unmap_r_pkts;
it_kernel->second.first.push_back(i);
continue;
}
}
it->second->second.first.push_back(i);
} else if(settings::CAPTURE_ASR & CAPTURE_SEND) {
const ext_sd cur_sd(i.src, i.p_src, i.t);
auto it = sd_pid_map.find(cur_sd);
if(it == sd_pid_map.end()) {
// last resort, if we can't find it, we should try with the default ANY address (0.0.0.0)
const ext_sd cur_sd_ANY(addr_t(i.src.get_af_type()), i.p_src, i.t);
it = sd_pid_map.find(cur_sd_ANY);
if(it == sd_pid_map.end()) {
log_list.push(gen_log(i, log_evt::type::UNMAP_S));
++st.unmap_s_pkts;
it_kernel->second.second.push_back(i);
continue;
}
}
it->second->second.second.push_back(i);
}
++st.proc_pkts;
}
// now prepare output structure
out.reserve(p_map_.size());
for(const auto& i : p_map_) {
proc_stats ps(i.first.pid, i.first.cmd);
for(const auto& r : i.second.first) {
ps.total_rs.first += r.len;
proc_stats::st& cur_stats = ps.addr_rs_map[r.src];
cur_stats.recv += r.len;
switch(r.t) {
case packet_stats::type::PACKET_TCP:
cur_stats.tcp_t += r.len;
break;
case packet_stats::type::PACKET_UDP:
cur_stats.udp_t += r.len;
break;
}
}
for(const auto& r : i.second.second) {
ps.total_rs.second += r.len;
proc_stats::st& cur_stats = ps.addr_rs_map[r.dst];
cur_stats.sent += r.len;
switch(r.t) {
case packet_stats::type::PACKET_TCP:
cur_stats.tcp_t += r.len;
break;
case packet_stats::type::PACKET_UDP:
cur_stats.udp_t += r.len;
break;
}
}
out.push_back(ps);
}
}
================================================
FILE: src/proc.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PROC_H_
#define _PROC_H_
#include <sys/types.h>
#include <map>
#include <list>
#include <vector>
#include <memory>
#include "packet_stats.h"
#include "async_log.h"
#include "name_res.h"
namespace nettop {
struct ext_sd {
addr_t addr;
int port;
enum packet_stats::type t;
ext_sd(const addr_t& addr_ = addr_t(), const int port_ = 0, const enum packet_stats::type t_ = packet_stats::type::PACKET_TCP) : addr(addr_), port(port_), t(t_) {
}
inline bool operator==(const ext_sd& rhs) const {
return port == rhs.port && t == rhs.t && addr == rhs.addr;
}
inline bool operator<(const ext_sd& rhs) const {
if(port == rhs.port) {
if(t == rhs.t) {
return addr < rhs.addr;
}
return t < rhs.t;
}
return port < rhs.port;
}
};
typedef std::vector<ext_sd> sd_vec;
class proc_info {
proc_info& operator=(const proc_info&) = delete;
public:
const pid_t pid;
const std::string cmd;
const sd_vec sd_v;
proc_info(const pid_t pid_, const std::string& cmd_, const sd_vec& sd_v_) : pid(pid_), cmd(cmd_), sd_v(sd_v_) {
}
proc_info(const proc_info& rhs) : pid(rhs.pid), cmd(rhs.cmd), sd_v(rhs.sd_v) {
}
inline bool operator==(const proc_info& rhs) const{
return pid == rhs.pid;
}
inline bool operator<(const proc_info& rhs) const {
return pid < rhs.pid;
}
};
struct proc_stats {
struct st {
size_t recv,
sent,
udp_t,
tcp_t;
st() : recv(0), sent(0), udp_t(0), tcp_t(0) {
}
};
typedef std::map<addr_t, st> addr_st_map;
pid_t pid;
std::string cmd;
addr_st_map addr_rs_map;
std::pair<size_t, size_t> total_rs;
proc_stats(const pid_t pid_, const std::string& cmd_) : pid(pid_), cmd(cmd_), total_rs(std::pair<size_t, size_t>(0, 0)) {
}
};
typedef std::vector<proc_stats> ps_vec;
class proc_mgr {
typedef std::list<packet_stats> ps_list;
typedef std::map<proc_info, std::pair<ps_list, ps_list> > proc_map;
proc_map p_map_;
public:
struct stats {
size_t total_pkts,
proc_pkts,
undet_pkts,
unmap_r_pkts,
unmap_s_pkts;
double min_ts,
max_ts;
stats() : total_pkts(0), proc_pkts(0), undet_pkts(0), unmap_r_pkts(0), unmap_s_pkts(0), min_ts(-1.0), max_ts(-1.0) {
}
};
proc_mgr();
void bind_packets(const std::list<packet_stats>& p_list, const local_addr_mgr& lam, ps_vec& out, stats& st, async_log_list& log_list);
};
}
#endif //_PROC_H_
================================================
FILE: src/settings.cpp
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#include "settings.h"
#include <iostream>
#include <getopt.h>
#include <cstring>
#include "utils.h"
namespace {
// settings/options management
void print_help(const char *prog, const char *version) {
using namespace nettop::settings;
std::cerr << "Usage: " << prog << " [options]\nExecutes nettop " << version << "\n\n"
"-r, --refresh s\t\t\tsets the refresh rate in 's' seconds (default " << REFRESH_SECS << ")\n"
"-c, --capture (a|s|r)\t\tCapture mode for 'a'll, 's'end and 'r'ecv only (default '" << 'a' << "')\n"
"-o, --order (a|d)\t\tOrdering of results, 'a'scending, 'd'escending (default '" << 'd' << "')\n"
" --filter-zero\t\tSet to filter all zero results (default not set)\n"
" --tcp-udp-split\t\tDisplays split of TCP and UDP traffic in % (default not set)\n"
"-n, --no-resolve\t\tDo not resolve addresses, leave IPs to be displayed\n"
"-a, --async-log-file (file)\tSets an output file where to store the packets attribued to the 'kernel' (default not set)\n"
"-l, --limit-hosts-rows\t\tLimits maximum number of hosts rows per pid (default no limit)\n"
" --help\t\t\tprints this help and exit\n\n"
"Press 'q' or 'ESC' inside nettop to quit, 'SPACE' or 'p' to pause nettop\n"
<< std::flush;
}
}
namespace nettop {
namespace settings {
size_t REFRESH_SECS = 3;
int CAPTURE_ASR = 3;
bool ORDER_TOP = true;
bool FILTER_ZERO = false;
bool TCP_UDP_TRAFFIC = false;
bool NO_RESOLVE = false;
std::string ASYNC_LOG_FILE = "";
size_t LIMIT_HOSTS_ROWS = 0;
}
}
int nettop::parse_args(int argc, char *argv[], const char *prog, const char *version) {
using namespace nettop::settings;
int c;
static struct option long_options[] = {
{"help", no_argument, 0, 0},
{"refresh", required_argument, 0, 'r'},
{"capture", required_argument, 0, 'c'},
{"order", required_argument, 0, 'o'},
{"no-resolve", no_argument, 0, 'n'},
{"filter-zero", no_argument, 0, 0},
{"tcp-udp-split", no_argument, 0, 0},
{"async-log-file", required_argument, 0, 'a'},
{"limit-hosts-rows", required_argument, 0, 'l'},
{0, 0, 0, 0}
};
while (1) {
// getopt_long stores the option index here
int option_index = 0;
if(-1 == (c = getopt_long(argc, argv, "hr:c:o:a:l:n", long_options, &option_index)))
break;
switch (c) {
case 0: {
// If this option set a flag, do nothing else now
if (long_options[option_index].flag != 0)
break;
if(!std::strcmp("filter-zero", long_options[option_index].name)) {
FILTER_ZERO = true;
} if(!std::strcmp("tcp-udp-split", long_options[option_index].name)) {
TCP_UDP_TRAFFIC = true;
} else if(!std::strcmp("help", long_options[option_index].name)) {
print_help(prog, version);
std::exit(0);
}
} break;
case 'r': {
const int r_res = std::atoi(optarg);
REFRESH_SECS = (r_res < 0) ? 1 : (r_res > 60) ? 60 : r_res;
} break;
case 'c': {
switch(optarg[0]) {
case 'a':
CAPTURE_ASR = CAPTURE_ALL;
break;
case 's':
CAPTURE_ASR = CAPTURE_SEND;
break;
case 'r':
CAPTURE_ASR = CAPTURE_RECV;
break;
default:
throw runtime_error("Invalid capture flag provided (expected 'a', 's' or 'r' but found '") << optarg[0] << "')";
break;
}
} break;
case 'o': {
switch(optarg[0]) {
case 'a':
ORDER_TOP = false;
break;
default:
ORDER_TOP = true;
break;
}
} break;
case 'a': {
ASYNC_LOG_FILE = optarg;
} break;
case 'l': {
const int m_res = std::atoi(optarg);
LIMIT_HOSTS_ROWS = (m_res > 0) ? m_res : 0;
} break;
case 'n': {
NO_RESOLVE = true;
} break;
case '?':
break;
default:
throw runtime_error("Invalid option '") << (char)c << "'";
break;
}
}
return optind;
}
================================================
FILE: src/settings.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SETTINGS_H_
#define _SETTINGS_H_
#include <cstdlib>
#include <string>
#define CAPTURE_SEND (0x01)
#define CAPTURE_RECV (0x02)
#define CAPTURE_ALL (CAPTURE_SEND|CAPTURE_RECV)
namespace nettop {
namespace settings {
extern size_t REFRESH_SECS;
extern int CAPTURE_ASR;
extern bool ORDER_TOP;
extern bool FILTER_ZERO;
extern bool TCP_UDP_TRAFFIC;
extern bool NO_RESOLVE;
extern std::string ASYNC_LOG_FILE;
extern size_t LIMIT_HOSTS_ROWS;
}
int parse_args(int argc, char *argv[], const char *prog, const char *version);
}
#endif //_SETTINGS_H_
================================================
FILE: src/utils.h
================================================
/*
* nettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it
*
* This file is part of nettop.
*
* nettop 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.
*
* nettop 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 nettop. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _UTILS_H_
#define _UTILS_H_
#include <exception>
#include <string>
#include <sstream>
#include <sys/time.h>
namespace nettop {
class runtime_error : public std::exception {
std::ostringstream _oss;
std::string _str;
public:
runtime_error(const char *e) throw() {
_oss << e;
_str = _oss.str();
}
runtime_error(const runtime_error& rhs) throw() {
_oss.str(rhs._oss.str());
_str = _oss.str();
}
runtime_error& operator=(const runtime_error& rhs) throw() {
_oss.str(rhs._oss.str());
_str = _oss.str();
return *this;
}
template<typename T>
runtime_error& operator<<(const T& in) {
_oss << in;
_str = _oss.str();
return *this;
}
virtual const char* what() const throw() {
return _str.c_str();
}
virtual ~runtime_error() throw() {
}
};
inline double tv_to_sec(const timeval& tv) {
return 1.0*tv.tv_sec + (1.0/1000000.0)*tv.tv_usec;
}
}
#endif //_UTILS_H_
gitextract_4t8i9myw/
├── LICENSE
├── Makefile
├── README.md
└── src/
├── addr_t.h
├── async_log.cpp
├── async_log.h
├── cap_mgr.cpp
├── cap_mgr.h
├── epoll_stdin.h
├── gpl_v3
├── main.cpp
├── mt_list.h
├── name_res.cpp
├── name_res.h
├── packet_stats.cpp
├── packet_stats.h
├── proc.cpp
├── proc.h
├── settings.cpp
├── settings.h
└── utils.h
SYMBOL INDEX (60 symbols across 15 files)
FILE: src/addr_t.h
function class (line 27) | class addr_t {
function is_ipv6 (line 88) | inline bool is_ipv6(void) const {
type sockaddr_in (line 95) | struct sockaddr_in
type sockaddr_in (line 100) | struct sockaddr_in
type sockaddr_in6 (line 108) | struct sockaddr_in6
type sockaddr_in6 (line 115) | struct sockaddr_in6
FILE: src/async_log.h
function namespace (line 31) | namespace nettop {
FILE: src/cap_mgr.cpp
type sll_header (line 41) | struct sll_header {
function process_tcp (line 49) | inline void process_tcp(const u_char *data, st_pkt_list& p_list, const d...
function process_udp (line 56) | inline void process_udp(const u_char *data, st_pkt_list& p_list, const d...
function process_ip (line 63) | inline void process_ip(const u_char *data, st_pkt_list& p_list, const do...
function process_ip6 (line 80) | inline void process_ip6(const u_char *data, st_pkt_list& p_list, const d...
function p_handler (line 97) | void p_handler(u_char *user, const struct pcap_pkthdr *header, const u_c...
FILE: src/cap_mgr.h
function namespace (line 28) | namespace nettop {
FILE: src/epoll_stdin.h
function namespace (line 27) | namespace utils {
FILE: src/main.cpp
function sign_onexit (line 38) | void sign_onexit(int param) {
type ps_sorted_iter (line 44) | struct ps_sorted_iter {
method ps_sorted_iter (line 48) | ps_sorted_iter(nettop::ps_vec::const_iterator it_p_vec_) : it_p_vec(it...
function sort_filter_data (line 54) | void sort_filter_data(const nettop::ps_vec& p_vec, sorted_p_vec& out) {
class curses_setup (line 92) | class curses_setup {
method recv_send_format (line 102) | static void recv_send_format(const std::chrono::nanoseconds& tm_elapse...
method curses_setup (line 127) | curses_setup(nettop::name_res& nr, const size_t limit_hosts = 0) : w_(...
method draw_paused (line 134) | void draw_paused(void) {
method redraw (line 151) | void redraw(const std::chrono::nanoseconds& tm_elapsed, const sorted_p...
type stdin_exit (line 236) | struct stdin_exit : public utils::epoll_stdin {
method on_data (line 237) | virtual bool on_data(const char* p, const size_t sz) const {
type auto_quit (line 257) | struct auto_quit {
method auto_quit (line 258) | auto_quit() {}
function main (line 263) | int main(int argc, char *argv[]) {
FILE: src/mt_list.h
function push (line 40) | void push(const T& in) {
function push_many (line 45) | void push_many(const std::list<T>& in) {
function swap (line 50) | void swap(std::list<T>& out) {
FILE: src/name_res.h
function namespace (line 30) | namespace nettop {
FILE: src/packet_stats.cpp
type ifaddrs (line 27) | struct ifaddrs
type sockaddr_in (line 38) | struct sockaddr_in
type sockaddr_in (line 38) | struct sockaddr_in
type sockaddr_in6 (line 41) | struct sockaddr_in6
type sockaddr_in6 (line 41) | struct sockaddr_in6
FILE: src/packet_stats.h
function class (line 28) | class packet_stats {
FILE: src/proc.cpp
function get_cmd_line (line 39) | std::string get_cmd_line(const pid_t pid) {
function get_sockets_inodes (line 63) | void get_sockets_inodes(const pid_t pid, v_inodes& out) {
function addr_t (line 95) | inline const addr_t get_addr_hexstr(const char* addr_s) {
function get_sockets_raw (line 139) | void get_sockets_raw(const bool tcp, const bool v6, m_inodes& out) {
function get_all_sockets (line 164) | void get_all_sockets(m_inodes& out) {
type log_evt (line 175) | struct log_evt : public nettop::async_line {
type type (line 176) | enum type {
method log_evt (line 185) | log_evt(const nettop::packet_stats& ps_, const enum type t_) : ps(ps_)...
method log (line 188) | virtual std::string log(nettop::name_res& nr) const {
function gen_log (line 206) | nettop::sp_async_line gen_log(const nettop::packet_stats& ps, const enum...
type dirent (line 224) | struct dirent
FILE: src/proc.h
function namespace (line 32) | namespace nettop {
type std (line 57) | typedef std::vector<ext_sd> sd_vec;
function class (line 59) | class proc_info {
function rhs (line 78) | inline bool operator<(const proc_info& rhs) const {
FILE: src/settings.cpp
function print_help (line 28) | void print_help(const char *prog, const char *version) {
type nettop (line 46) | namespace nettop {
type settings (line 47) | namespace settings {
type option (line 63) | struct option
FILE: src/settings.h
function namespace (line 30) | namespace nettop {
FILE: src/utils.h
function namespace (line 28) | namespace nettop {
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (111K chars).
[
{
"path": "LICENSE",
"chars": 35141,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "Makefile",
"chars": 2053,
"preview": "#Makefile generated by amake\n#On Thu Aug 17 11:55:23 2017\n#To print amake help use 'amake --help'.\nCC=gcc\nCPPC=g++\nLINK="
},
{
"path": "README.md",
"chars": 3953,
"preview": "# nettop\n\nUtility to show network traffic (both TCP and UDP v4 and v6) split by process and remote host. You can find mo"
},
{
"path": "src/addr_t.h",
"chars": 4504,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/async_log.cpp",
"chars": 2147,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/async_log.h",
"chars": 1871,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/cap_mgr.cpp",
"chars": 5046,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/cap_mgr.h",
"chars": 1285,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/epoll_stdin.h",
"chars": 2204,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/gpl_v3",
"chars": 716,
"preview": "/*\n*\tnettop (C) 2014 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free softwar"
},
{
"path": "src/main.cpp",
"chars": 11245,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/mt_list.h",
"chars": 1395,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/name_res.cpp",
"chars": 1796,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/name_res.h",
"chars": 1376,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/packet_stats.cpp",
"chars": 1635,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/packet_stats.h",
"chars": 1653,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/proc.cpp",
"chars": 13981,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/proc.h",
"chars": 3150,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/settings.cpp",
"chars": 4570,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/settings.h",
"chars": 1302,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
},
{
"path": "src/utils.h",
"chars": 2131,
"preview": "/*\n*\tnettop (C) 2017-2020 E. Oriani, ema <AT> fastwebnet <DOT> it\n*\n*\tThis file is part of nettop.\n*\n*\tnettop is free so"
}
]
About this extraction
This page contains the full source code of the Emanem/nettop GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (100.7 KB), approximately 28.4k tokens, and a symbol index with 60 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.