Full Code of mchome/dogcom for AI

master 6f5f55062e43 cached
27 files
146.4 KB
45.4k tokens
107 symbols
1 requests
Download .txt
Repository: mchome/dogcom
Branch: master
Commit: 6f5f55062e43
Files: 27
Total size: 146.4 KB

Directory structure:
gitextract_f9rp1ayh/

├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── auth.c
├── auth.h
├── configparse.c
├── configparse.h
├── daemon.c
├── daemon.h
├── debug.h
├── eapol.c
├── eapol.h
├── keepalive.c
├── keepalive.h
├── libs/
│   ├── common.c
│   ├── common.h
│   ├── md4.c
│   ├── md4.h
│   ├── md5.c
│   ├── md5.h
│   ├── sha1.c
│   └── sha1.h
├── main.c
├── sample-d.conf
└── sample-p.conf

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
test
drcom.conf
test.conf
dogcom
main
.vscode

# Prerequisites
*.d

# Object files
*.o
*.ko
*.obj
*.elf

# Linker output
*.ilk
*.map
*.exp

# Precompiled Headers
*.gch
*.pch

# Libraries
*.lib
*.a
*.la
*.lo

# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib

# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex

# Debug files
*.dSYM/
*.su
*.idb
*.pdb

# Kernel Module Compile Results
*.mod*
*.cmd
modules.order
Module.symvers
Mkfile.old
dkms.conf
*.stackdump

================================================
FILE: .travis.yml
================================================
language: c
os:
    - linux
    - osx
compiler:
    - gcc
    - clang

script:
    - make test=y
    - ./dogcom -m dhcp -c sample-d.conf
    - ./dogcom -m pppoe -c sample-p.conf

branches:
    only:
        - master

================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are 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.

  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.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  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 AGPL, see
<http://www.gnu.org/licenses/>.


================================================
FILE: Makefile
================================================
CC     = gcc
TARGET = dogcom
INSTALL_DIR = /usr/bin/

ifeq ($(debug), y)
	CFLAGS += -DDEBUG -g
endif

ifeq ($(win32), y)
	CFLAGS += -lws2_32
	# TARGET = dogcom.exe
endif

ifeq ($(static), y)
	CFLAGS += -static
endif

ifeq ($(strip), y)
	CFLAGS += -Os -s -Wno-unused-result
endif

ifeq ($(force_encrypt), y)
	CFLAGS += -DFORCE_ENCRYPT
endif

ifeq ($(test), y)
	CFLAGS += -std=gnu99 -Werror -DTEST
else
	CFLAGS += -std=gnu99 -Werror
endif

SOURCES = $(wildcard *.c) $(wildcard libs/*.c)
OBJS    = $(patsubst %.c, %.o, $(SOURCES))

$(TARGET):	$(OBJS)
	$(CC) $(DEBUG) $(TEST) $(OBJS) $(CFLAGS) -o $(TARGET)

all:	$(TARGET)

install:	$(TARGET)
	cp $(TARGET) $(INSTALL_DIR)

clean:
	rm -f $(OBJS)
	rm -f $(TARGET)

distclean:  clean

.PHONY: all clean distclean install


================================================
FILE: README.md
================================================
# dogcom [![travis-ci](https://travis-ci.org/mchome/dogcom.svg "Build status")](https://travis-ci.org/mchome/dogcom) [![badge](https://img.shields.io/badge/%20built%20with-%20%E2%9D%A4-ff69b4.svg "build with love")](https://github.com/mchome/dogcom) [![version](https://img.shields.io/badge/stable%20-%20v1.6.2-4dc71f.svg "stable version")](https://github.com/mchome/dogcom/tree/v1.6.2)

[Drcom-generic](https://github.com/drcoms/drcom-generic) implementation in C.

```
Usage:
        dogcom -m <dhcp/pppoe> -c <FILEPATH> [options <argument>]...

Options:
        --mode <dhcp/pppoe>, -m <dhcp/pppoe>  set your dogcom mode
        --conf <FILEPATH>, -c <FILEPATH>      import configuration file
        --bindip <IPADDR>, -b <IPADDR>        bind your ip address(default is 0.0.0.0)
        --log <LOGPATH>, -l <LOGPATH>         specify log file
        --802.1x, -x                          enable 802.1x
        --daemon, -d                          set daemon flag
        --eternal, -e                         set eternal flag
        --verbose, -v                         set verbose flag
        --help, -h                            display this help
```

Config file is compatible with [drcom-generic](https://github.com/drcoms/drcom-generic).

#### Example:

```bash
$ dogcom -m dhcp -c dogcom.conf
$ dogcom -m dhcp -c dogcom.conf -l /tmp/dogcom.log -v
$ dogcom -m dhcp -c dogcom.conf -d # (PS: only on Linux build)
$ dogcom -m pppoe -c dogcom.conf -x # (PS: only on Linux build)
$ dogcom -m pppoe -c dogcom.conf -e # eternal dogcoming (default times is 5)
$ dogcom -m pppoe -c dogcom.conf -v
$ dogcom -m dhcp -c dogcom.conf -b 10.2.3.12 -v
```

#### To build:

```bash
$ make # Linux
$ make win32=y # Windows(MinGW)
$ make test=y # For testing purposes
$ make force_encrypt=y # Force open encrypt mode in PPPoE version
```

#### Openwrt-package
[https://github.com/mchome/openwrt-dogcom](https://github.com/mchome/openwrt-dogcom)

#### Tutorial
[![asciicast](https://asciinema.org/a/9j7cj1s61jiczx2s0206tosjr.png)](https://asciinema.org/a/9j7cj1s61jiczx2s0206tosjr)

### Thanks:
- [gdut-drcom](https://github.com/chenhaowen01/gdut-drcom 'chenhaowen01')
- [jlu-drcom-client](https://github.com/drcoms/jlu-drcom-client/tree/master/C-version 'feix')
- [leetking](https://github.com/leetking 'leetking')

### Special thanks:
- [Drcom-generic](https://github.com/drcoms/drcom-generic 'ly0')

### License:
![AGPL V3](https://cloud.githubusercontent.com/assets/7392658/20011165/a0caabdc-a2e5-11e6-974c-8d4961c7d6d3.png)


================================================
FILE: auth.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

#ifdef WIN32
#include <winsock2.h>
typedef int socklen_t;
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#endif

#include "auth.h"
#include "configparse.h"
#include "debug.h"
#include "keepalive.h"
#include "libs/md4.h"
#include "libs/md5.h"
#include "libs/sha1.h"

#define BIND_PORT 61440
#define DEST_PORT 61440

int dhcp_challenge(int sockfd, struct sockaddr_in addr, unsigned char seed[]) {
    unsigned char challenge_packet[20], recv_packet[1024];
    memset(challenge_packet, 0, 20);
    challenge_packet[0] = 0x01;
    challenge_packet[1] = 0x02;
    challenge_packet[2] = rand() & 0xff;
    challenge_packet[3] = rand() & 0xff;
    challenge_packet[4] = drcom_config.AUTH_VERSION[0];

    sendto(sockfd, challenge_packet, 20, 0, (struct sockaddr *)&addr, sizeof(addr));

    if (verbose_flag) {
        print_packet("[Challenge sent] ", challenge_packet, 20);
    }
    if (logging_flag) {
        logging("[Challenge sent] ", challenge_packet, 20);
    }
#ifdef TEST
    unsigned char test[4] = {0x52, 0x6c, 0xe4, 0x00};
    memcpy(seed, test, 4);
    print_packet("[TEST MODE]<PREP SEED> ", seed, 4);
    return 0;
#endif

    socklen_t addrlen = sizeof(addr);
    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
        get_lasterror("Failed to recv data");
#else
        perror("Failed to recv data");
#endif
        return 1;
    }

    if (verbose_flag) {
        print_packet("[Challenge recv] ", recv_packet, 76);
    }
    if (logging_flag) {
        logging("[Challenge recv] ", recv_packet, 76);
    }

    if (recv_packet[0] != 0x02) {
        printf("Bad challenge response received.\n");
        return 1;
    }

    memcpy(seed, &recv_packet[4], 4);
#ifdef DEBUG
    print_packet("<GET SEED> ", seed, 4);
#endif

    return 0;
}

int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[], int try_JLUversion) {
    unsigned int login_packet_size;
    unsigned int length_padding = 0;
    int JLU_padding = 0;

    if (strlen(drcom_config.password) > 8) {
        length_padding = strlen(drcom_config.password) - 8 + (length_padding % 2);
        if (try_JLUversion) {
            printf("Start JLU mode.\n");
            if (logging_flag) {
                logging("Start JLU mode.", NULL, 0);
            }
            if (strlen(drcom_config.password) != 16) {
                JLU_padding = strlen(drcom_config.password) / 4;
            }
            length_padding = 28 + (strlen(drcom_config.password) - 8) + JLU_padding;
        }
    }
    if (drcom_config.ror_version) {
        login_packet_size = 338 + length_padding;
    } else {
        login_packet_size = 330;
    }
    unsigned char login_packet[login_packet_size], recv_packet[1024], MD5A[16], MACxorMD5A[6], MD5B[16], checksum1[8], checksum2[4];
    memset(login_packet, 0, login_packet_size);
    memset(recv_packet, 0, 100);

    // build login-packet
    login_packet[0] = 0x03;
    login_packet[1] = 0x01;
    login_packet[2] = 0x00;
    login_packet[3] = strlen(drcom_config.username) + 20;
    int MD5A_len = 6 + strlen(drcom_config.password);
    unsigned char MD5A_str[MD5A_len];
    MD5A_str[0] = 0x03;
    MD5A_str[1] = 0x01;
    memcpy(MD5A_str + 2, seed, 4);
    memcpy(MD5A_str + 6, drcom_config.password, strlen(drcom_config.password));
    MD5(MD5A_str, MD5A_len, MD5A);
    memcpy(login_packet + 4, MD5A, 16);
    memcpy(login_packet + 20, drcom_config.username, strlen(drcom_config.username));
    memcpy(login_packet + 56, &drcom_config.CONTROLCHECKSTATUS, 1);
    memcpy(login_packet + 57, &drcom_config.ADAPTERNUM, 1);
    uint64_t sum = 0;
    uint64_t mac = 0;
    // unpack
    for (int i = 0; i < 6; i++) {
        sum = (int)MD5A[i] + sum * 256;
    }
    // unpack
    for (int i = 0; i < 6; i++) {
        mac = (int)drcom_config.mac[i] + mac * 256;
    }
    sum ^= mac;
    // pack
    for (int i = 6; i > 0; i--) {
        MACxorMD5A[i - 1] = (unsigned char)(sum % 256);
        sum /= 256;
    }
    memcpy(login_packet + 58, MACxorMD5A, sizeof(MACxorMD5A));
    int MD5B_len = 9 + strlen(drcom_config.password);
    unsigned char MD5B_str[MD5B_len];
    memset(MD5B_str, 0, MD5B_len);
    MD5B_str[0] = 0x01;
    memcpy(MD5B_str + 1, drcom_config.password, strlen(drcom_config.password));
    memcpy(MD5B_str + strlen(drcom_config.password) + 1, seed, 4);
    MD5(MD5B_str, MD5B_len, MD5B);
    memcpy(login_packet + 64, MD5B, 16);
    login_packet[80] = 0x01;
    unsigned char host_ip[4];
    sscanf(drcom_config.host_ip, "%hhd.%hhd.%hhd.%hhd",
           &host_ip[0],
           &host_ip[1],
           &host_ip[2],
           &host_ip[3]);
    memcpy(login_packet + 81, host_ip, 4);
    unsigned char checksum1_str[101], checksum1_tmp[4] = {0x14, 0x00, 0x07, 0x0b};
    memcpy(checksum1_str, login_packet, 97);
    memcpy(checksum1_str + 97, checksum1_tmp, 4);
    MD5(checksum1_str, 101, checksum1);
    memcpy(login_packet + 97, checksum1, 8);
    memcpy(login_packet + 105, &drcom_config.IPDOG, 1);
    memcpy(login_packet + 110, &drcom_config.host_name, strlen(drcom_config.host_name));
    unsigned char PRIMARY_DNS[4];
    sscanf(drcom_config.PRIMARY_DNS, "%hhd.%hhd.%hhd.%hhd",
           &PRIMARY_DNS[0],
           &PRIMARY_DNS[1],
           &PRIMARY_DNS[2],
           &PRIMARY_DNS[3]);
    memcpy(login_packet + 142, PRIMARY_DNS, 4);
    unsigned char dhcp_server[4];
    sscanf(drcom_config.dhcp_server, "%hhd.%hhd.%hhd.%hhd",
           &dhcp_server[0],
           &dhcp_server[1],
           &dhcp_server[2],
           &dhcp_server[3]);
    memcpy(login_packet + 146, dhcp_server, 4);
    unsigned char OSVersionInfoSize[4] = {0x94};
    unsigned char OSMajor[4] = {0x05};
    unsigned char OSMinor[4] = {0x01};
    unsigned char OSBuild[4] = {0x28, 0x0a};
    unsigned char PlatformID[4] = {0x02};
    if (try_JLUversion) {
        OSVersionInfoSize[0] = 0x94;
        OSMajor[0] = 0x06;
        OSMinor[0] = 0x02;
        OSBuild[0] = 0xf0;
        OSBuild[1] = 0x23;
        PlatformID[0] = 0x02;
        unsigned char ServicePack[40] = {0x33, 0x64, 0x63, 0x37, 0x39, 0x66, 0x35, 0x32, 0x31, 0x32, 0x65, 0x38, 0x31, 0x37, 0x30, 0x61, 0x63, 0x66, 0x61, 0x39, 0x65, 0x63, 0x39, 0x35, 0x66, 0x31, 0x64, 0x37, 0x34, 0x39, 0x31, 0x36, 0x35, 0x34, 0x32, 0x62, 0x65, 0x37, 0x62, 0x31};
        unsigned char hostname[9] = {0x44, 0x72, 0x43, 0x4f, 0x4d, 0x00, 0xcf, 0x07, 0x68};
        memcpy(login_packet + 182, hostname, 9);
        memcpy(login_packet + 246, ServicePack, 40);
    }
    memcpy(login_packet + 162, OSVersionInfoSize, 4);
    memcpy(login_packet + 166, OSMajor, 4);
    memcpy(login_packet + 170, OSMinor, 4);
    memcpy(login_packet + 174, OSBuild, 4);
    memcpy(login_packet + 178, PlatformID, 4);
    if (!try_JLUversion) {
        memcpy(login_packet + 182, &drcom_config.host_os, strlen(drcom_config.host_os));
    }
    memcpy(login_packet + 310, drcom_config.AUTH_VERSION, 2);
    int counter = 312;
    unsigned int ror_padding = 0;
    if (strlen(drcom_config.password) <= 8) {
        ror_padding = 8 - strlen(drcom_config.password);
    } else {
        if ((strlen(drcom_config.password) - 8) % 2) {
            ror_padding = 1;
        }
        if (try_JLUversion) {
            ror_padding = JLU_padding;
        }
    }
    if (drcom_config.ror_version) {
        MD5(MD5A_str, MD5A_len, MD5A);
        login_packet[counter + 1] = strlen(drcom_config.password);
        counter += 2;
        for (int i = 0, x = 0; i < strlen(drcom_config.password); i++) {
            x = (int)MD5A[i] ^ (int)drcom_config.password[i];
            login_packet[counter + i] = (unsigned char)(((x << 3) & 0xff) + (x >> 5));
        }
        counter += strlen(drcom_config.password);
        // print_packet("TEST ", ror, strlen(drcom_config.password));
    } else {
        ror_padding = 2;
    }
    login_packet[counter] = 0x02;
    login_packet[counter + 1] = 0x0c;
    unsigned char checksum2_str[counter + 18];  // [counter + 14 + 4]
    memset(checksum2_str, 0, counter + 18);
    unsigned char checksum2_tmp[6] = {0x01, 0x26, 0x07, 0x11};
    memcpy(checksum2_str, login_packet, counter + 2);
    memcpy(checksum2_str + counter + 2, checksum2_tmp, 6);
    memcpy(checksum2_str + counter + 8, drcom_config.mac, 6);
    sum = 1234;
    uint64_t ret = 0;
    for (int i = 0; i < counter + 14; i += 4) {
        ret = 0;
        // reverse unsigned char array[4]
        for (int j = 4; j > 0; j--) {
            ret = ret * 256 + (int)checksum2_str[i + j - 1];
        }
        sum ^= ret;
    }
    sum = (1968 * sum) & 0xffffffff;
    for (int j = 0; j < 4; j++) {
        checksum2[j] = (unsigned char)(sum >> (j * 8) & 0xff);
    }
    memcpy(login_packet + counter + 2, checksum2, 4);
    memcpy(login_packet + counter + 8, drcom_config.mac, 6);
    login_packet[counter + ror_padding + 14] = 0xe9;
    login_packet[counter + ror_padding + 15] = 0x13;
    if (try_JLUversion) {
        login_packet[counter + ror_padding + 14] = 0x60;
        login_packet[counter + ror_padding + 15] = 0xa2;
    }

    sendto(sockfd, login_packet, sizeof(login_packet), 0, (struct sockaddr *)&addr, sizeof(addr));

    if (verbose_flag) {
        print_packet("[Login sent] ", login_packet, sizeof(login_packet));
    }
    if (logging_flag) {
        logging("[Login sent] ", login_packet, sizeof(login_packet));
    }

#ifdef TEST
    unsigned char test[16] = {0x44, 0x72, 0x63, 0x6f, 0x77, 0x27, 0x20, 0xca, 0xed, 0x05, 0x6e, 0x35, 0xaa, 0x8b, 0x01, 0xfb};
    memcpy(auth_information, test, 16);
    print_packet("[TEST MODE]<PREP AUTH_INFORMATION> ", auth_information, 16);
    return 0;
#endif

    socklen_t addrlen = sizeof(addr);
    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
        get_lasterror("Failed to recv data");
#else
        perror("Failed to recv data");
#endif
        return 1;
    }

    if (recv_packet[0] != 0x04) {
        if (verbose_flag) {
            print_packet("[login recv] ", recv_packet, 100);
        }
        printf("<<< Login failed >>>\n");
        if (logging_flag) {
            logging("[login recv] ", recv_packet, 100);
            logging("<<< Login failed >>>", NULL, 0);
        }
        char err_msg[256];
        if (recv_packet[0] == 0x05) {
            switch (recv_packet[4]) {
                case CHECK_MAC:
                    strcpy(err_msg, "[Tips] Someone is using this account with wired.");
                    break;
                case SERVER_BUSY:
                    strcpy(err_msg, "[Tips] The server is busy, please log back in again.");
                    break;
                case WRONG_PASS:
                    strcpy(err_msg, "[Tips] Account and password not match.");
                    break;
                case NOT_ENOUGH:
                    strcpy(err_msg, "[Tips] The cumulative time or traffic for this account has exceeded the limit.");
                    break;
                case FREEZE_UP:
                    strcpy(err_msg, "[Tips] This account is suspended.");
                    break;
                case NOT_ON_THIS_IP:
                    strcpy(err_msg, "[Tips] IP address does not match, this account can only be used in the specified IP address.");
                    break;
                case NOT_ON_THIS_MAC:
                    strcpy(err_msg, "[Tips] MAC address does not match, this account can only be used in the specified IP and MAC address.");
                    break;
                case TOO_MUCH_IP:
                    strcpy(err_msg, "[Tips] This account has too many IP addresses.");
                    break;
                case UPDATE_CLIENT:
                    strcpy(err_msg, "[Tips] The client version is incorrect.");
                    break;
                case NOT_ON_THIS_IP_MAC:
                    strcpy(err_msg, "[Tips] This account can only be used on specified MAC and IP address.");
                    break;
                case MUST_USE_DHCP:
                    strcpy(err_msg, "[Tips] Your PC set up a static IP, please change to DHCP, and then re-login.");
                    break;
                default:
                    strcpy(err_msg, "[Tips] Unknown error number.");
                    break;
            }
            printf("%s\n", err_msg);
            if (logging_flag) {
                logging(err_msg, NULL, 0);
            }
        }
        return 1;
    } else {
        if (verbose_flag) {
            print_packet("[login recv] ", recv_packet, 100);
        }
        printf("<<< Logged in >>>\n");
        if (logging_flag) {
            logging("[login recv] ", recv_packet, 100);
            logging("<<< Logged in >>>", NULL, 0);
        }
    }

    memcpy(auth_information, &recv_packet[23], 16);
#ifdef DEBUG
    print_packet("<GET AUTH_INFORMATION> ", auth_information, 16);
#endif

    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) >= 0) {
        DEBUG_PRINT(("Get notice packet."));
    }

    return 0;
}

int pppoe_challenge(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *encrypt_mode) {
    unsigned char challenge_packet[8], recv_packet[1024];
    memset(challenge_packet, 0, 8);
    unsigned char challenge_tmp[5] = {0x07, 0x00, 0x08, 0x00, 0x01};
    memcpy(challenge_packet, challenge_tmp, 5);
    challenge_packet[1] = *pppoe_counter % 0xFF;
    (*pppoe_counter)++;

    sendto(sockfd, challenge_packet, 8, 0, (struct sockaddr *)&addr, sizeof(addr));

    if (verbose_flag) {
        print_packet("[Challenge sent] ", challenge_packet, 8);
    }
    if (logging_flag) {
        logging("[Challenge sent] ", challenge_packet, 8);
    }
#ifdef TEST
    unsigned char test1[4] = {0x26, 0xe6, 0xe1, 0x02};
    unsigned char test2[4] = {0xc0, 0xa8, 0x01, 0x0b};
    memcpy(seed, test1, 4);
    memcpy(sip, test2, 4);
    *encrypt_mode = 1; /* encrypt_mode test switch [0 or 1] */
    print_packet("[TEST MODE]<PREP SEED> ", seed, 4);
    print_packet("[TEST MODE]<PREP SIP> ", sip, 4);
    printf("[TEST MODE]<PREP ENCRYPT_MODE> %d\n", *encrypt_mode);
    return 0;
#endif

    socklen_t addrlen = sizeof(addr);
    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
        get_lasterror("Failed to recv data");
#else
        perror("Failed to recv data");
#endif
        return 1;
    }

    if (verbose_flag) {
        print_packet("[Challenge recv] ", recv_packet, 32);
    }
    if (logging_flag) {
        logging("[Challenge recv] ", recv_packet, 32);
    }

    if (recv_packet[0] != 0x07) {
        printf("Bad challenge response received.\n");
        return 1;
    }
    if (recv_packet[5] != 0x00) {
        *encrypt_mode = 1;
    } else {
        *encrypt_mode = 0;
    }

#ifdef FORCE_ENCRYPT
    *encrypt_mode = 1;
#endif

    memcpy(seed, &recv_packet[8], 4);
    memcpy(sip, &recv_packet[12], 4);
    memcpy(drcom_config.KEEP_ALIVE_VERSION, &recv_packet[28], 2);
#ifdef DEBUG
    print_packet("<GET SEED> ", seed, 4);
    print_packet("<GET SIP> ", sip, 4);
    printf("<GET ENCRYPT_MODE> %d", *encrypt_mode);
#endif

    return 0;
}

int pppoe_login(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *login_first, int *encrypt_mode, int *encrypt_type) {
    unsigned char login_packet[96], recv_packet[1024];
    memset(login_packet, 0, 96);
    unsigned char login_tmp[5] = {0x07, 0x00, 0x60, 0x00, 0x03};
    memcpy(login_packet, login_tmp, 5);
    login_packet[1] = *pppoe_counter % 0xFF;
    (*pppoe_counter)++;
    memcpy(login_packet + 12, sip, 4);
    if (*login_first) {
        login_packet[17] = 0x62;
    } else {
        login_packet[17] = 0x63;
    }
    memcpy(login_packet + 19, &drcom_config.pppoe_flag, 1);
    memcpy(login_packet + 20, seed, 4);
    unsigned char crc[8] = {0};
    *encrypt_type = seed[0] & 3;
    if (!*encrypt_mode) {
        *encrypt_type = 0;
    }
    gen_crc(seed, *encrypt_type, crc);
    unsigned char crc_tmp[32] = {0};
    memcpy(crc_tmp, login_packet, 32);
    memcpy(crc_tmp + 24, crc, 8);
    uint64_t ret = 0;
    uint64_t sum = 0;
    unsigned char crc2[4] = {0};
    if (*encrypt_type == 0) {
        for (int i = 0; i < 32; i += 4) {
            ret = 0;
            for (int j = 4; j > 0; j--) {
                ret = ret * 256 + (int)crc_tmp[i + j - 1];
            }
            sum ^= ret;
            sum &= 0xffffffff;
        }
        sum = sum * 19680126 & 0xffffffff;
        for (int i = 0; i < 4; i++) {
            crc2[i] = (unsigned char)(sum % 256);
            sum /= 256;
        }
        memcpy(login_packet + 24, crc2, 4);
    } else {
        memcpy(login_packet + 24, crc, 8);
    }
    // login_packet[39] = 0x8b;
    // memcpy(login_packet + 40, sip, 4);
    // unsigned char smask[4] = {0xff, 0xff, 0xff, 0xff};
    // memcpy(login_packet + 44, smask, 4);
    // login_packet[54] = 0x40;

    sendto(sockfd, login_packet, 96, 0, (struct sockaddr *)&addr, sizeof(addr));
    if (verbose_flag) {
        print_packet("[PPPoE_login sent] ", login_packet, 96);
    }
    if (logging_flag) {
        logging("[PPPoE_login sent] ", login_packet, 96);
    }
#ifdef TEST
    return 0;
#endif

    socklen_t addrlen = sizeof(addr);
    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
        get_lasterror("Failed to recv data");
#else
        perror("Failed to recv data");
#endif
        return 1;
    }

    if (verbose_flag) {
        print_packet("[PPPoE_login recv] ", recv_packet, 48);
    }
    if (logging_flag) {
        logging("[PPPoE_login recv] ", recv_packet, 48);
    }

    if (recv_packet[0] != 0x07) {
        printf("Bad pppoe_login response received.\n");
        return 1;
    }

    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) >= 0) {
        DEBUG_PRINT(("Get notice packet."));
    }

    return 0;
}

int dogcom(int try_times) {
#ifdef WIN32
    WORD sockVersion = MAKEWORD(2, 2);
    WSADATA wsaData;
    if (WSAStartup(sockVersion, &wsaData) != 0) {
        return 1;
    }
#endif
    int sockfd;

    struct sockaddr_in bind_addr;
    memset(&bind_addr, 0, sizeof(bind_addr));
    bind_addr.sin_family = AF_INET;
    if (verbose_flag) {
        printf("You are binding at %s!\n\n", bind_ip);
    }
#ifdef WIN32
    bind_addr.sin_addr.S_un.S_addr = inet_addr(bind_ip);
#else
    bind_addr.sin_addr.s_addr = inet_addr(bind_ip);
#endif
    bind_addr.sin_port = htons(BIND_PORT);

    struct sockaddr_in dest_addr;
    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.sin_family = AF_INET;
#ifdef WIN32
    dest_addr.sin_addr.S_un.S_addr = inet_addr(drcom_config.server);
#else
    dest_addr.sin_addr.s_addr = inet_addr(drcom_config.server);
#endif
    dest_addr.sin_port = htons(DEST_PORT);

    srand(time(NULL));

    // create socket
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
#ifdef WIN32
        get_lasterror("Failed to create socket");
#else
        perror("Failed to create socket");
#endif
        return 1;
    }
    // bind socket
    if (bind(sockfd, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) < 0) {
#ifdef WIN32
        get_lasterror("Failed to bind socket");
#else
        perror("Failed to bind socket");
#endif
        return 1;
    }

    // set timeout
#ifdef WIN32
    int timeout = 3000;
#else
    struct timeval timeout;
    timeout.tv_sec = 3;
    timeout.tv_usec = 0;
#endif
    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
#ifdef WIN32
        get_lasterror("Failed to set sock opt");
#else
        perror("Failed to set sock opt");
#endif
        return 1;
    }

    // start dogcoming
    if (strcmp(mode, "dhcp") == 0) {
        int login_failed_attempts = 0;
        int try_JLUversion = 0;
        for (int try_counter = 0; try_counter < try_times; try_counter++) {
            if (eternal_flag) {
                try_counter = 0;
            }
            unsigned char seed[4];
            unsigned char auth_information[16];
            if (dhcp_challenge(sockfd, dest_addr, seed)) {
                printf("Retrying...\n");
                if (logging_flag) {
                    logging("Retrying...", NULL, 0);
                }
                sleep(3);
            } else {
                usleep(200000);  // 0.2 sec
                if (login_failed_attempts > 2) {
                    try_JLUversion = 1;
                }
                if (!dhcp_login(sockfd, dest_addr, seed, auth_information, try_JLUversion)) {
                    int keepalive_counter = 0;
                    int keepalive_try_counter = 0;
                    int first = 1;
                    while (1) {
                        if (!keepalive_1(sockfd, dest_addr, seed, auth_information)) {
                            usleep(200000);  // 0.2 sec
                            if (keepalive_2(sockfd, dest_addr, &keepalive_counter, &first, 0)) {
                                continue;
                            }
                            if (verbose_flag) {
                                printf("Keepalive in loop.\n");
                            }
                            if (logging_flag) {
                                logging("Keepalive in loop.", NULL, 0);
                            }
                            sleep(20);
                        } else {
                            if (keepalive_try_counter > 5) {
                                break;
                            }
                            keepalive_try_counter++;
                            continue;
                        }
                    }
                } else {
                    login_failed_attempts += 1;
                    printf("Retrying...\n");
                    if (logging_flag) {
                        logging("Retrying...", NULL, 0);
                    }
                    sleep(3);
                };
            }
        }
    } else if (strcmp(mode, "pppoe") == 0) {
        int pppoe_counter = 0;
        int keepalive_counter = 0;
        unsigned char seed[4], sip[4]; /* pppoe's seed == dhcp's KEEP_ALIVE_VERSION */
        int login_first = 1;
        int first = 1;
        int encrypt_mode = 0;
        int encrypt_type = 0;
        int try_counter = 0;
        while (1) {
            if (pppoe_challenge(sockfd, dest_addr, &pppoe_counter, seed, sip, &encrypt_mode)) {
                printf("Retrying...\n");
                if (logging_flag) {
                    logging("Retrying...", NULL, 0);
                }
                login_first = 1;
                try_counter++;
                if (eternal_flag) {
                    try_counter = 0;
                }
                if (try_counter >= try_times) {
                    break;
                }
                sleep(5);
                continue;
            } else {
                usleep(200000);  // 0.2 sec
                if (pppoe_login(sockfd, dest_addr, &pppoe_counter, seed, sip, &login_first, &encrypt_mode, &encrypt_type)) {
                    continue;
                } else {
                    login_first = 0;
                    if (keepalive_2(sockfd, dest_addr, &keepalive_counter, &first, &encrypt_type)) {
                        continue;
                    } else {
                        if (verbose_flag) {
                            printf("PPPoE in loop.\n");
                        }
                        if (logging_flag) {
                            logging("PPPoE in loop.", NULL, 0);
                        }
                        sleep(10);
                        continue;
                    }
                }
            }
        }
    }

    printf(">>>>> Failed to keep in touch with server, exiting <<<<<\n\n");
    if (logging_flag) {
        logging(">>>>> Failed to keep in touch with server, exiting <<<<<", NULL, 0);
    }
#ifdef WIN32
    closesocket(sockfd);
    WSACleanup();
#else
    close(sockfd);
#endif
    return 1;
}

void print_packet(char msg[10], unsigned char *packet, int length) {
    printf("%s", msg);
    for (int i = 0; i < length; i++) {
        printf("%02x", packet[i]);
    }
    printf("\n");
}

void logging(char msg[10], unsigned char *packet, int length) {
    FILE *ptr_file;
    ptr_file = fopen(log_path, "a");

    char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    time_t timep;
    struct tm *p;
    time(&timep);
    p = localtime(&timep);
    fprintf(ptr_file, "[%04d/%02d/%02d %s %02d:%02d:%02d] ",
            (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday, wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);

    fprintf(ptr_file, "%s", msg);
    for (int i = 0; i < length; i++) {
        fprintf(ptr_file, "%02x", packet[i]);
    }
    fprintf(ptr_file, "\n");

    fclose(ptr_file);
}

#ifdef WIN32
void get_lasterror(char *msg) {
    char err_msg[256];
    err_msg[0] = '\0';
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL,
                  WSAGetLastError(),
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                  err_msg,
                  sizeof(err_msg),
                  NULL);
    fprintf(stderr, "%s: %s", msg, err_msg);
}
#endif

================================================
FILE: auth.h
================================================
#ifndef AUTH_H_
#define AUTH_H_

#ifdef WIN32
#include <winsock2.h>
#else
#include <netinet/in.h>
#endif

enum {
    CHECK_MAC = 0x01,
    SERVER_BUSY = 0x02,
    WRONG_PASS = 0x03,
    NOT_ENOUGH = 0x04,
    FREEZE_UP = 0x05,
    NOT_ON_THIS_IP = 0x07,
    NOT_ON_THIS_MAC = 0x0B,
    TOO_MUCH_IP = 0x14,
    UPDATE_CLIENT = 0x15,
    NOT_ON_THIS_IP_MAC = 0x16,
    MUST_USE_DHCP = 0x17
};

int dhcp_challenge(int sockfd, struct sockaddr_in addr, unsigned char seed[]);
int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[], int try_JLUversion);
int pppoe_challenge(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *encrypt_mode);
int pppoe_login(int sockfd, struct sockaddr_in addr, int *pppoe_counter, unsigned char seed[], unsigned char sip[], int *first, int *encrypt_mode, int *encrypt_type);
int dogcom(int try_times);
void print_packet(char msg[10], unsigned char *packet, int length);
void logging(char msg[10], unsigned char *packet, int length);
void get_lasterror(char *msg);

#endif  // AUTH_H_

================================================
FILE: configparse.c
================================================
#include "configparse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "debug.h"

int verbose_flag = 0;
int logging_flag = 0;
int eapol_flag = 0;
int eternal_flag = 0;
char *log_path;
char mode[10];
char bind_ip[20];
struct config drcom_config;

static int read_d_config(char *buf, int size);
static int read_p_config(char *buf, int size);

int config_parse(char *filepath) {
    FILE *ptr_file;
    char buf[100];

    ptr_file = fopen(filepath, "r");
    if (!ptr_file) {
        printf("Failed to read config file.\n");
        exit(1);
    }

    while (fgets(buf, sizeof(buf), ptr_file)) {
        if (strcmp(mode, "dhcp") == 0) {
            read_d_config(buf, sizeof(buf));
        } else if (strcmp(mode, "pppoe") == 0) {
            read_p_config(buf, sizeof(buf));
        }
    }
    if (verbose_flag) {
        printf("\n\n");
    }
    fclose(ptr_file);

    return 0;
}

static int read_d_config(char *buf, int size) {
    if (verbose_flag) {
        printf("%s", buf);
    }

    char *delim = " ='\r\n";
    char *delim2 = "\\x";
    char *key;
    char *value;
    if (strlen(key = strtok(buf, delim))) {
        value = strtok(NULL, delim);
    }
    drcom_config.keepalive1_mod = 0;

    if (strcmp(key, "server") == 0) {
        strcpy(drcom_config.server, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.server));
    } else if (strcmp(key, "username") == 0) {
        strcpy(drcom_config.username, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.username));
    } else if (strcmp(key, "password") == 0) {
        strcpy(drcom_config.password, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.password));
    } else if (strcmp(key, "CONTROLCHECKSTATUS") == 0) {
        value = strtok(value, delim2);
        sscanf(value, "%02hhx", &drcom_config.CONTROLCHECKSTATUS);
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.CONTROLCHECKSTATUS));
    } else if (strcmp(key, "ADAPTERNUM") == 0) {
        value = strtok(value, delim2);
        sscanf(value, "%02hhx", &drcom_config.ADAPTERNUM);
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.ADAPTERNUM));
    } else if (strcmp(key, "host_ip") == 0) {
        strcpy(drcom_config.host_ip, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.host_ip));
    } else if (strcmp(key, "IPDOG") == 0) {
        value = strtok(value, delim2);
        sscanf(value, "%02hhx", &drcom_config.IPDOG);
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.IPDOG));
    } else if (strcmp(key, "host_name") == 0) {
        strcpy(drcom_config.host_name, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.host_name));
    } else if (strcmp(key, "PRIMARY_DNS") == 0) {
        strcpy(drcom_config.PRIMARY_DNS, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.PRIMARY_DNS));
    } else if (strcmp(key, "dhcp_server") == 0) {
        strcpy(drcom_config.dhcp_server, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.dhcp_server));
    } else if (strcmp(key, "AUTH_VERSION") == 0) {
        char *v1 = strtok(value, delim2);
        char *v2 = strtok(NULL, delim2);
        sscanf(v1, "%02hhx", v1);
        sscanf(v2, "%02hhx", v2);
        memcpy(&drcom_config.AUTH_VERSION[0], v1, 1);
        memcpy(&drcom_config.AUTH_VERSION[1], v2, 1);
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.AUTH_VERSION[0]));
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.AUTH_VERSION[1]));
    } else if (strcmp(key, "mac") == 0) {
        char *delim3 = "x";
        // strsep(&value, delim3);
        value = strtok(value, delim3);
        value = strtok(NULL, delim3);
        sscanf(value, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
               &drcom_config.mac[0],
               &drcom_config.mac[1],
               &drcom_config.mac[2],
               &drcom_config.mac[3],
               &drcom_config.mac[4],
               &drcom_config.mac[5]);
#ifdef DEBUG
        printf("[PARSER_DEBUG]0x");
        for (int i = 0; i < 6; i++) {
            printf("%02x", drcom_config.mac[i]);
        }
        printf("\n");
#endif
    } else if (strcmp(key, "host_os") == 0) {
        strcpy(drcom_config.host_os, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.host_os));
    } else if (strcmp(key, "KEEP_ALIVE_VERSION") == 0) {
        char *v1 = strtok(value, delim2);
        char *v2 = strtok(NULL, delim2);
        sscanf(v1, "%02hhx", v1);
        sscanf(v2, "%02hhx", v2);
        memcpy(&drcom_config.KEEP_ALIVE_VERSION[0], v1, 1);
        memcpy(&drcom_config.KEEP_ALIVE_VERSION[1], v2, 1);
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.KEEP_ALIVE_VERSION[0]));
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.KEEP_ALIVE_VERSION[1]));
    } else if (strcmp(key, "ror_version") == 0) {
        if (strcmp(value, "True") == 0) {
            drcom_config.ror_version = 1;
        } else {
            drcom_config.ror_version = 0;
        }
        DEBUG_PRINT(("\n[PARSER_DEBUG]\n%d\n", drcom_config.ror_version));
    } else if (strcmp(key, "keepalive1_mod") == 0) {
        if (strcmp(value, "True") == 0) {
            drcom_config.keepalive1_mod = 1;
        } else {
            drcom_config.keepalive1_mod = 0;
        }
        DEBUG_PRINT(("\n[PARSER_DEBUG]\n%d\n", drcom_config.keepalive1_mod));
    } else {
        return 1;
    }

    return 0;
}

static int read_p_config(char *buf, int size) {
    if (verbose_flag) {
        printf("%s", buf);
    }

    char *delim = " ='\r\n";
    char *delim2 = "\\x";
    char *key;
    char *value;
    if (strlen(key = strtok(buf, delim))) {
        value = strtok(NULL, delim);
    }

    if (strcmp(key, "server") == 0) {
        strcpy(drcom_config.server, value);
        DEBUG_PRINT(("[PARSER_DEBUG]%s\n", drcom_config.server));
    } else if (strcmp(key, "pppoe_flag") == 0) {
        value = strtok(value, delim2);
        sscanf(value, "%02hhx", &drcom_config.pppoe_flag);
        DEBUG_PRINT(("[PARSER_DEBUG]0x%02x\n", drcom_config.pppoe_flag));
    } else if (strcmp(key, "keep_alive2_flag") == 0) {
        value = strtok(value, delim2);
        sscanf(value, "%02hhx", &drcom_config.keep_alive2_flag);
        DEBUG_PRINT(("\n[PARSER_DEBUG]0x%02x\n", drcom_config.keep_alive2_flag));
    } else {
        return 1;
    }

    return 0;
}

================================================
FILE: configparse.h
================================================
#ifndef CONFIGPARSE_H_
#define CONFIGPARSE_H_

struct config {
    char server[20];
    char username[36];
    char password[20];
    unsigned char CONTROLCHECKSTATUS;
    unsigned char ADAPTERNUM;
    char host_ip[20];
    unsigned char IPDOG;
    char host_name[20];
    char PRIMARY_DNS[20];
    char dhcp_server[20];
    unsigned char AUTH_VERSION[2];
    unsigned char mac[6];
    char host_os[20];
    unsigned char KEEP_ALIVE_VERSION[2];
    int ror_version;
    int keepalive1_mod;
    unsigned char pppoe_flag;
    unsigned char keep_alive2_flag; /* abandoned */
};

extern struct config drcom_config;
extern int verbose_flag;
extern int logging_flag;
extern int eapol_flag;
extern int eternal_flag;
extern char *log_path;
extern char mode[10];
extern char bind_ip[20];

int config_parse(char *filepath);

#endif  // CONFIGPARSE_H_

================================================
FILE: daemon.c
================================================
#ifdef linux

#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "debug.h"

int daemon_flag = 0;
int pid_file_handle;

void kill_daemon() {
    close(pid_file_handle);
    remove("/tmp/dogcom.pid");
}

void signal_handler(int signal) {
    switch (signal) {
        case SIGHUP:
            break;
        case SIGINT:
            break;
        case SIGTERM:
            kill_daemon();
            exit(0);
            break;
        default:
            break;
    }
}

void daemonise() {
    pid_t pid;
    struct sigaction sig_action;
    sigset_t sigset;

    pid = fork();
    if (pid < 0) {
        printf("Fork failed!\n");
        exit(1);
    } else if (pid > 0) {
        DEBUG_PRINT(("PID is %d.\n", pid));
        exit(0);
    }
    if (setsid() < 0) {
        printf("Setsid failed!\n");
        exit(1);
    }

    sigemptyset(&sigset);
    sigaddset(&sigset, SIGCHLD);
    sigaddset(&sigset, SIGTSTP);
    sigaddset(&sigset, SIGTTOU);
    sigaddset(&sigset, SIGTTIN);
    sigprocmask(SIG_BLOCK, &sigset, NULL);
    sig_action.sa_handler = signal_handler;
    sigemptyset(&sig_action.sa_mask);
    sig_action.sa_flags = 0;
    sigaction(SIGHUP, &sig_action, NULL);
    sigaction(SIGTERM, &sig_action, NULL);
    sigaction(SIGINT, &sig_action, NULL);

    pid = fork();
    if (pid < 0) {
        printf("Fork failed!\n");
        exit(1);
    } else if (pid > 0) {
        DEBUG_PRINT(("PID is %d.\n", pid));
        exit(0);
    }

    chdir("/tmp/");
    umask(027);

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    open("/dev/null", O_RDONLY);
    open("/dev/null", O_WRONLY);
    open("/dev/null", O_RDWR);

    pid_file_handle = open("/tmp/dogcom.pid", O_RDWR | O_CREAT, 0600);
    if (pid_file_handle < 0) {
        exit(1);
    }
    if (lockf(pid_file_handle, F_TLOCK, 0) < 0) {
        exit(1);
    }

    char spid[10];
    sprintf(spid, "%d\n", getpid());
    write(pid_file_handle, spid, strlen(spid));
}

#endif

================================================
FILE: daemon.h
================================================
#ifndef DAEMON_H_
#define DAEMON_H_

void kill_daemon();
void signal_handler(int signal);
void daemonise();

extern int daemon_flag;
extern int pid_file_handle;

#endif  // DAEMON_H_

================================================
FILE: debug.h
================================================
#ifdef DEBUG
#define DEBUG_PRINT(s) printf s
#else
#define DEBUG_PRINT(s) \
    do {               \
    } while (0)
#endif

================================================
FILE: eapol.c
================================================
#ifdef linux

#include "eapol.h"
#include "libs/common.h"
#include "libs/md5.h"

#include <arpa/inet.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <netpacket/packet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define BUFF_LEN (512)

static uchar client_mac[ETH_ALEN];

static uchar sendbuff[BUFF_LEN];
static uchar recvbuff[BUFF_LEN];
static char ifname[IFNAMSIZ] = "eth0";
static ethII_t *sendethii, *recvethii;
static eapol_t *sendeapol, *recveapol;
static eap_t *sendeap, *recveap;
static eapbody_t *sendeapbody, *recveapbody;

static char _uname[UNAME_LEN];
static char _pwd[PWD_LEN];
static int pwdlen;

static int eap_keep_alive(int skfd, struct sockaddr const *skaddr);
static int eap_md5_clg(int skfd, struct sockaddr const *skaddr);
static int eap_res_identity(int skfd, struct sockaddr const *skaddr);
static int eapol_init(int *skfd, struct sockaddr *skaddr);
static int eapol_start(int skfd, struct sockaddr const *skaddr);
static int eapol_logoff(int skfd, struct sockaddr const *skaddr);
static int filte_req_identity(int skfd, struct sockaddr const *skaddr);
static int filte_req_md5clg(int skfd, struct sockaddr const *skaddr);
static int filte_success(int skfd, struct sockaddr const *skaddr);
static int eap_daemon(int skfd, struct sockaddr const *skaddr);

/*
 * 初始化缓存区,生产套接字和地址接口信息
 * skfd: 被初始化的socket
 * skaddr: 被初始化地址接口信息
 * @return: 0: 成功
 *          -1: 初始化套接字失败
 *          -2: 初始化地址信息失败
 */
static int eapol_init(int *skfd, struct sockaddr *skaddr) {
    struct ifreq ifr;
    struct sockaddr_ll *skllp = (struct sockaddr_ll *)skaddr;
    sendethii = (ethII_t *)sendbuff;
    sendeapol = (eapol_t *)((uchar *)sendethii + sizeof(ethII_t));
    sendeap = (eap_t *)((uchar *)sendeapol + sizeof(eapol_t));
    sendeapbody = (eapbody_t *)((uchar *)sendeap + sizeof(eap_t));
    recvethii = (ethII_t *)recvbuff;
    recveapol = (eapol_t *)((uchar *)recvethii + sizeof(ethII_t));
    recveap = (eap_t *)((uchar *)recveapol + sizeof(eapol_t));
    recveapbody = (eapbody_t *)((uchar *)recveap + sizeof(eap_t));

    if (-1 == (*skfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))) {
        perror("Socket");
        return -1;
    }
    /* 先假定就是eth0接口 */
    memset(skaddr, 0, sizeof(struct sockaddr_ll));
    memset(&ifr, 0, sizeof(struct ifreq));
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
    if (-1 == ioctl(*skfd, SIOCGIFINDEX, &ifr)) {
        perror("Get index");
        goto addr_err;
    }
    skllp->sll_ifindex = ifr.ifr_ifindex;
    _D("%s's index: %d\n", ifname, skllp->sll_ifindex);
    if (-1 == ioctl(*skfd, SIOCGIFHWADDR, &ifr)) {
        perror("Get MAC");
        goto addr_err;
    }
    memcpy(client_mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
    _D("%s's MAC: %02X-%02X-%02X-%02X-%02X-%02X\n", ifname,
       client_mac[0], client_mac[1], client_mac[2],
       client_mac[3], client_mac[4], client_mac[5]);
    skllp->sll_family = PF_PACKET;
    /*skllp->sll_protocol = ETH_P_ARP;*/
    /*skllp->sll_ifindex = ? 已给出 */
    skllp->sll_hatype = ARPHRD_ETHER;
    skllp->sll_pkttype = PACKET_HOST;
    skllp->sll_halen = ETH_ALEN;
    return 0;

addr_err:
    close(*skfd);
    return -2;
}

/*
 * 过滤得到eap-request-identity包
 * @return: 0: 成功获取
 *          -1: 超时
 */
static int filte_req_identity(int skfd, struct sockaddr const *skaddr) {
    (void)skaddr;
    int stime = time((time_t *)NULL);
    for (; difftime(time((time_t *)NULL), stime) <= TIMEOUT;) {
        /* TODO 看下能不能只接受某类包,包过滤 */
        recvfrom(skfd, recvbuff, BUFF_LEN, 0, NULL, NULL);
        /* eap包且是request */
        if (recvethii->type == htons(ETHII_8021X) && mac_equal(recvethii->dst_mac, client_mac) && recveapol->type == EAPOL_PACKET && recveap->code == EAP_CODE_REQ && recveap->type == EAP_TYPE_IDEN) {
            return 0;
        }
    }
    return -1;
}
/*
 * 过滤得到eap-request-md5clg包
 * @return: 0: 成功获取
 *          -1: 超时
 *          -2: 服务器中止登录,用户名不存在
 */
static int filte_req_md5clg(int skfd, struct sockaddr const *skaddr) {
    (void)skaddr;
    int stime = time((time_t *)NULL);
    for (; difftime(time((time_t *)NULL), stime) <= TIMEOUT;) {
        recvfrom(skfd, recvbuff, BUFF_LEN, 0, NULL, NULL);
        /* 是request且是eap-request-md5clg */
        if (recvethii->type == htons(ETHII_8021X) && mac_equal(recvethii->dst_mac, client_mac) && recveapol->type == EAPOL_PACKET) {
            if (recveap->code == EAP_CODE_REQ && recveap->type == EAP_TYPE_MD5) {
#ifdef DEBUG
                _M("id: %d\n", sendeap->id);
                _M("md5: ");
                int i;
                for (i = 0; i < recveapbody->md5size; ++i)
                    _M("%.2x", recveapbody->md5value[i]);
                _M("\n");
                _M("ex-md5: ");
                for (i = 0; i < ntohs(recveap->len) - recveapbody->md5size - 2; ++i)
                    _M("%.2x", recveapbody->md5exdata[i]);
                _M("\n");
#endif
                return 0;
            } else if (recveap->id == sendeap->id && recveap->code == EAP_CODE_FAIL) {
                _D("id: %d fail.\n", sendeap->id);
                return -2;
            }
        }
    }
    return -1;
}
/*
 * 过滤得到登录成功包
 * @return: 0: 成功获取
 *          -1: 超时
 *          -2: 服务器中止登录,密码错误吧
 */
static int filte_success(int skfd, struct sockaddr const *skaddr) {
    (void)skaddr;
    int stime = time((time_t *)NULL);
    for (; difftime(time((time_t *)NULL), stime) <= TIMEOUT;) {
        recvfrom(skfd, recvbuff, BUFF_LEN, 0, NULL, NULL);
        if (recvethii->type == htons(ETHII_8021X) && mac_equal(recvethii->dst_mac, client_mac) && recveapol->type == EAPOL_PACKET) {
            if (recveap->id == sendeap->id && recveap->code == EAP_CODE_SUCS) {
                _D("id: %d login success.\n", sendeap->id);
                return 0;
            } else if (recveap->id == sendeap->id && recveap->code == EAP_CODE_FAIL) {
                _D("id: %d fail.\n", sendeap->id);
                return -2;
            }
        }
    }
    return -1;
}
/*
 * 广播发送eapol-start
 */
static int eapol_start(int skfd, struct sockaddr const *skaddr) {
    /* 这里采用eap标记的组播mac地址,也许采用广播也可以吧 */
    uchar broadcast_mac[ETH_ALEN] = {
        //		0x01, 0x80, 0xc2, 0x00, 0x00, 0x03,
        0xff,
        0xff,
        0xff,
        0xff,
        0xff,
        0xff,
    };
    memcpy(sendethii->dst_mac, broadcast_mac, ETH_ALEN);
    memcpy(sendethii->src_mac, client_mac, ETH_ALEN);
    sendethii->type = htons(ETHII_8021X);
    sendeapol->ver = EAPOL_VER;
    sendeapol->type = EAPOL_START;
    sendeapol->len = 0x0;
    sendto(skfd, sendbuff, ETH_ALEN * 2 + 6, 0, skaddr, sizeof(struct sockaddr_ll));
    return 0;
}
/* 退出登录 */
static int eapol_logoff(int skfd, struct sockaddr const *skaddr) {
    uchar broadcast_mac[ETH_ALEN] = {
        //		0x01, 0x80, 0xc2, 0x00, 0x00, 0x03,
        0xff,
        0xff,
        0xff,
        0xff,
        0xff,
        0xff,
    };
    memcpy(sendethii->dst_mac, broadcast_mac, ETH_ALEN);
    memcpy(sendethii->src_mac, client_mac, ETH_ALEN);
    sendethii->type = htons(ETHII_8021X);
    sendeapol->ver = EAPOL_VER;
    sendeapol->type = EAPOL_LOGOFF;
    sendeapol->len = 0x0;
    sendeap->id = EAPOL_LOGOFF_ID;
    sendto(skfd, sendbuff, ETH_ALEN * 2 + 6, 0, skaddr, sizeof(struct sockaddr_ll));
    return 0;
}
/* 回应request-identity */
static int eap_res_identity(int skfd, struct sockaddr const *skaddr) {
    memcpy(sendethii->dst_mac, recvethii->src_mac, ETH_ALEN);
    sendeapol->type = EAPOL_PACKET;
    sendeapol->len = htons(sizeof(eap_t) + sizeof(eapbody_t));
    sendeap->code = EAP_CODE_RES;
    sendeap->id = recveap->id;
    sendeap->len = htons(sizeof(eapbody_t));
    sendeap->type = EAP_TYPE_IDEN;
    strncpy((char *)sendeapbody->identity, _uname, UNAME_LEN);
    sendto(skfd, sendbuff, ETH_ALEN * 2 + 6 + 5 + sizeof(eapbody_t),
           0, skaddr, sizeof(struct sockaddr_ll));
    return 0;
}
/* 回应md5clg */
static int eap_md5_clg(int skfd, struct sockaddr const *skaddr) {
    uchar md5buff[BUFF_LEN];
    sendeap->id = recveap->id;
    sendeap->len = htons(sizeof(eapbody_t));
    sendeap->type = EAP_TYPE_MD5;
    sendeapbody->md5size = recveapbody->md5size;
    memcpy(md5buff, &sendeap->id, 1);
    memcpy(md5buff + 1, _pwd, pwdlen);
    memcpy(md5buff + 1 + pwdlen, recveapbody->md5value, recveapbody->md5size);
    MD5(md5buff, 1 + pwdlen + recveapbody->md5size, sendeapbody->md5value);
    memcpy((char *)sendeapbody->md5exdata, _uname, strlen(_uname));
    sendto(skfd, sendbuff, ETH_ALEN * 2 + 6 + 5 + sizeof(eapbody_t),
           0, skaddr, sizeof(struct sockaddr_ll));
    return 0;
}

/*
 * 保持在线
 * eap心跳包
 * 某些eap实现需要心跳或多次认证
 * 目前有些服务器会有如下特征
 * 每一分钟,服务端发送一个request-identity包来判断是否在线
 */
static int eap_keep_alive(int skfd, struct sockaddr const *skaddr) {
    int status;
    time_t stime, etime;
    /* EAP_KPALV_TIMEOUT时间内已经不再有心跳包,我们认为服务器不再需要心跳包了 */
    //for (; difftime(time((time_t*)NULL), stime) <= EAP_KPALV_TIMEOUT; ) {
    stime = time((time_t *)NULL);
    for (;;) {
        status = filte_req_identity(skfd, skaddr);
        //_D("%s: [EAP:KPALV] get status: %d\n", format_time(), status);
        if (0 == status) {
            etime = time((time_t *)NULL);
            _D("dtime: %fs\n", difftime(etime, stime));
            if (difftime(etime, stime) <= 10) {
                stime = time((time_t *)NULL);
                continue;
            }
            stime = time((time_t *)NULL);
#if 0
#ifdef DEBUG
			_D("[KPALV] get eap request identity:\n");
			_D("dst<-src: %2X:%2X:%2X:%2X:%2X:%2X <- %2X:%2X:%2X:%2X:%2X:%2X\n",
					recvethii->dst_mac[0], recvethii->dst_mac[1], recvethii->dst_mac[2],
					recvethii->dst_mac[3], recvethii->dst_mac[4], recvethii->dst_mac[5],
					recvethii->src_mac[0], recvethii->src_mac[1], recvethii->src_mac[2],
					recvethii->src_mac[3], recvethii->src_mac[4], recvethii->src_mac[5]);
			_D("ethII.type: 0x%4x\n", ntohs(recvethii->type));
			_D("recveapol.type: %s\n", recveapol->type==EAPOL_PACKET?"EAPOL_PACKET":"UNKNOWN");
			_D("recveapol.len: %d\n", ntohs(recveapol->len));
			_D("recveap.code: %s\n", recveap->code==EAP_CODE_REQ?"EAP_CODE_REQ":"UNKNOWN");
			_D("recveap.id: %d\n", recveap->id);
			_D("recveap.type: %s\n", recveap->type==EAP_TYPE_IDEN?"EAP_TYPE_IDEN":"UNKNOWN");
#endif
#endif
            _M("%s: [EAP:KPALV] get a request-identity\n", format_time());
            eap_res_identity(skfd, skaddr);
#if 0
#ifdef DEBUG
			_D("[EAP:KPALV] send eap response identity:\n");
			_D("dst<-src: %2X:%2X:%2X:%2X:%2X:%2X <- %2X:%2X:%2X:%2X:%2X:%2X\n",
					sendethii->dst_mac[0], sendethii->dst_mac[1], sendethii->dst_mac[2],
					sendethii->dst_mac[3], sendethii->dst_mac[4], sendethii->dst_mac[5],
					sendethii->src_mac[0], sendethii->src_mac[1], sendethii->src_mac[2],
					sendethii->src_mac[3], sendethii->src_mac[4], sendethii->src_mac[5]);
			_D("ethII.type: 0x%4x\n", ntohs(sendethii->type));
			_D("sendeapol.type: %s\n", sendeapol->type==EAPOL_PACKET?"EAPOL_PACKET":"UNKNOWN");
			_D("sendeapol.len: %d\n", ntohs(sendeapol->len));
			_D("sendeap.code: %s\n", sendeap->code==EAP_CODE_RES?"EAP_CODE_RES":"UNKNOWN");
			_D("sendeap.id: %d\n", sendeap->id);
			_D("sendeap.type: %s\n", sendeap->type==EAP_TYPE_IDEN?"EAP_TYPE_IDEN":"UNKNOWN");
			_D("sendeapbody.identity: %s\n", sendeapbody->identity);
#endif
#endif
        }
        status = -1;
    }
    return 0;
}
/*
 * 后台心跳进程
 * @return: 0, 正常运行
 * 			-1, 运行失败
 */
static int eap_daemon(int skfd, struct sockaddr const *skaddr) {
    /* 如果存在原来的keep alive进程,就干掉他 */
#define PID_FILE "/tmp/cwnu-drcom-eap.pid"
    FILE *kpalvfd = fopen(PID_FILE, "r+");
    if (NULL == kpalvfd) {
        _M("[EAP:KPALV] No process pidfile. %s: %s\n", PID_FILE, strerror(errno));
        kpalvfd = fopen(PID_FILE, "w+"); /* 不存在,创建 */
        if (NULL == kpalvfd) {
            _M("[EAP:KPALV] Detect pid file eror(%s)! quit!\n", strerror(errno));
            return -1;
        }
    }
    pid_t oldpid;

    fseek(kpalvfd, 0L, SEEK_SET);
    if ((1 == fscanf(kpalvfd, "%d", (int *)&oldpid)) && (oldpid != (pid_t)-1)) {
        _D("oldkpalv pid: %d\n", oldpid);
        kill(oldpid, SIGKILL);
    }
    setsid();
    if (0 != chdir("/"))
        _M("[EAP:KPALV:WARN] %s\n", strerror(errno));
    umask(0);
    /* 在/tmp下写入自己(keep alive)pid */
    pid_t curpid = getpid();
    _D("kpalv curpid: %d\n", curpid);
    /*
	 * if (0 != ftruncate(fileno(kpalvfd), 0))
	 * 这个写法有时不能正常截断文件,截断后前面有\0?
	 */
    if (NULL == (kpalvfd = freopen(PID_FILE, "w+", kpalvfd)))
        _M("[EAP:KPALV:WARN] truncat pidfile '%s': %s\n", PID_FILE, strerror(errno));
    fprintf(kpalvfd, "%d", curpid);
    fflush(kpalvfd);
    if (0 == eap_keep_alive(skfd, skaddr)) {
        _M("%s: [EAP:KPALV] Server maybe not need keep alive paket.\n", format_time());
        _M("%s: [EAP:KPALV] Now, keep alive process quit!\n", format_time());
    }
    if (NULL == (kpalvfd = freopen(PID_FILE, "w+", kpalvfd)))
        _M("[EAP:KPALV:WARN] truncat pidfile '%s': %s\n", PID_FILE, strerror(errno));
    fprintf(kpalvfd, "-1"); /* 写入-1表示已经离开 */
    fflush(kpalvfd);
    fclose(kpalvfd);

    return 0;
}

/*
 * eap认证
 * uname: 用户名
 * pwd: 密码
 * @return: 0: 成功
 *          1: 用户不存在
 *          2: 密码错误
 *          3: 其他超时
 *          4: 服务器拒绝请求登录
 *          -1: 没有找到合适网络接口
 *          -2: 没有找到服务器
 */
int eaplogin(char const *uname, char const *pwd) {
    int i;
    int state;
    int skfd;
    struct sockaddr_ll ll;

    _M("Use user '%s' to login...\n", uname);
    _M("[EAP:0] Initilize interface...\n");
    strncpy(_uname, uname, UNAME_LEN);
    strncpy(_pwd, pwd, PWD_LEN);
    pwdlen = strlen(_pwd);
    if (0 != eapol_init(&skfd, (struct sockaddr *)&ll))
        return -1;
    /* 无论如何先请求一下下线 */
    eapol_logoff(skfd, (struct sockaddr *)&ll);
    /* eap-start */
    _M("[EAP:1] Send eap-start...\n");
    for (i = 0; i < TRY_TIMES; ++i) {
        eapol_start(skfd, (struct sockaddr *)&ll);
        if (0 == filte_req_identity(skfd, (struct sockaddr *)&ll))
            break;
        _M(" [EAP:1] %dth Try send eap-start...\n", i + 1);
    }
    if (i >= TRY_TIMES) goto _timeout;

    /* response-identity */
    _M("[EAP:2] Send response-identity...\n");
    for (i = 0; i < TRY_TIMES; ++i) {
        eap_res_identity(skfd, (struct sockaddr *)&ll);
        state = filte_req_md5clg(skfd, (struct sockaddr *)&ll);
        if (0 == state)
            break;
        else if (-2 == state)
            goto _no_uname;
        _M(" [EAP:2] %dth Try send response-identity...\n", i + 1);
    }
    if (i >= TRY_TIMES) goto _timeout;

    /* response-md5clg */
    _M("[EAP:3] Send response-md5clg...\n");
    for (i = 0; i < TRY_TIMES; ++i) {
        eap_md5_clg(skfd, (struct sockaddr *)&ll);
        state = filte_success(skfd, (struct sockaddr *)&ll);
        if (0 == state) {
            _M("[EAP:4] Login success.\n");
            break; /* 登录成功 */
        } else if (-2 == state)
            goto _pwd_err;
        _M(" [EAP:3] %dth Try send response-md5clg...\n", i + 1);
    }
    if (i >= TRY_TIMES) goto _timeout;

    /* 登录成功,生成心跳进程 */
    switch (fork()) {
        case 0:
            if (0 != eap_daemon(skfd, (struct sockaddr *)&ll)) {
                _M("[EAP:ERROR] Create daemon process to keep alive error!\n");
                close(skfd);
                exit(1);
            }
            exit(0);
            break;
        case -1:
            _M("[EAP:WARN] Cant create daemon, maybe `OFFLINE` after soon.\n");
    }
    close(skfd);
    return 0;

_timeout:
    _M("[EAP:ERROR] Not server in range.\n");
    close(skfd);
    return -2;
_no_uname:
    _M("[EAP:ERROR] No this user(%s).\n", uname);
    close(skfd);
    return 1;
_pwd_err:
    _M("[EAP:ERROR] The server refuse to login. Password error.\n");
    close(skfd);
    return 4;
}

int eaplogoff(void) {
    int skfd;
    struct sockaddr_ll ll;
    int state;
    int i;

    _M("[EAP:0] Initilize interface...\n");
    if (0 != eapol_init(&skfd, (struct sockaddr *)&ll))
        return -1;
    _M("[EAP:1] Requset logoff...\n");
    for (i = 0; i < TRY_TIMES; ++i) {
        eapol_logoff(skfd, (struct sockaddr *)&ll);
        state = filte_success(skfd, (struct sockaddr *)&ll);
        if (-2 == state) {
            _M("[EAP:2] Logoff!\n");
            return 0;
        }
        _M(" [EAP:1] %dth Try Requset logoff...\n", i + 1);
    }
    _M("[EAP:ERROR] Not server in range. or You were logoff.\n");
    return -1;
}

int eaprefresh(char const *uname, char const *pwd) {
    return eaplogin(uname, pwd);
}

/* 设置ifname */
void setifname(char const *_ifname) {
    strncpy(ifname, _ifname, IFNAMSIZ);
}

#endif

================================================
FILE: eapol.h
================================================
#ifndef EAPOL_H__
#define EAPOL_H__

#include "libs/common.h"

#define IDEN_LEN UNAME_LEN

#define TRY_TIMES (3)
/* 每次请求超过TIMEOUT秒,就重新请求一次 */
#define TIMEOUT (3)
/* eap 在EAP_KPALV_TIMEOUT秒内没有回应,认为不需要心跳 */
#define EAP_KPALV_TIMEOUT (420) /* 7分钟 */

/* ethii层取0x888e表示上层是8021.x */
#define ETHII_8021X (0x888e)

#define EAPOL_VER (0x01)
#define EAPOL_PACKET (0x00)
#define EAPOL_START (0x01)
#define EAPOL_LOGOFF (0x02)
/* 貌似请求下线的id都是这个 */
#define EAPOL_LOGOFF_ID (255)

#define EAP_CODE_REQ (0x01)
#define EAP_CODE_RES (0x02)
#define EAP_CODE_SUCS (0x03)
#define EAP_CODE_FAIL (0x04)
#define EAP_TYPE_IDEN (0x01)
#define EAP_TYPE_MD5 (0x04)

#pragma pack(1)
/* ethii 帧 */
/* 其实这个和struct ether_header是一样的结构 */
typedef struct {
    uchar dst_mac[ETH_ALEN];
    uchar src_mac[ETH_ALEN];
    uint16 type; /* 取值0x888e,表明是8021.x */
} ethII_t;
/* eapol 帧 */
typedef struct {
    uchar ver; /* 取值0x01 */
    /*
     * 0x00: eapol-packet
     * 0x01: eapol-start
     * 0x02: eapol-logoff
     */
    uchar type;
    uint16 len;
} eapol_t;
/* eap报文头 */
typedef struct {
    /*
     * 0x01: request
     * 0x02: response
     * 0x03: success
     * 0x04: failure
     */
    uchar code;
    uchar id;
    uint16 len;
    /*
     * 0x01: identity
     * 0x04: md5-challenge
     */
    uchar type;
} eap_t;
/* 报文体 */
#define MD5_SIZE 16
#define STUFF_LEN (64)
typedef union {
    uchar identity[IDEN_LEN];
    struct {
        uchar _size;
        uchar _md5value[MD5_SIZE];
        uchar _exdata[STUFF_LEN];
    } md5clg;
} eapbody_t;
#define md5size md5clg._size
#define md5value md5clg._md5value
#define md5exdata md5clg._exdata
#pragma pack()

/*
 * eap认证
 * uname: 用户名
 * pwd: 密码
 * @return: 0: 成功
 *          1: 用户不存在
 *          2: 密码错误
 *          3: 其他超时
 *          4: 服务器拒绝请求登录
 *          -1: 没有找到合适网络接口
 *          -2: 没有找到服务器
 */
extern int eaplogin(char const *uname, char const *pwd);
/*
 * eap下线
 */
extern int eaplogoff(void);
/*
 * eap重新登录
 */
extern int eaprefresh(char const *uname, char const *pwd);
/*
 * 用来设置ifname
 */
extern void setifname(char const *ifname);
// #ifdef WIN32
/*
 * 由于windows下实现进程的特殊性,这里把eap_daemon导出给main_cli使用
 * ifname: 心跳的物理接口名字
 * @return: 0: keep alive 进程正常退出,也许并不需要心跳进程
 *         !0: 错误原因导致keep alive 进程退出,也许是没法创建进程
 */
// extern int eap_daemon(char const *ifname);
// #endif /* WINDOWS */
#undef IDEN_LEN

#endif


================================================
FILE: keepalive.c
================================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef WIN32
#include <winsock2.h>
typedef int socklen_t;
#else
#include <netinet/in.h>
#include <sys/socket.h>
#endif

#include "auth.h"
#include "configparse.h"
#include "debug.h"
#include "keepalive.h"
#include "libs/md4.h"
#include "libs/md5.h"
#include "libs/sha1.h"

int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[]) {
    if (drcom_config.keepalive1_mod) {
        unsigned char keepalive_1_packet1[8] = {0x07, 0x01, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00};
        unsigned char recv_packet1[1024], keepalive_1_packet2[38], recv_packet2[1024];
        memset(keepalive_1_packet2, 0, 38);
        sendto(sockfd, keepalive_1_packet1, 8, 0, (struct sockaddr *)&addr, sizeof(addr));
        if (verbose_flag) {
            print_packet("[Keepalive1_packet1 sent] ", keepalive_1_packet1, 8);
        }
        if (logging_flag) {
            logging("[Keepalive1_packet1 sent] ", keepalive_1_packet1, 8);
        }
#ifdef TEST
        printf("[TEST MODE]IN TEST MODE, PASS\n");
        return 0;
#endif
        socklen_t addrlen = sizeof(addr);
        while (1) {
            if (recvfrom(sockfd, recv_packet1, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
                get_lasterror("Failed to recv data");
#else
                perror("Failed to recv data");
#endif
                return 1;
            } else {
                if (verbose_flag) {
                    print_packet("[Keepalive1 challenge_recv] ", recv_packet1, 100);
                }
                if (logging_flag) {
                    logging("[Keepalive1 challenge_recv] ", recv_packet1, 100);
                }

                if (recv_packet1[0] == 0x07) {
                    break;
                } else if (recv_packet1[0] == 0x4d) {
                    DEBUG_PRINT(("Get notice packet.\n"));
                    continue;
                } else {
                    printf("Bad keepalive1 challenge response received.\n");
                    return 1;
                }
            }
        }

        unsigned char keepalive1_seed[4] = {0};
        int encrypt_type;
        unsigned char crc[8] = {0};
        memcpy(keepalive1_seed, &recv_packet1[8], 4);
        encrypt_type = keepalive1_seed[0] & 3;
        gen_crc(keepalive1_seed, encrypt_type, crc);
        keepalive_1_packet2[0] = 0xff;
        memcpy(keepalive_1_packet2 + 8, keepalive1_seed, 4);
        memcpy(keepalive_1_packet2 + 12, crc, 8);
        memcpy(keepalive_1_packet2 + 20, auth_information, 16);
        keepalive_1_packet2[36] = rand() & 0xff;
        keepalive_1_packet2[37] = rand() & 0xff;

        sendto(sockfd, keepalive_1_packet2, 38, 0, (struct sockaddr *)&addr, sizeof(addr));
        if (verbose_flag) {
            print_packet("[Keepalive1_packet2 sent] ", keepalive_1_packet2, 38);
        }
        if (logging_flag) {
            logging("[Keepalive1_packet2 sent] ", keepalive_1_packet2, 38);
        }

        if (recvfrom(sockfd, recv_packet2, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
            get_lasterror("Failed to recv data");
#else
            perror("Failed to recv data");
#endif
            return 1;
        } else {
            if (verbose_flag) {
                print_packet("[Keepalive1 recv] ", recv_packet2, 100);
            }
            if (logging_flag) {
                logging("[Keepalive1 recv] ", recv_packet2, 100);
            }

            if (recv_packet2[0] != 0x07) {
                printf("Bad keepalive1 response received.\n");
                return 1;
            }
        }

    } else {
        unsigned char keepalive_1_packet[42], recv_packet[1024], MD5A[16];
        memset(keepalive_1_packet, 0, 42);
        keepalive_1_packet[0] = 0xff;
        int MD5A_len = 6 + strlen(drcom_config.password);
        unsigned char MD5A_str[MD5A_len];
        MD5A_str[0] = 0x03;
        MD5A_str[1] = 0x01;
        memcpy(MD5A_str + 2, seed, 4);
        memcpy(MD5A_str + 6, drcom_config.password, strlen(drcom_config.password));
        MD5(MD5A_str, MD5A_len, MD5A);
        memcpy(keepalive_1_packet + 1, MD5A, 16);
        memcpy(keepalive_1_packet + 20, auth_information, 16);
        keepalive_1_packet[36] = rand() & 0xff;
        keepalive_1_packet[37] = rand() & 0xff;

        sendto(sockfd, keepalive_1_packet, 42, 0, (struct sockaddr *)&addr, sizeof(addr));

        if (verbose_flag) {
            print_packet("[Keepalive1 sent] ", keepalive_1_packet, 42);
        }
        if (logging_flag) {
            logging("[Keepalive1 sent] ", keepalive_1_packet, 42);
        }

#ifdef TEST
        printf("[TEST MODE]IN TEST MODE, PASS\n");
        return 0;
#endif

        socklen_t addrlen = sizeof(addr);
        while (1) {
            if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
                get_lasterror("Failed to recv data");
#else
                perror("Failed to recv data");
#endif
                return 1;
            } else {
                if (verbose_flag) {
                    print_packet("[Keepalive1 recv] ", recv_packet, 100);
                }
                if (logging_flag) {
                    logging("[Keepalive1 recv] ", recv_packet, 100);
                }

                if (recv_packet[0] == 0x07) {
                    break;
                } else if (recv_packet[0] == 0x4d) {
                    DEBUG_PRINT(("Get notice packet."));
                    continue;
                } else {
                    printf("Bad keepalive1 response received.\n");
                    return 1;
                }
            }
        }
    }

    return 0;
}

void gen_crc(unsigned char seed[], int encrypt_type, unsigned char crc[]) {
    if (encrypt_type == 0) {
        char DRCOM_DIAL_EXT_PROTO_CRC_INIT[4] = {0xc7, 0x2f, 0x31, 0x01};
        char gencrc_tmp[4] = {0x7e};
        memcpy(crc, DRCOM_DIAL_EXT_PROTO_CRC_INIT, 4);
        memcpy(crc + 4, gencrc_tmp, 4);
    } else if (encrypt_type == 1) {
        unsigned char hash[32] = {0};
        MD5(seed, 4, hash);
        crc[0] = hash[2];
        crc[1] = hash[3];
        crc[2] = hash[8];
        crc[3] = hash[9];
        crc[4] = hash[5];
        crc[5] = hash[6];
        crc[6] = hash[13];
        crc[7] = hash[14];
    } else if (encrypt_type == 2) {
        unsigned char hash[32] = {0};
        MD4(seed, 4, hash);
        crc[0] = hash[1];
        crc[1] = hash[2];
        crc[2] = hash[8];
        crc[3] = hash[9];
        crc[4] = hash[4];
        crc[5] = hash[5];
        crc[6] = hash[11];
        crc[7] = hash[12];
    } else if (encrypt_type == 3) {
        unsigned char hash[32] = {0};
        SHA1(seed, 4, hash);
        crc[0] = hash[2];
        crc[1] = hash[3];
        crc[2] = hash[9];
        crc[3] = hash[10];
        crc[4] = hash[5];
        crc[5] = hash[6];
        crc[6] = hash[15];
        crc[7] = hash[16];
    }
}

void keepalive_2_packetbuilder(unsigned char keepalive_2_packet[], int keepalive_counter, int filepacket, int type, int encrypt_type) {
    keepalive_2_packet[0] = 0x07;
    keepalive_2_packet[1] = keepalive_counter;
    keepalive_2_packet[2] = 0x28;
    keepalive_2_packet[4] = 0x0b;
    keepalive_2_packet[5] = type;
    if (filepacket) {
        keepalive_2_packet[6] = 0x0f;
        keepalive_2_packet[7] = 0x27;
    } else {
        memcpy(keepalive_2_packet + 6, drcom_config.KEEP_ALIVE_VERSION, 2);
    }
    keepalive_2_packet[8] = 0x2f;
    keepalive_2_packet[9] = 0x12;
    if (type == 3) {
        unsigned char host_ip[4] = {0};
        if (strcmp(mode, "dhcp") == 0) {
            sscanf(drcom_config.host_ip, "%hhd.%hhd.%hhd.%hhd",
                   &host_ip[0],
                   &host_ip[1],
                   &host_ip[2],
                   &host_ip[3]);
            memcpy(keepalive_2_packet + 28, host_ip, 4);
        } else if (strcmp(mode, "pppoe") == 0) {
            unsigned char crc[8] = {0};
            gen_crc(keepalive_2_packet, encrypt_type, crc);
            memcpy(keepalive_2_packet + 32, crc, 8);
        }
    }
}

int keepalive_2(int sockfd, struct sockaddr_in addr, int *keepalive_counter, int *first, int *encrypt_type) {
    unsigned char keepalive_2_packet[40], recv_packet[1024], tail[4];
    socklen_t addrlen = sizeof(addr);

#ifdef TEST
    printf("[TEST MODE]IN TEST MODE, PASS\n");
#else
    if (*first) {
        // send the file packet
        memset(keepalive_2_packet, 0, 40);
        if (strcmp(mode, "pppoe") == 0) {
            keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, *encrypt_type);
        } else {
            keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, 0);
        }
        (*keepalive_counter)++;

        sendto(sockfd, keepalive_2_packet, 40, 0, (struct sockaddr *)&addr, sizeof(addr));

        if (verbose_flag) {
            print_packet("[Keepalive2_file sent] ", keepalive_2_packet, 40);
        }
        if (logging_flag) {
            logging("[Keepalive2_file sent] ", keepalive_2_packet, 40);
        }
        if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
            get_lasterror("Failed to recv data");
#else
            perror("Failed to recv data");
#endif
            return 1;
        }
        if (verbose_flag) {
            print_packet("[Keepalive2_file recv] ", recv_packet, 40);
        }
        if (logging_flag) {
            logging("[Keepalive2_file recv] ", recv_packet, 40);
        }

        if (recv_packet[0] == 0x07) {
            if (recv_packet[2] == 0x10) {
                if (verbose_flag) {
                    printf("Filepacket received.\n");
                }
            } else if (recv_packet[2] != 0x28) {
                if (verbose_flag) {
                    printf("Bad keepalive2 response received.\n");
                }
                return 1;
            }
        } else {
            printf("Bad keepalive2 response received.\n");
            return 1;
        }
    }
#endif

    // send the first packet
    *first = 0;
    memset(keepalive_2_packet, 0, 40);
    if (strcmp(mode, "pppoe") == 0) {
        keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, *encrypt_type);
    } else {
        keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 1, 0);
    }
    (*keepalive_counter)++;
    sendto(sockfd, keepalive_2_packet, 40, 0, (struct sockaddr *)&addr, sizeof(addr));

    if (verbose_flag) {
        print_packet("[Keepalive2_A sent] ", keepalive_2_packet, 40);
    }
    if (logging_flag) {
        logging("[Keepalive2_A sent] ", keepalive_2_packet, 40);
    }

#ifdef TEST
    unsigned char test[4] = {0x13, 0x38, 0xe2, 0x11};
    memcpy(tail, test, 4);
    print_packet("[TEST MODE]<PREP TAIL> ", tail, 4);
#else
    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
        get_lasterror("Failed to recv data");
#else
        perror("Failed to recv data");
#endif
        return 1;
    }
    if (verbose_flag) {
        print_packet("[Keepalive2_B recv] ", recv_packet, 40);
    }
    if (logging_flag) {
        logging("[Keepalive2_B recv] ", recv_packet, 40);
    }

    if (recv_packet[0] == 0x07) {
        if (recv_packet[2] != 0x28) {
            printf("Bad keepalive2 response received.\n");
            return 1;
        }
    } else {
        printf("Bad keepalive2 response received.\n");
        return 1;
    }
    memcpy(tail, &recv_packet[16], 4);
#endif

#ifdef DEBUG
    print_packet("<GET TAIL> ", tail, 4);
#endif

    // send the third packet
    memset(keepalive_2_packet, 0, 40);
    if (strcmp(mode, "pppoe") == 0) {
        keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 3, *encrypt_type);
    } else {
        keepalive_2_packetbuilder(keepalive_2_packet, *keepalive_counter % 0xFF, *first, 3, 0);
    }
    memcpy(keepalive_2_packet + 16, tail, 4);
    (*keepalive_counter)++;
    sendto(sockfd, keepalive_2_packet, 40, 0, (struct sockaddr *)&addr, sizeof(addr));

    if (verbose_flag) {
        print_packet("[Keepalive2_C sent] ", keepalive_2_packet, 40);
    }
    if (logging_flag) {
        logging("[Keepalive2_C sent] ", keepalive_2_packet, 40);
    }

#ifdef TEST
    printf("[TEST MODE]IN TEST MODE, PASS\n");
    exit(0);
#endif

    if (recvfrom(sockfd, recv_packet, 1024, 0, (struct sockaddr *)&addr, &addrlen) < 0) {
#ifdef WIN32
        get_lasterror("Failed to recv data");
#else
        perror("Failed to recv data");
#endif
        return 1;
    }
    if (verbose_flag) {
        print_packet("[Keepalive2_D recv] ", recv_packet, 40);
    }
    if (logging_flag) {
        logging("[Keepalive2_D recv] ", recv_packet, 40);
    }

    if (recv_packet[0] == 0x07) {
        if (recv_packet[2] != 0x28) {
            printf("Bad keepalive2 response received.\n");
            return 1;
        }
    } else {
        printf("Bad keepalive2 response received.\n");
        return 1;
    }

    return 0;
}

================================================
FILE: keepalive.h
================================================
#ifndef KEEPALIVE_H_
#define KEEPALIVE_H_

int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], unsigned char auth_information[]);
int keepalive_2(int sockfd, struct sockaddr_in addr, int *keepalive_counter, int *first, int *encrypt_type);
void gen_crc(unsigned char seed[], int encrypt_type, unsigned char crc[]);
void keepalive_2_packetbuilder(unsigned char keepalive_2_packet[], int keepalive_counter, int filepacket, int type, int encrypt_type);

#endif  // KEEPALIVE_H_

================================================
FILE: libs/common.c
================================================
#ifdef linux

/*
 * 一些通用的代码
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include "common.h"

// #ifdef LINUX
#include <unistd.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <sys/select.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#define PATH_SEP   '/'
// #elif WIN32
// # include <windows.h>
// # include <pcap.h>
// # define PATH_SEP   '\\'
// #endif


extern int getexedir(char *exedir)
{
// #ifdef LINUX
    int cnt = readlink("/proc/self/exe", exedir, EXE_PATH_MAX);
// #elif WIN32
//     int cnt = GetModuleFileName(NULL, exedir, EXE_PATH_MAX);
// #endif
    if (cnt < 0 || cnt >= EXE_PATH_MAX)
        return -1;
    _D("exedir: %s\n", exedir);
    char *end = strrchr(exedir, PATH_SEP);
    if (!end) return -1;
    *(end+1) = '\0';
    _D("exedir: %s\n", exedir);
    return 0;
}

extern int mac_equal(uchar const *mac1, uchar const *mac2)
{
	int i;
	for (i = 0; i < ETH_ALEN; ++i) {
		if (mac1[i] != mac2[i])
			return 0;
	}

	return 1;
}
extern int ip_equal(int type, void const *ip1, void const *ip2)
{
	uchar const *p1 = (uchar const*)ip1;
	uchar const *p2 = (uchar const*)ip2;
	int len = 4;
	if (AF_INET6 == type) {
		len = 16;
	}
	int i;
	for (i = 0; i < len; ++i) {
		if (p1[i] != p2[i])
			return 0;
	}
	return 1;
}

static int is_filter(char const *ifname)
{
	/* 过滤掉无线,虚拟机接口等 */
	char const *filter[] = {
		/* windows */
		"Wireless", "Microsoft",
		"Virtual",
		/* linux */
		"lo", "wlan", "vboxnet",
		"ifb", "gre", "teql",
		"br", "imq", "ra",
		"wds", "sit", "apcli",
	};
	unsigned int i;
	for (i = 0; i < ARRAY_SIZE(filter); ++i) {
		if (strstr(ifname, filter[i]))
			return 1;
	}
	return 0;
}
// #ifdef LINUX
static char *get_ifname_from_buff(char *buff)
{
	char *s;
	while (isspace(*buff))
		++buff;
	s = buff;
	while (':' != *buff && '\0' != *buff)
		++buff;
	*buff = '\0';
	return s;
}
// #endif
/*
 * 获取所有网络接口
 * ifnames 实际获取的接口
 * cnt     两个作用,1:传入表示ifnames最多可以存储的接口个数
 *                   2:返回表示实际获取了的接口个数
 * 返回接口个数在cnt里
 * @return: >=0  成功,实际获取的接口个数
 *          -1 获取失败
 *          -2 cnt过小
 */
extern int getall_ifs(iflist_t *ifs, int *cnt)
{
	int i = 0;
	if (!ifs || *cnt <= 0) return -2;

// #ifdef LINUX    /* linux (unix osx?) */
#define _PATH_PROCNET_DEV "/proc/net/dev"
#define BUFF_LINE_MAX	(1024)
	char buff[BUFF_LINE_MAX];
	FILE *fd = fopen(_PATH_PROCNET_DEV, "r");
	char *name;
	if (NULL == fd) {
		perror("fopen");
		return -1;
	}
	/* _PATH_PROCNET_DEV文件格式如下,...表示后面我们不关心
	 * Inter-|   Receive ...
	 * face |bytes    packets ...
	 * eth0: 147125283  119599 ...
	 * wlan0:  229230    2635   ...
	 * lo: 10285509   38254  ...
	 */
	/* 略过开始两行 */
	fgets(buff, BUFF_LINE_MAX, fd);
	fgets(buff, BUFF_LINE_MAX, fd);
	while (NULL != fgets(buff, BUFF_LINE_MAX, fd)) {
		name = get_ifname_from_buff(buff);
		_D("%s\n", name);
		/* 过滤无关网络接口 */
		if (is_filter(name)) {
			_D("filtered %s.\n", name);
			continue;
		}
		strncpy(ifs[i].name, name, IFNAMSIZ);
		_D("ifs[%d].name: %s\n", i, ifs[i].name);
		++i;
		if (i >= *cnt) {
			fclose(fd);
			return -2;
		}
	}
	fclose(fd);

// #elif WIN32
// 	pcap_if_t *alldevs;
// 	char errbuf[PCAP_ERRBUF_SIZE];
// 	if (-1 == pcap_findalldevs(&alldevs, errbuf)) {
// 		_M("Get interfaces handler error: %s\n", errbuf);
// 		return -1;
// 	}
// 	for (pcap_if_t *d = alldevs; d; d = d->next) {
// 		if (is_filter(d->description)) {
// 			_D("filtered %s.\n", d->description);
// 			continue;
// 		}
// 		if (i >= *cnt) return -2;
// 		strncpy(ifs[i].name, d->name, IFNAMSIZ);
// 		strncpy(ifs[i].desc, d->description, IFDESCSIZ);
// 		++i;
// 	}
// 	pcap_freealldevs(alldevs);
// #endif

	*cnt = i;
	return i;
}

extern char const *format_time(void)
{
	static char buff[FORMAT_TIME_MAX];
	time_t rawtime;
	struct tm *timeinfo;

	time(&rawtime);
	timeinfo = localtime(&rawtime);
	if (NULL == timeinfo) return NULL;
	strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", timeinfo);

	return buff;
}
extern int copy(char const *f1, char const *f2)
{
	if (NULL == f1 || NULL == f2) return -1;
	FILE *src, *dst;
	src = fopen(f1, "r");
	dst = fopen(f2, "w");
	if (NULL == src || NULL == dst) return -1;
	char buff[1024];
	int n;
	while (0 < (n = fread(buff, 1, 1024, src)))
		fwrite(buff, 1, n, dst);

	fclose(src);
	fclose(dst);

	return 0;
}
/*
 * 本地是否是小端序
 * @return: !0: 是
 *           0: 不是(大端序)
 */
static int islsb()
{
	static uint16 a = 0x0001;
	return (int)(*(uchar*)&a);
}
static uint16 exorders(uint16 n)
{
	return ((n>>8)|(n<<8));
}
static uint32 exorderl(uint32 n)
{
	return (n>>24)|((n&0x00ff0000)>>8)|((n&0x0000ff00)<<8)|(n<<24);
}
extern uint16 htols(uint16 n)
{
	return islsb()?n:exorders(n);
}
extern uint16 htoms(uint16 n)
{
	return islsb()?exorders(n):n;
}
extern uint16 ltohs(uint16 n)
{
	return islsb()?n:exorders(n);
}
extern uint16 mtohs(uint16 n)
{
	return islsb()?exorders(n):n;
}
extern uint32 htoll(uint32 n)
{
	return islsb()?n:exorderl(n);
}
extern uint32 htoml(uint32 n)
{
	return islsb()?exorderl(n):n;
}
extern uint32 ltohl(uint32 n)
{
	return islsb()?n:exorderl(n);
}
extern uint32 mtohl(uint32 n)
{
	return islsb()?exorderl(n):n;
}
extern uchar const *format_mac(uchar const *macarr)
{
	static uchar formatmac[] =
		"xx:xx:xx:xx:xx:xx";
	if (NULL == macarr)
		return NULL;
	sprintf((char*)formatmac, "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",
			macarr[0], macarr[1], macarr[2],
			macarr[3], macarr[4], macarr[5]);
	return formatmac;
}
/*
 * 以16进制打印数据
 */
extern void format_data(uchar const *d, size_t len)
{
	int i;
	for (i = 0; i < (long)len; ++i) {
		if (i != 0 && i%16 == 0)
			_M("\n");
		_M("%02x ", d[i]);
	}
	_M("\n");
}

#ifdef LINUX
/*
 * 返回t1-t0的时间差
 * 由于这里精度没必要达到ns,故返回相差微秒ms
 * @return: 时间差,单位微秒(1s == 1000ms)
 */
extern long difftimespec(struct timespec t1, struct timespec t0)
{
	long d = t1.tv_sec-t0.tv_sec;
	d *= 1000;
	d += (t1.tv_nsec-t0.tv_nsec)/(long)(1e6);
	return d;
}

/*
 * 判断网络是否连通
 * 最长延时3s,也就是说如果3s内没有检测到数据回应,那么认为网络不通
 * TODO 使用icmp协议判断
 * @return: !0: 连通
 *           0: 没有连通
 */
extern int isnetok(char const *ifname)
{
	static char baidu[] = "baidu.com";
	sleep(100);
	return 1;
}

/*
 * 休眠ms微秒
 */
extern void msleep(long ms)
{
	struct timeval tv;
	tv.tv_sec = ms/1000;
	tv.tv_usec = ms%1000*1000;
	select(0, 0, 0, 0, &tv);
}
#endif /* LINUX */

#endif

================================================
FILE: libs/common.h
================================================
#ifndef COMMON_H__
#define COMMON_H__
/*
 * 通用的代码和定义
 */
typedef unsigned char uchar;	/* 一个字节 */
typedef unsigned short uint16;	/* 两个字节 */
typedef unsigned int uint32;	/* 四个字节 */

/* 用户名和密码长度 */
#define UNAME_LEN	(32)
#define PWD_LEN		(32)

#define FORMAT_TIME_MAX	(64)

// #ifdef LINUX
#include <linux/limits.h>
#include <netinet/if_ether.h>
#include <arpa/inet.h>
#include <net/if.h>
#define EXE_PATH_MAX   (PATH_MAX+1)
// #elif WIN32
// # include <windows.h>
// # define ETH_ALEN	    (6)
// # define IF_NAMSIZE	    (64)
// # define MTU_MAX	    (65536)
// # define EXE_PATH_MAX   (MAX_PATH+1)
// # define IFDESCSIZ      (126)
// #endif

typedef struct {
    char name[IF_NAMESIZE]; /* linux下是eth0, windows采用的是注册表类似的(\Device\NPF_{xxxx-xxx-xx-xx-xxx}) */
// #ifdef WIN32
//     char desc[IFDESCSIZ]; /* windows下描述(AMD PCNET Family PCI Ethernet Adapter) */
// #endif
}iflist_t;


#undef ARRAY_SIZE
#define ARRAY_SIZE(arr)	(sizeof(arr)/sizeof(arr[0]))

#define MAX(x, y)	((x)>(y)?(x):(y))
#define MIN(x, y)	((x)>(y)?(y):(x))

#undef PRINT
#ifdef GUI
# include <glib.h>
# define PRINT(...) g_print(__VA_ARGS__)
#else
# include <stdio.h>
# define PRINT(...) fprintf(stderr, __VA_ARGS__)
#endif

#ifdef DEBUG
# define _D(...) \
    do { \
        PRINT("%s:%s:%d:", format_time(), __FILE__, __LINE__); \
        PRINT(__VA_ARGS__); \
    } while(0)
#else
# define _D(...)    ((void)0)
#endif

#define _M(...)    PRINT(__VA_ARGS__);

/*
 * 获取程序所在的实际绝对路径的目录
 * exedir: 返回目录,加上\0一起长度是EXE_PATH_MAX,
 *         如果本上长度达到了EXE_PATH_MAX(不包括\0),那么也会返回失败
 * @return: 0: 成功
 *         !0: 失败
 */
extern int getexedir(char *exedir);
/*
 * 比较两个mac是否相同
 * @return: 0: 不同
 *         !0: 相同
 */
extern int mac_equal(uchar const *mac1, uchar const *mac2);

/*
 * 判断两个ip是否相等
 * type: AF_INET or AF_INET6, 分别对应ipv4,ipv6
 * ip1, ip2: 比较的两个ip,同为struct in_addr或struct in6_addr的指针
 * @return: 0: 不同
 *         !0: 相同
 */
extern int ip_equal(int type, void const *ip1, void const *ip2);

/*
 * 获取所有网络接口
 * ifnames 实际获取的接口
 * cnt     两个作用,1:传入表示ifnames最多可以存储的接口个数
 *                   2:返回表示实际获取了的接口个数
 * 返回接口个数在cnt里
 * @return: >=0  成功,实际获取的接口个数
 *          -1 获取失败
 *          -2 cnt过小
 */
extern int getall_ifs(iflist_t *ifs, int *cnt);
/*
 * 获取当前时间按照
 * yyyy-MM-dd HH:mm:ss
 * 格式返回
 * NOTE 不要去修改返回结果,并且不是线程安全的
 * @return: NULL: 失败
 *         !NULL: 存储的结果
 */
extern char const *format_time(void);
/*
 * 简单的复制文件,暂时不进行细致错误检查
 * NOTE 是绝对路径
 * scr: 源文件
 * dst: 目标文件
 * @return: 0: 成功
 *         -1: 失败
 */
extern int copy(char const *src, char const *dst);

/*
 * 字节序转换相关函数
 * host to lsb/msb short/long (host->l/m)
 * lsb/msb to host short/long (l/m->host)
 */
extern uint16 htols(uint16 n);
extern uint16 htoms(uint16 n);
extern uint16 ltohs(uint16 n);
extern uint16 mtohs(uint16 n);

extern uint32 htoll(uint32 n);
extern uint32 htoml(uint32 n);
extern uint32 ltohl(uint32 n);
extern uint32 mtohl(uint32 n);

extern uchar const *format_mac(uchar const *mac);

/*
 * 判断网络是否连通
 * ifname: 接口名字
 * @return: !0: 连通
 *           0: 没有连通
 */
extern int isnetok(char const *ifname);
/*
 * 返回t1-t0的时间差
 * 由于这里精度没必要达到ns,故返回相差微秒ms
 * @return: 时间差,单位微秒(1s == 1000ms)
 */
extern long difftimespec(struct timespec t1, struct timespec t0);

/*
 * 休眠ms微秒
 */
extern void msleep(long ms);

/*
 * 以16进制打印数据
 */
extern void format_data(uchar const *d, size_t len);

#endif

================================================
FILE: libs/md4.c
================================================
/*
 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
 * MD4 Message-Digest Algorithm (RFC 1320).
 *
 * Homepage:
 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md4
 *
 * Author:
 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
 *
 * This software was written by Alexander Peslyak in 2001.  No copyright is
 * claimed, and the software is hereby placed in the public domain.
 * In case this attempt to disclaim copyright and place the software in the
 * public domain is deemed null and void, then the software is
 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
 * general public under the following terms:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 *
 * There's ABSOLUTELY NO WARRANTY, express or implied.
 *
 * (This is a heavily cut-down "BSD license".)
 *
 * This differs from Colin Plumb's older public domain implementation in that
 * no exactly 32-bit integer data type is required (any 32-bit or wider
 * unsigned integer data type will do), there's no compile-time endianness
 * configuration, and the function prototypes match OpenSSL's.  No code from
 * Colin Plumb's implementation has been reused; this comment merely compares
 * the properties of the two independent implementations.
 *
 * The primary goals of this implementation are portability and ease of use.
 * It is meant to be fast, but not as fast as possible.  Some known
 * optimizations are not included to reduce source code size and avoid
 * compile-time configuration.
 */

#ifndef HAVE_OPENSSL

#include <string.h>

#include "md4.h"

/*
 * The basic MD4 functions.
 *
 * F and G are optimized compared to their RFC 1320 definitions, with the
 * optimization for F borrowed from Colin Plumb's MD5 implementation.
 */
#define F(x, y, z)			((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z)			(((x) & ((y) | (z))) | ((y) & (z)))
#define H(x, y, z)			((x) ^ (y) ^ (z))

/*
 * The MD4 transformation for all three rounds.
 */
#define STEP(f, a, b, c, d, x, s) \
	(a) += f((b), (c), (d)) + (x); \
	(a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s))));

/*
 * SET reads 4 input bytes in little-endian byte order and stores them in a
 * properly aligned word in host byte order.
 *
 * The check for little-endian architectures that tolerate unaligned memory
 * accesses is just an optimization.  Nothing will break if it fails to detect
 * a suitable architecture.
 *
 * Unfortunately, this optimization may be a C strict aliasing rules violation
 * if the caller's data buffer has effective type that cannot be aliased by
 * MD4_u32plus.  In practice, this problem may occur if these MD4 routines are
 * inlined into a calling function, or with future and dangerously advanced
 * link-time optimizations.  For the time being, keeping these MD4 routines in
 * their own translation unit avoids the problem.
 */
#if defined(__i386__) || defined(__x86_64__) || defined(__vax__)
#define SET(n) \
	(*(MD4_u32plus *)&ptr[(n) * 4])
#define GET(n) \
	SET(n)
#else
#define SET(n) \
	(ctx->block[(n)] = \
	(MD4_u32plus)ptr[(n) * 4] | \
	((MD4_u32plus)ptr[(n) * 4 + 1] << 8) | \
	((MD4_u32plus)ptr[(n) * 4 + 2] << 16) | \
	((MD4_u32plus)ptr[(n) * 4 + 3] << 24))
#define GET(n) \
	(ctx->block[(n)])
#endif

/*
 * This processes one or more 64-byte data blocks, but does NOT update the bit
 * counters.  There are no alignment requirements.
 */
static const void *body(MD4_CTX *ctx, const void *data, unsigned long size)
{
	const unsigned char *ptr;
	MD4_u32plus a, b, c, d;
	MD4_u32plus saved_a, saved_b, saved_c, saved_d;
	const MD4_u32plus ac1 = 0x5a827999, ac2 = 0x6ed9eba1;

	ptr = (const unsigned char *)data;

	a = ctx->a;
	b = ctx->b;
	c = ctx->c;
	d = ctx->d;

	do {
		saved_a = a;
		saved_b = b;
		saved_c = c;
		saved_d = d;

/* Round 1 */
		STEP(F, a, b, c, d, SET(0), 3)
		STEP(F, d, a, b, c, SET(1), 7)
		STEP(F, c, d, a, b, SET(2), 11)
		STEP(F, b, c, d, a, SET(3), 19)
		STEP(F, a, b, c, d, SET(4), 3)
		STEP(F, d, a, b, c, SET(5), 7)
		STEP(F, c, d, a, b, SET(6), 11)
		STEP(F, b, c, d, a, SET(7), 19)
		STEP(F, a, b, c, d, SET(8), 3)
		STEP(F, d, a, b, c, SET(9), 7)
		STEP(F, c, d, a, b, SET(10), 11)
		STEP(F, b, c, d, a, SET(11), 19)
		STEP(F, a, b, c, d, SET(12), 3)
		STEP(F, d, a, b, c, SET(13), 7)
		STEP(F, c, d, a, b, SET(14), 11)
		STEP(F, b, c, d, a, SET(15), 19)

/* Round 2 */
		STEP(G, a, b, c, d, GET(0) + ac1, 3)
		STEP(G, d, a, b, c, GET(4) + ac1, 5)
		STEP(G, c, d, a, b, GET(8) + ac1, 9)
		STEP(G, b, c, d, a, GET(12) + ac1, 13)
		STEP(G, a, b, c, d, GET(1) + ac1, 3)
		STEP(G, d, a, b, c, GET(5) + ac1, 5)
		STEP(G, c, d, a, b, GET(9) + ac1, 9)
		STEP(G, b, c, d, a, GET(13) + ac1, 13)
		STEP(G, a, b, c, d, GET(2) + ac1, 3)
		STEP(G, d, a, b, c, GET(6) + ac1, 5)
		STEP(G, c, d, a, b, GET(10) + ac1, 9)
		STEP(G, b, c, d, a, GET(14) + ac1, 13)
		STEP(G, a, b, c, d, GET(3) + ac1, 3)
		STEP(G, d, a, b, c, GET(7) + ac1, 5)
		STEP(G, c, d, a, b, GET(11) + ac1, 9)
		STEP(G, b, c, d, a, GET(15) + ac1, 13)

/* Round 3 */
		STEP(H, a, b, c, d, GET(0) + ac2, 3)
		STEP(H, d, a, b, c, GET(8) + ac2, 9)
		STEP(H, c, d, a, b, GET(4) + ac2, 11)
		STEP(H, b, c, d, a, GET(12) + ac2, 15)
		STEP(H, a, b, c, d, GET(2) + ac2, 3)
		STEP(H, d, a, b, c, GET(10) + ac2, 9)
		STEP(H, c, d, a, b, GET(6) + ac2, 11)
		STEP(H, b, c, d, a, GET(14) + ac2, 15)
		STEP(H, a, b, c, d, GET(1) + ac2, 3)
		STEP(H, d, a, b, c, GET(9) + ac2, 9)
		STEP(H, c, d, a, b, GET(5) + ac2, 11)
		STEP(H, b, c, d, a, GET(13) + ac2, 15)
		STEP(H, a, b, c, d, GET(3) + ac2, 3)
		STEP(H, d, a, b, c, GET(11) + ac2, 9)
		STEP(H, c, d, a, b, GET(7) + ac2, 11)
		STEP(H, b, c, d, a, GET(15) + ac2, 15)

		a += saved_a;
		b += saved_b;
		c += saved_c;
		d += saved_d;

		ptr += 64;
	} while (size -= 64);

	ctx->a = a;
	ctx->b = b;
	ctx->c = c;
	ctx->d = d;

	return ptr;
}

void MD4_Init(MD4_CTX *ctx)
{
	ctx->a = 0x67452301;
	ctx->b = 0xefcdab89;
	ctx->c = 0x98badcfe;
	ctx->d = 0x10325476;

	ctx->lo = 0;
	ctx->hi = 0;
}

void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size)
{
	MD4_u32plus saved_lo;
	unsigned long used, available;

	saved_lo = ctx->lo;
	if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo)
		ctx->hi++;
	ctx->hi += size >> 29;

	used = saved_lo & 0x3f;

	if (used) {
		available = 64 - used;

		if (size < available) {
			memcpy(&ctx->buffer[used], data, size);
			return;
		}

		memcpy(&ctx->buffer[used], data, available);
		data = (const unsigned char *)data + available;
		size -= available;
		body(ctx, ctx->buffer, 64);
	}

	if (size >= 64) {
		data = body(ctx, data, size & ~(unsigned long)0x3f);
		size &= 0x3f;
	}

	memcpy(ctx->buffer, data, size);
}

#define OUT(dst, src) \
	(dst)[0] = (unsigned char)(src); \
	(dst)[1] = (unsigned char)((src) >> 8); \
	(dst)[2] = (unsigned char)((src) >> 16); \
	(dst)[3] = (unsigned char)((src) >> 24);

void MD4_Final(unsigned char *result, MD4_CTX *ctx)
{
	unsigned long used, available;

	used = ctx->lo & 0x3f;

	ctx->buffer[used++] = 0x80;

	available = 64 - used;

	if (available < 8) {
		memset(&ctx->buffer[used], 0, available);
		body(ctx, ctx->buffer, 64);
		used = 0;
		available = 64;
	}

	memset(&ctx->buffer[used], 0, available - 8);

	ctx->lo <<= 3;
	OUT(&ctx->buffer[56], ctx->lo)
	OUT(&ctx->buffer[60], ctx->hi)

	body(ctx, ctx->buffer, 64);

	OUT(&result[0], ctx->a)
	OUT(&result[4], ctx->b)
	OUT(&result[8], ctx->c)
	OUT(&result[12], ctx->d)

	memset(ctx, 0, sizeof(*ctx));
}

void MD4(const void *data, unsigned long size, unsigned char *result) {
	MD4_CTX ctx;
	MD4_Init(&ctx);
	MD4_Update(&ctx, data, size);
	MD4_Final(result, &ctx);
}

#endif


================================================
FILE: libs/md4.h
================================================
/*
 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
 * MD4 Message-Digest Algorithm (RFC 1320).
 *
 * Homepage:
 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md4
 *
 * Author:
 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
 *
 * This software was written by Alexander Peslyak in 2001.  No copyright is
 * claimed, and the software is hereby placed in the public domain.
 * In case this attempt to disclaim copyright and place the software in the
 * public domain is deemed null and void, then the software is
 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
 * general public under the following terms:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 *
 * There's ABSOLUTELY NO WARRANTY, express or implied.
 *
 * See md4.c for more information.
 */

#ifdef HAVE_OPENSSL
#include <openssl/md4.h>
#elif !defined(_MD4_H)
#define _MD4_H

/* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned int MD4_u32plus;

typedef struct {
	MD4_u32plus lo, hi;
	MD4_u32plus a, b, c, d;
	unsigned char buffer[64];
	MD4_u32plus block[16];
} MD4_CTX;

extern void MD4_Init(MD4_CTX *ctx);
extern void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size);
extern void MD4_Final(unsigned char *result, MD4_CTX *ctx);

void MD4(const void *data, unsigned long size, unsigned char *result);

#endif


================================================
FILE: libs/md5.c
================================================
/*
 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
 * MD5 Message-Digest Algorithm (RFC 1321).
 *
 * Homepage:
 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
 *
 * Author:
 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
 *
 * This software was written by Alexander Peslyak in 2001.  No copyright is
 * claimed, and the software is hereby placed in the public domain.
 * In case this attempt to disclaim copyright and place the software in the
 * public domain is deemed null and void, then the software is
 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
 * general public under the following terms:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 *
 * There's ABSOLUTELY NO WARRANTY, express or implied.
 *
 * (This is a heavily cut-down "BSD license".)
 *
 * This differs from Colin Plumb's older public domain implementation in that
 * no exactly 32-bit integer data type is required (any 32-bit or wider
 * unsigned integer data type will do), there's no compile-time endianness
 * configuration, and the function prototypes match OpenSSL's.  No code from
 * Colin Plumb's implementation has been reused; this comment merely compares
 * the properties of the two independent implementations.
 *
 * The primary goals of this implementation are portability and ease of use.
 * It is meant to be fast, but not as fast as possible.  Some known
 * optimizations are not included to reduce source code size and avoid
 * compile-time configuration.
 */

#ifndef HAVE_OPENSSL

#include <string.h>

#include "md5.h"

/*
 * The basic MD5 functions.
 *
 * F and G are optimized compared to their RFC 1321 definitions for
 * architectures that lack an AND-NOT instruction, just like in Colin Plumb's
 * implementation.
 */
#define F(x, y, z)			((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z)			((y) ^ ((z) & ((x) ^ (y))))
#define H(x, y, z)			(((x) ^ (y)) ^ (z))
#define H2(x, y, z)			((x) ^ ((y) ^ (z)))
#define I(x, y, z)			((y) ^ ((x) | ~(z)))

/*
 * The MD5 transformation for all four rounds.
 */
#define STEP(f, a, b, c, d, x, t, s) \
	(a) += f((b), (c), (d)) + (x) + (t); \
	(a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \
	(a) += (b);

/*
 * SET reads 4 input bytes in little-endian byte order and stores them in a
 * properly aligned word in host byte order.
 *
 * The check for little-endian architectures that tolerate unaligned memory
 * accesses is just an optimization.  Nothing will break if it fails to detect
 * a suitable architecture.
 *
 * Unfortunately, this optimization may be a C strict aliasing rules violation
 * if the caller's data buffer has effective type that cannot be aliased by
 * MD5_u32plus.  In practice, this problem may occur if these MD5 routines are
 * inlined into a calling function, or with future and dangerously advanced
 * link-time optimizations.  For the time being, keeping these MD5 routines in
 * their own translation unit avoids the problem.
 */
#if defined(__i386__) || defined(__x86_64__) || defined(__vax__)
#define SET(n) \
	(*(MD5_u32plus *)&ptr[(n) * 4])
#define GET(n) \
	SET(n)
#else
#define SET(n) \
	(ctx->block[(n)] = \
	(MD5_u32plus)ptr[(n) * 4] | \
	((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \
	((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \
	((MD5_u32plus)ptr[(n) * 4 + 3] << 24))
#define GET(n) \
	(ctx->block[(n)])
#endif

/*
 * This processes one or more 64-byte data blocks, but does NOT update the bit
 * counters.  There are no alignment requirements.
 */
static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
{
	const unsigned char *ptr;
	MD5_u32plus a, b, c, d;
	MD5_u32plus saved_a, saved_b, saved_c, saved_d;

	ptr = (const unsigned char *)data;

	a = ctx->a;
	b = ctx->b;
	c = ctx->c;
	d = ctx->d;

	do {
		saved_a = a;
		saved_b = b;
		saved_c = c;
		saved_d = d;

/* Round 1 */
		STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7)
		STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12)
		STEP(F, c, d, a, b, SET(2), 0x242070db, 17)
		STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22)
		STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7)
		STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12)
		STEP(F, c, d, a, b, SET(6), 0xa8304613, 17)
		STEP(F, b, c, d, a, SET(7), 0xfd469501, 22)
		STEP(F, a, b, c, d, SET(8), 0x698098d8, 7)
		STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12)
		STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17)
		STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22)
		STEP(F, a, b, c, d, SET(12), 0x6b901122, 7)
		STEP(F, d, a, b, c, SET(13), 0xfd987193, 12)
		STEP(F, c, d, a, b, SET(14), 0xa679438e, 17)
		STEP(F, b, c, d, a, SET(15), 0x49b40821, 22)

/* Round 2 */
		STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5)
		STEP(G, d, a, b, c, GET(6), 0xc040b340, 9)
		STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14)
		STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20)
		STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5)
		STEP(G, d, a, b, c, GET(10), 0x02441453, 9)
		STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14)
		STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20)
		STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5)
		STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9)
		STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14)
		STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20)
		STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5)
		STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9)
		STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14)
		STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20)

/* Round 3 */
		STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4)
		STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11)
		STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16)
		STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23)
		STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4)
		STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11)
		STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16)
		STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23)
		STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4)
		STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11)
		STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16)
		STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23)
		STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4)
		STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11)
		STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16)
		STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23)

/* Round 4 */
		STEP(I, a, b, c, d, GET(0), 0xf4292244, 6)
		STEP(I, d, a, b, c, GET(7), 0x432aff97, 10)
		STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15)
		STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21)
		STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6)
		STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10)
		STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15)
		STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21)
		STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6)
		STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10)
		STEP(I, c, d, a, b, GET(6), 0xa3014314, 15)
		STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21)
		STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6)
		STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10)
		STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15)
		STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21)

		a += saved_a;
		b += saved_b;
		c += saved_c;
		d += saved_d;

		ptr += 64;
	} while (size -= 64);

	ctx->a = a;
	ctx->b = b;
	ctx->c = c;
	ctx->d = d;

	return ptr;
}

void MD5_Init(MD5_CTX *ctx)
{
	ctx->a = 0x67452301;
	ctx->b = 0xefcdab89;
	ctx->c = 0x98badcfe;
	ctx->d = 0x10325476;

	ctx->lo = 0;
	ctx->hi = 0;
}

void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size)
{
	MD5_u32plus saved_lo;
	unsigned long used, available;

	saved_lo = ctx->lo;
	if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo)
		ctx->hi++;
	ctx->hi += size >> 29;

	used = saved_lo & 0x3f;

	if (used) {
		available = 64 - used;

		if (size < available) {
			memcpy(&ctx->buffer[used], data, size);
			return;
		}

		memcpy(&ctx->buffer[used], data, available);
		data = (const unsigned char *)data + available;
		size -= available;
		body(ctx, ctx->buffer, 64);
	}

	if (size >= 64) {
		data = body(ctx, data, size & ~(unsigned long)0x3f);
		size &= 0x3f;
	}

	memcpy(ctx->buffer, data, size);
}

#define OUT(dst, src) \
	(dst)[0] = (unsigned char)(src); \
	(dst)[1] = (unsigned char)((src) >> 8); \
	(dst)[2] = (unsigned char)((src) >> 16); \
	(dst)[3] = (unsigned char)((src) >> 24);

void MD5_Final(unsigned char *result, MD5_CTX *ctx)
{
	unsigned long used, available;

	used = ctx->lo & 0x3f;

	ctx->buffer[used++] = 0x80;

	available = 64 - used;

	if (available < 8) {
		memset(&ctx->buffer[used], 0, available);
		body(ctx, ctx->buffer, 64);
		used = 0;
		available = 64;
	}

	memset(&ctx->buffer[used], 0, available - 8);

	ctx->lo <<= 3;
	OUT(&ctx->buffer[56], ctx->lo)
	OUT(&ctx->buffer[60], ctx->hi)

	body(ctx, ctx->buffer, 64);

	OUT(&result[0], ctx->a)
	OUT(&result[4], ctx->b)
	OUT(&result[8], ctx->c)
	OUT(&result[12], ctx->d)

	memset(ctx, 0, sizeof(*ctx));
}

void MD5(const void *data, unsigned long size, unsigned char *result) {
	MD5_CTX ctx;
	MD5_Init(&ctx);
	MD5_Update(&ctx, data, size);
	MD5_Final(result, &ctx);
}

#endif


================================================
FILE: libs/md5.h
================================================
/*
 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
 * MD5 Message-Digest Algorithm (RFC 1321).
 *
 * Homepage:
 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
 *
 * Author:
 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
 *
 * This software was written by Alexander Peslyak in 2001.  No copyright is
 * claimed, and the software is hereby placed in the public domain.
 * In case this attempt to disclaim copyright and place the software in the
 * public domain is deemed null and void, then the software is
 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
 * general public under the following terms:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 *
 * There's ABSOLUTELY NO WARRANTY, express or implied.
 *
 * See md5.c for more information.
 */

#ifdef HAVE_OPENSSL
#include <openssl/md5.h>
#elif !defined(_MD5_H)
#define _MD5_H

/* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned int MD5_u32plus;

typedef struct {
	MD5_u32plus lo, hi;
	MD5_u32plus a, b, c, d;
	unsigned char buffer[64];
	MD5_u32plus block[16];
} MD5_CTX;

extern void MD5_Init(MD5_CTX *ctx);
extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size);
extern void MD5_Final(unsigned char *result, MD5_CTX *ctx);

void MD5(const void *data, unsigned long size, unsigned char *result);

#endif


================================================
FILE: libs/sha1.c
================================================

/* from valgrind tests */

/* ================ sha1.c ================ */
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain

Test Vectors (from FIPS PUB 180-1)
"abc"
  A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
  84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
A million repetitions of "a"
  34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/

/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */
/* #define SHA1HANDSOFF * Copies data before messing with it. */

#define SHA1HANDSOFF

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "sha1.h"

#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))

/* blk0() and blk() perform the initial expand. */
/* I got the idea of expanding during the round function from SSLeay */
#if BYTE_ORDER == LITTLE_ENDIAN
#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
    |(rol(block->l[i],8)&0x00FF00FF))
#elif BYTE_ORDER == BIG_ENDIAN
#define blk0(i) block->l[i]
#else
#error "Endianness not defined!"
#endif
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
    ^block->l[(i+2)&15]^block->l[i&15],1))

/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);


/* Hash a single 512-bit block. This is the core of the algorithm. */

void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
{
    uint32_t a, b, c, d, e;
    typedef union {
        unsigned char c[64];
        uint32_t l[16];
    } CHAR64LONG16;
#ifdef SHA1HANDSOFF
    CHAR64LONG16 block[1];  /* use array to appear as a pointer */
    memcpy(block, buffer, 64);
#else
    /* The following had better never be used because it causes the
     * pointer-to-const buffer to be cast into a pointer to non-const.
     * And the result is written through.  I threw a "const" in, hoping
     * this will cause a diagnostic.
     */
    CHAR64LONG16* block = (const CHAR64LONG16*)buffer;
#endif
    /* Copy context->state[] to working vars */
    a = state[0];
    b = state[1];
    c = state[2];
    d = state[3];
    e = state[4];
    /* 4 rounds of 20 operations each. Loop unrolled. */
    R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
    R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
    R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
    R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
    R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
    R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
    R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
    R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
    R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
    R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
    R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
    R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
    R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
    R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
    R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
    R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
    R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
    R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
    R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
    R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
    /* Add the working vars back into context.state[] */
    state[0] += a;
    state[1] += b;
    state[2] += c;
    state[3] += d;
    state[4] += e;
    /* Wipe variables */
    a = b = c = d = e = 0;
#ifdef SHA1HANDSOFF
    memset(block, '\0', sizeof(block));
#endif
}


/* SHA1Init - Initialize new context */

void SHA1Init(SHA1_CTX* context)
{
    /* SHA1 initialization constants */
    context->state[0] = 0x67452301;
    context->state[1] = 0xEFCDAB89;
    context->state[2] = 0x98BADCFE;
    context->state[3] = 0x10325476;
    context->state[4] = 0xC3D2E1F0;
    context->count[0] = context->count[1] = 0;
}


/* Run your data through this. */

void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len)
{
    uint32_t i, j;

    j = context->count[0];
    if ((context->count[0] += len << 3) < j)
        context->count[1]++;
    context->count[1] += (len>>29);
    j = (j >> 3) & 63;
    if ((j + len) > 63) {
        memcpy(&context->buffer[j], data, (i = 64-j));
        SHA1Transform(context->state, context->buffer);
        for ( ; i + 63 < len; i += 64) {
            SHA1Transform(context->state, &data[i]);
        }
        j = 0;
    }
    else i = 0;
    memcpy(&context->buffer[j], &data[i], len - i);
}


/* Add padding and return the message digest. */

void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
{
    unsigned i;
    unsigned char finalcount[8];
    unsigned char c;

#if 0	/* untested "improvement" by DHR */
    /* Convert context->count to a sequence of bytes
     * in finalcount.  Second element first, but
     * big-endian order within element.
     * But we do it all backwards.
     */
    unsigned char *fcp = &finalcount[8];

    for (i = 0; i < 2; i++)
       {
        uint32_t t = context->count[i];
        int j;

        for (j = 0; j < 4; t >>= 8, j++)
	          *--fcp = (unsigned char) t;
    }
#else
    for (i = 0; i < 8; i++) {
        finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
         >> ((3-(i & 3)) * 8) ) & 255);  /* Endian independent */
    }
#endif
    c = 0200;
    SHA1Update(context, &c, 1);
    while ((context->count[0] & 504) != 448) {
	c = 0000;
        SHA1Update(context, &c, 1);
    }
    SHA1Update(context, finalcount, 8);  /* Should cause a SHA1Transform() */
    for (i = 0; i < 20; i++) {
        digest[i] = (unsigned char)
         ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
    }
    /* Wipe variables */
    memset(context, '\0', sizeof(*context));
    memset(&finalcount, '\0', sizeof(finalcount));
}
/* ================ end of sha1.c ================ */

void SHA1(const unsigned char* data, uint32_t len, unsigned char digest[20]) {
    SHA1_CTX ctx;
    SHA1Init(&ctx);
    SHA1Update(&ctx, data, len);
    SHA1Final(digest, &ctx);
}

================================================
FILE: libs/sha1.h
================================================
#ifndef SHA1_H
#define SHA1_H
/* ================ sha1.h ================ */
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain
*/
#include <stdint.h>

typedef struct {
    uint32_t state[5];
    uint32_t count[2];
    unsigned char buffer[64];
} SHA1_CTX;

void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]);
void SHA1Init(SHA1_CTX* context);
void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len);
void SHA1Final(unsigned char digest[20], SHA1_CTX* context);

void SHA1(const unsigned char* data, uint32_t len, unsigned char digest[20]);

#endif


================================================
FILE: main.c
================================================
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "auth.h"
#include "configparse.h"

#ifdef linux
#include <limits.h>
#include "daemon.h"
#include "eapol.h"
#include "libs/common.h"
#endif

#define VERSION "1.6.2"

void print_help(int exval);
int try_smart_eaplogin(void);

static const char default_bind_ip[20] = "0.0.0.0";

int main(int argc, char *argv[]) {
    if (argc == 1) {
        print_help(1);
    }

    char *file_path;

    while (1) {
        static const struct option long_options[] = {
            {"mode", required_argument, 0, 'm'},
            {"conf", required_argument, 0, 'c'},
            {"bindip", required_argument, 0, 'b'},
            {"log", required_argument, 0, 'l'},
#ifdef linux
            {"daemon", no_argument, 0, 'd'},
            {"802.1x", no_argument, 0, 'x'},
#endif
            {"eternal", no_argument, 0, 'e'},
            {"verbose", no_argument, 0, 'v'},
            {"help", no_argument, 0, 'h'},
            {0, 0, 0, 0}};

        int c;
        int option_index = 0;
#ifdef linux
        c = getopt_long(argc, argv, "m:c:b:l:dxevh", long_options, &option_index);
#else
        c = getopt_long(argc, argv, "m:c:b:l:evh", long_options, &option_index);
#endif

        if (c == -1) {
            break;
        }
        switch (c) {
            case 'm':
                if (strcmp(optarg, "dhcp") == 0) {
                    strcpy(mode, optarg);
                } else if (strcmp(optarg, "pppoe") == 0) {
                    strcpy(mode, optarg);
                } else {
                    printf("unknown mode\n");
                    exit(1);
                }
                break;
            case 'c':
#ifndef __APPLE__
                if (mode != NULL) {
#endif
#ifdef linux
                    char path_c[PATH_MAX];
                    realpath(optarg, path_c);
                    file_path = strdup(path_c);
#else
                file_path = optarg;
#endif
#ifndef __APPLE__
                }
#endif
                break;
            case 'b':
                strcpy(bind_ip, optarg);
                break;
            case 'l':
#ifndef __APPLE__
                if (mode != NULL) {
#endif
#ifdef linux
                    char path_l[PATH_MAX];
                    realpath(optarg, path_l);
                    log_path = strdup(path_l);
#else
                log_path = optarg;
#endif
                    logging_flag = 1;
#ifndef __APPLE__
                }
#endif
                break;
#ifdef linux
            case 'd':
                daemon_flag = 1;
                break;
            case 'x':
                eapol_flag = 1;
                break;
#endif
            case 'e':
                eternal_flag = 1;
                break;
            case 'v':
                verbose_flag = 1;
                break;
            case 'h':
                print_help(0);
                break;
            case '?':
                print_help(1);
                break;
            default:
                break;
        }
    }

#ifndef __APPLE__
    if (mode != NULL && file_path != NULL) {
#endif
#ifdef linux
        if (daemon_flag) {
            daemonise();
        }
#endif

#ifdef WIN32  // dirty fix with win32
        char tmp[10] = {0};
        strcpy(tmp, mode);
#endif
        if (!config_parse(file_path)) {
#ifdef WIN32  // dirty fix with win32
            strcpy(mode, tmp);
#endif

#ifdef linux
            if (eapol_flag) {  // eable 802.1x authorization
                if (0 != try_smart_eaplogin()) {
                    printf("Can't finish 802.1x authorization!\n");
                    return 1;
                }
            }
#endif
            if (strlen(bind_ip) == 0) {
                memcpy(bind_ip, default_bind_ip, sizeof(default_bind_ip));
            }
            dogcom(5);
        } else {
            return 1;
        }
#ifndef __APPLE__
    } else {
        printf("Need more options!\n\n");
        return 1;
    }
#endif
    return 0;
}

void print_help(int exval) {
    printf("\nDrcom-generic implementation in C.\n");
    printf("Version: %s\n\n", VERSION);

    printf("Usage:\n");
    printf("\tdogcom -m <dhcp/pppoe> -c <FILEPATH> [options <argument>]...\n\n");

    printf("Options:\n");
    printf("\t--mode <dhcp/pppoe>, -m <dhcp/pppoe>  set your dogcom mode \n");
    printf("\t--conf <FILEPATH>, -c <FILEPATH>      import configuration file\n");
    printf("\t--bindip <IPADDR>, -b <IPADDR>        bind your ip address(default is 0.0.0.0)\n");
    printf("\t--log <LOGPATH>, -l <LOGPATH>         specify log file\n");
#ifdef linux
    printf("\t--daemon, -d                          set daemon flag\n");
    printf("\t--802.1x, -x                          enable 802.1x\n");
#endif
    printf("\t--eternal, -e                         set eternal flag\n");
    printf("\t--verbose, -v                         set verbose flag\n");
    printf("\t--help, -h                            display this help\n\n");
    exit(exval);
}

#ifdef linux
int try_smart_eaplogin(void) {
#define IFS_MAX (64)
    int ifcnt = IFS_MAX;
    iflist_t ifs[IFS_MAX];
    if (0 > getall_ifs(ifs, &ifcnt))
        return -1;

    for (int i = 0; i < ifcnt; ++i) {
        setifname(ifs[i].name);
        if (0 == eaplogin(drcom_config.username, drcom_config.password))
            return 0;
    }
    return -1;
}
#endif

================================================
FILE: sample-d.conf
================================================
server = '192.168.1.14'
username = 'a'
password = 'a'
CONTROLCHECKSTATUS = '\x20'
ADAPTERNUM = '\x01'
host_ip = '10.30.22.17'
IPDOG = '\x01'
host_name = 'LIYUANYUAN'
PRIMARY_DNS = '114.114.114.114'
dhcp_server = '0.0.0.0'
AUTH_VERSION = '\x0A\x00'
mac = 0xb888e3051680
host_os = '8089D'
KEEP_ALIVE_VERSION = '\xDC\x02'
ror_version = True
keepalive1_mod = True

================================================
FILE: sample-p.conf
================================================
server = '192.168.1.14'
pppoe_flag = '\x18'
keep_alive2_flag = '\xd8'
Download .txt
gitextract_f9rp1ayh/

├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── auth.c
├── auth.h
├── configparse.c
├── configparse.h
├── daemon.c
├── daemon.h
├── debug.h
├── eapol.c
├── eapol.h
├── keepalive.c
├── keepalive.h
├── libs/
│   ├── common.c
│   ├── common.h
│   ├── md4.c
│   ├── md4.h
│   ├── md5.c
│   ├── md5.h
│   ├── sha1.c
│   └── sha1.h
├── main.c
├── sample-d.conf
└── sample-p.conf
Download .txt
SYMBOL INDEX (107 symbols across 18 files)

FILE: auth.c
  type socklen_t (line 10) | typedef int socklen_t;
  function dhcp_challenge (line 28) | int dhcp_challenge(int sockfd, struct sockaddr_in addr, unsigned char se...
  function dhcp_login (line 82) | int dhcp_login(int sockfd, struct sockaddr_in addr, unsigned char seed[]...
  function pppoe_challenge (line 365) | int pppoe_challenge(int sockfd, struct sockaddr_in addr, int *pppoe_coun...
  function pppoe_login (line 436) | int pppoe_login(int sockfd, struct sockaddr_in addr, int *pppoe_counter,...
  function dogcom (line 527) | int dogcom(int try_times) {
  function print_packet (line 715) | void print_packet(char msg[10], unsigned char *packet, int length) {
  function logging (line 723) | void logging(char msg[10], unsigned char *packet, int length) {
  function get_lasterror (line 745) | void get_lasterror(char *msg) {

FILE: auth.h
  type sockaddr_in (line 24) | struct sockaddr_in
  type sockaddr_in (line 25) | struct sockaddr_in
  type sockaddr_in (line 26) | struct sockaddr_in
  type sockaddr_in (line 27) | struct sockaddr_in

FILE: configparse.c
  type config (line 14) | struct config
  function config_parse (line 19) | int config_parse(char *filepath) {
  function read_d_config (line 44) | static int read_d_config(char *buf, int size) {
  function read_p_config (line 152) | static int read_p_config(char *buf, int size) {

FILE: configparse.h
  type config (line 4) | struct config {
  type config (line 25) | struct config

FILE: daemon.c
  function kill_daemon (line 15) | void kill_daemon() {
  function signal_handler (line 20) | void signal_handler(int signal) {
  function daemonise (line 35) | void daemonise() {

FILE: eapol.c
  type sockaddr (line 41) | struct sockaddr
  type sockaddr (line 42) | struct sockaddr
  type sockaddr (line 43) | struct sockaddr
  type sockaddr (line 44) | struct sockaddr
  type sockaddr (line 45) | struct sockaddr
  type sockaddr (line 46) | struct sockaddr
  type sockaddr (line 47) | struct sockaddr
  type sockaddr (line 48) | struct sockaddr
  type sockaddr (line 49) | struct sockaddr
  type sockaddr (line 50) | struct sockaddr
  function eapol_init (line 60) | static int eapol_init(int *skfd, struct sockaddr *skaddr) {
  function filte_req_identity (line 112) | static int filte_req_identity(int skfd, struct sockaddr const *skaddr) {
  function filte_req_md5clg (line 131) | static int filte_req_md5clg(int skfd, struct sockaddr const *skaddr) {
  function filte_success (line 166) | static int filte_success(int skfd, struct sockaddr const *skaddr) {
  function eapol_start (line 186) | static int eapol_start(int skfd, struct sockaddr const *skaddr) {
  function eapol_logoff (line 207) | static int eapol_logoff(int skfd, struct sockaddr const *skaddr) {
  function eap_res_identity (line 228) | static int eap_res_identity(int skfd, struct sockaddr const *skaddr) {
  function eap_md5_clg (line 242) | static int eap_md5_clg(int skfd, struct sockaddr const *skaddr) {
  function eap_keep_alive (line 265) | static int eap_keep_alive(int skfd, struct sockaddr const *skaddr) {
  function eap_daemon (line 327) | static int eap_daemon(int skfd, struct sockaddr const *skaddr) {
  function eaplogin (line 386) | int eaplogin(char const *uname, char const *pwd) {
  function eaplogoff (line 468) | int eaplogoff(void) {
  function eaprefresh (line 491) | int eaprefresh(char const *uname, char const *pwd) {
  function setifname (line 496) | void setifname(char const *_ifname) {

FILE: eapol.h
  type ethII_t (line 34) | typedef struct {
  type eapol_t (line 40) | typedef struct {
  type eap_t (line 51) | typedef struct {
  type eapbody_t (line 70) | typedef union {

FILE: keepalive.c
  type socklen_t (line 7) | typedef int socklen_t;
  function keepalive_1 (line 21) | int keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[...
  function gen_crc (line 171) | void gen_crc(unsigned char seed[], int encrypt_type, unsigned char crc[]) {
  function keepalive_2_packetbuilder (line 213) | void keepalive_2_packetbuilder(unsigned char keepalive_2_packet[], int k...
  function keepalive_2 (line 244) | int keepalive_2(int sockfd, struct sockaddr_in addr, int *keepalive_coun...

FILE: keepalive.h
  type sockaddr_in (line 4) | struct sockaddr_in
  type sockaddr_in (line 5) | struct sockaddr_in

FILE: libs/common.c
  function getexedir (line 31) | extern int getexedir(char *exedir)
  function mac_equal (line 48) | extern int mac_equal(uchar const *mac1, uchar const *mac2)
  function ip_equal (line 58) | extern int ip_equal(int type, void const *ip1, void const *ip2)
  function is_filter (line 74) | static int is_filter(char const *ifname)
  function getall_ifs (line 117) | extern int getall_ifs(iflist_t *ifs, int *cnt)
  type tm (line 188) | struct tm
  function copy (line 197) | extern int copy(char const *f1, char const *f2)
  function islsb (line 219) | static int islsb()
  function uint16 (line 224) | static uint16 exorders(uint16 n)
  function uint32 (line 228) | static uint32 exorderl(uint32 n)
  function uint16 (line 232) | extern uint16 htols(uint16 n)
  function uint16 (line 236) | extern uint16 htoms(uint16 n)
  function uint16 (line 240) | extern uint16 ltohs(uint16 n)
  function uint16 (line 244) | extern uint16 mtohs(uint16 n)
  function uint32 (line 248) | extern uint32 htoll(uint32 n)
  function uint32 (line 252) | extern uint32 htoml(uint32 n)
  function uint32 (line 256) | extern uint32 ltohl(uint32 n)
  function uint32 (line 260) | extern uint32 mtohl(uint32 n)
  function uchar (line 264) | extern uchar const *format_mac(uchar const *macarr)
  function format_data (line 278) | extern void format_data(uchar const *d, size_t len)
  function difftimespec (line 295) | extern long difftimespec(struct timespec t1, struct timespec t0)
  function isnetok (line 310) | extern int isnetok(char const *ifname)
  function msleep (line 320) | extern void msleep(long ms)

FILE: libs/common.h
  type uchar (line 6) | typedef unsigned char uchar;
  type uint16 (line 7) | typedef unsigned short uint16;
  type uint32 (line 8) | typedef unsigned int uint32;
  type iflist_t (line 31) | typedef struct {
  type timespec (line 149) | struct timespec
  type timespec (line 149) | struct timespec

FILE: libs/md4.c
  function MD4_Init (line 186) | void MD4_Init(MD4_CTX *ctx)
  function MD4_Update (line 197) | void MD4_Update(MD4_CTX *ctx, const void *data, unsigned long size)
  function MD4_Final (line 237) | void MD4_Final(unsigned char *result, MD4_CTX *ctx)
  function MD4 (line 270) | void MD4(const void *data, unsigned long size, unsigned char *result) {

FILE: libs/md4.h
  type MD4_u32plus (line 32) | typedef unsigned int MD4_u32plus;
  type MD4_CTX (line 34) | typedef struct {

FILE: libs/md5.c
  function MD5_Init (line 207) | void MD5_Init(MD5_CTX *ctx)
  function MD5_Update (line 218) | void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size)
  function MD5_Final (line 258) | void MD5_Final(unsigned char *result, MD5_CTX *ctx)
  function MD5 (line 291) | void MD5(const void *data, unsigned long size, unsigned char *result) {

FILE: libs/md5.h
  type MD5_u32plus (line 32) | typedef unsigned int MD5_u32plus;
  type MD5_CTX (line 34) | typedef struct {

FILE: libs/sha1.c
  function SHA1Transform (line 54) | void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  function SHA1Init (line 115) | void SHA1Init(SHA1_CTX* context)
  function SHA1Update (line 129) | void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len)
  function SHA1Final (line 153) | void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
  function SHA1 (line 198) | void SHA1(const unsigned char* data, uint32_t len, unsigned char digest[...

FILE: libs/sha1.h
  type SHA1_CTX (line 11) | typedef struct {

FILE: main.c
  type option (line 30) | struct option
  function print_help (line 167) | void print_help(int exval) {
  function try_smart_eaplogin (line 190) | int try_smart_eaplogin(void) {
Condensed preview — 27 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (160K chars).
[
  {
    "path": ".gitignore",
    "chars": 473,
    "preview": "test\ndrcom.conf\ntest.conf\ndogcom\nmain\n.vscode\n\n# Prerequisites\n*.d\n\n# Object files\n*.o\n*.ko\n*.obj\n*.elf\n\n# Linker output"
  },
  {
    "path": ".travis.yml",
    "chars": 215,
    "preview": "language: c\nos:\n    - linux\n    - osx\ncompiler:\n    - gcc\n    - clang\n\nscript:\n    - make test=y\n    - ./dogcom -m dhcp "
  },
  {
    "path": "LICENSE",
    "chars": 34520,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "Makefile",
    "chars": 764,
    "preview": "CC     = gcc\nTARGET = dogcom\nINSTALL_DIR = /usr/bin/\n\nifeq ($(debug), y)\n\tCFLAGS += -DDEBUG -g\nendif\n\nifeq ($(win32), y)"
  },
  {
    "path": "README.md",
    "chars": 2523,
    "preview": "# dogcom [![travis-ci](https://travis-ci.org/mchome/dogcom.svg \"Build status\")](https://travis-ci.org/mchome/dogcom) [!["
  },
  {
    "path": "auth.c",
    "chars": 25507,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n\n"
  },
  {
    "path": "auth.h",
    "chars": 1115,
    "preview": "#ifndef AUTH_H_\n#define AUTH_H_\n\n#ifdef WIN32\n#include <winsock2.h>\n#else\n#include <netinet/in.h>\n#endif\n\nenum {\n    CHE"
  },
  {
    "path": "configparse.c",
    "chars": 6362,
    "preview": "#include \"configparse.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"debug.h\"\n\nint verbose_flag"
  },
  {
    "path": "configparse.h",
    "chars": 840,
    "preview": "#ifndef CONFIGPARSE_H_\n#define CONFIGPARSE_H_\n\nstruct config {\n    char server[20];\n    char username[36];\n    char pass"
  },
  {
    "path": "daemon.c",
    "chars": 2070,
    "preview": "#ifdef linux\n\n#include <fcntl.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include"
  },
  {
    "path": "daemon.h",
    "chars": 182,
    "preview": "#ifndef DAEMON_H_\n#define DAEMON_H_\n\nvoid kill_daemon();\nvoid signal_handler(int signal);\nvoid daemonise();\n\nextern int "
  },
  {
    "path": "debug.h",
    "chars": 123,
    "preview": "#ifdef DEBUG\n#define DEBUG_PRINT(s) printf s\n#else\n#define DEBUG_PRINT(s) \\\n    do {               \\\n    } while (0)\n#en"
  },
  {
    "path": "eapol.c",
    "chars": 16767,
    "preview": "#ifdef linux\n\n#include \"eapol.h\"\n#include \"libs/common.h\"\n#include \"libs/md5.h\"\n\n#include <arpa/inet.h>\n#include <net/et"
  },
  {
    "path": "eapol.h",
    "chars": 2351,
    "preview": "#ifndef EAPOL_H__\n#define EAPOL_H__\n\n#include \"libs/common.h\"\n\n#define IDEN_LEN UNAME_LEN\n\n#define TRY_TIMES (3)\n/* 每次请求"
  },
  {
    "path": "keepalive.c",
    "chars": 13169,
    "preview": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef WIN32\n#include <winsock2.h>\ntypedef int socklen_t;\n#e"
  },
  {
    "path": "keepalive.h",
    "chars": 496,
    "preview": "#ifndef KEEPALIVE_H_\n#define KEEPALIVE_H_\n\nint keepalive_1(int sockfd, struct sockaddr_in addr, unsigned char seed[], un"
  },
  {
    "path": "libs/common.c",
    "chars": 6315,
    "preview": "#ifdef linux\n\n/*\n * 一些通用的代码\n */\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <"
  },
  {
    "path": "libs/common.h",
    "chars": 3325,
    "preview": "#ifndef COMMON_H__\n#define COMMON_H__\n/*\n * 通用的代码和定义\n */\ntypedef unsigned char uchar;\t/* 一个字节 */\ntypedef unsigned short "
  },
  {
    "path": "libs/md4.c",
    "chars": 7682,
    "preview": "/*\n * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.\n * MD4 Message-Digest Algorithm (RFC 1"
  },
  {
    "path": "libs/md4.h",
    "chars": 1482,
    "preview": "/*\n * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.\n * MD4 Message-Digest Algorithm (RFC 1"
  },
  {
    "path": "libs/md5.c",
    "chars": 8906,
    "preview": "/*\n * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.\n * MD5 Message-Digest Algorithm (RFC 1"
  },
  {
    "path": "libs/md5.h",
    "chars": 1482,
    "preview": "/*\n * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.\n * MD5 Message-Digest Algorithm (RFC 1"
  },
  {
    "path": "libs/sha1.c",
    "chars": 6894,
    "preview": "\n/* from valgrind tests */\n\n/* ================ sha1.c ================ */\n/*\nSHA-1 in C\nBy Steve Reid <steve@edmweb.com"
  },
  {
    "path": "libs/sha1.h",
    "chars": 603,
    "preview": "#ifndef SHA1_H\n#define SHA1_H\n/* ================ sha1.h ================ */\n/*\nSHA-1 in C\nBy Steve Reid <steve@edmweb.c"
  },
  {
    "path": "main.c",
    "chars": 5362,
    "preview": "#include <getopt.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"auth.h\"\n#include \"configparse.h"
  },
  {
    "path": "sample-d.conf",
    "chars": 359,
    "preview": "server = '192.168.1.14'\nusername = 'a'\npassword = 'a'\nCONTROLCHECKSTATUS = '\\x20'\nADAPTERNUM = '\\x01'\nhost_ip = '10.30.2"
  },
  {
    "path": "sample-p.conf",
    "chars": 69,
    "preview": "server = '192.168.1.14'\npppoe_flag = '\\x18'\nkeep_alive2_flag = '\\xd8'"
  }
]

About this extraction

This page contains the full source code of the mchome/dogcom GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 27 files (146.4 KB), approximately 45.4k tokens, and a symbol index with 107 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.

Copied to clipboard!