[
  {
    "path": ".gitignore",
    "content": "**/*.o\n**/*.swp\ndeb/package/\ndeb/pcapfix.deb\npcapfix\n"
  },
  {
    "path": "COPYING",
    "content": "\n\t\t    GNU GENERAL PUBLIC LICENSE\n\t\t       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n\t\t\t    Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n\t\t       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n \n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n  \n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n\t\t     END OF TERMS AND CONDITIONS\n\n\t    How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\n"
  },
  {
    "path": "Changelog",
    "content": "pcapfix Changelog\n*****************\n\n1.1.7 - 03.07.2021\n-------\n* fixed security issues\n\n1.1.6 - 13.06.2021\n-------\n* added security boundary checks in pcapng format\n\n1.1.5 - 05.04.2021\n-------\n* snaplen checks are only performed in soft mode now\n* fixed repairs for dlt 195 (ieee 802.15.4 with fcs)\n* fixed (binary) file repair bug under Microsoft Windows\n* improved compiling on all platforms (thanks to mdeweerd)\n\n1.1.4 - 22.01.2019\n------------------\n* added support for extended pcap file format (kuznetzov)\n* fixed dtl 113 (linux cooked) handling (thanks to Andre Luyer)\n* improved hard and soft mode checks for younger/older packets\n* minor fixes and improvements\n\n1.1.3 - 04.09.2018\n------------------\n* implemtented soft mode (for plausibility checks)\n\n1.1.2 - 16.07.2018\n------------------\n* fixed cross compiling (thanks to Helmut Grohne)\n* increased maximum snap length to 262144\n\n1.1.1 - 25.12.2017\n------------------\n* added write buffers and support to perform repair\n  process without creation of a separate output file\n* fixed another MacOS build problem\n* fixed minor bugs\n\n1.1.0 - 31.08.2014\n------------------\n* added checks for valid pcapng format (epb)\n* added --outfile parameter to chose fixed file name\n* improved pcapng packet alignment (pb, spb, nrb)\n* improved pcapng option fields handling\n* improved status and verbosity outputs\n* fixed reparation bugs with swapped pcap files\n* fixed MacOS compile problem\n* fixed windows output file name extension missing\n* fixed many minor bugs\n\n1.0.2 - 18.02.2014\n------------------\n* added support for files larger than 2GB on 32bit systems\n\n1.0.1 - 03.11.2013\n------------------\n* added reparation block type id zero (pcapng)\n* added reparation of capture length inside EPB (pcapng)\n* set data link type to ethernet on missing header (pcap)\n* changed missing pcap header threshold\n* fixed minor bugs\n\n1.0.0 - 12.10.2013\n------------------\n* added pcapng support\n* added nanoseconds support (Issue #1)\n* improved console output\n* minor bugs fixed\n\n0.7.3 - 16.06.2013\n------------------\n* added snoop file detection\n* added large file support on 32bit architectures\n* improved missing header detection\n* fixed compiling errors on hurd and kfreebsd architectures\n* fixed minor bugs\n\n0.7.2 - 30.03.2013\n------------------\n* compiles on Apple systems properly now\n* fixed problems installing man-pages (on some systems)\n\n0.7.1 - 03.01.2013\n------------------\n* REALLY fixed file pointer exception on windows64 systems\n* updated man-page\n\n0.7 - 18.10.2012\n----------------\n* added support for swapped (big endian) pcap files\n* compiles on OpenBSD properly now\n* fixed file pointer exception on windows64 systems\n* fixed detection bug when corrupted packet is larger than 65536 bytes\n* fixed minimal packet limit to cope with wlan traffic\n\n0.6 - 20.05.2012\n----------------\n* added deep scan option (-d) to force packet detection inside the whole file\n* detects ascii-corruption in pcap header (unix->win)\n* improved global header and packet checks (0 <= usec <= 1000000)\n* repair files that first packet is entirely corrupted\n* repair oversized packets\n* improved last packet mismatch correction\n* fixed reading packets over EOF\n\n0.5 - 05.05.2012\n----------------\n* repair files that packets were not saved chronologically\n* detect and repair overlapping packets\n* detect and repair cut-off pcap files\n* detect and repair ascii-mode transfered pcap files (pcap headers only!)\n* added progress bar\n* added man-page\n\n0.4 - 27.04.2012\n----------------\n* completely redesigned packet detection algorithm (replaced bottom-up-recovery with brute-force-packet-guessing)\n* improved detection rate by additional plausability checks\n* increased speed when repairing large pcap files\n\n0.3 - 31.03.2012\n----------------\n* when recovering packets size will be checked to be smaller than 65536\n* added recognition when a file does not seem to be a pcap file at all\n* compiles on windows systems properly now (tested with dev-cpp)\n* added option to manually select data link type\n\n0.2 - 11.03.2012\n----------------\n* pcapfix compiles on 64bit systems correctly now\n* fixed segfault when no filename was given\n* fixed (input) file not found bug on directory differ\n* added recognition of other data link types beside ethernet in global header\n* added source code documentation\n\n0.1 - 01.03.2012\n----------------\n* this is the first version, everything has changed thou :-)\n"
  },
  {
    "path": "INSTALL",
    "content": "Installation Instructions\n*************************\n\nTo compile pcapfix you need GNU Make and GNU-C/C++.\nPlease check via 'make -v' whether you are using a proper version.\nThe result should show something similar to 'GNU Make 4.3' in its output.\n\nBasic Installation\n==================\n\n1. Compile pcapfix with the following command:\n\n\tmake\n\n2. Install the binary file\n\n\tmake install\n\n\nThe tool will be installed in /usr by default. To change this, edit\nthe $PREFIX variable in Makefile.\n\n\nUninstall\n=========\n\nTo uninstall pcapfix just enter:\n\n\tmake uninstall\n\n\nMicrosoft Windows\n=================\n\nCompile pcapfix using cygwin:\n\tgcc -c pcap.c -o pcap.o\n\tgcc -c pcap_kuznet.c -o pcap_kuznet.o\n\tgcc -c pcapng.c -o pcapng.o\n\tgcc -c winfunc.c -o winfunc.o\n\tgcc pcapfix.c pcap.o pcap_kuznet.c pcapng.o winfunc.o -l ws2_32 -o pcapfix.exe\n\n\nTroubleshooting\n===============\n\nIf there are any problems compiling the program, please write an email\nto ruport@f00l.de and include your compiling error message.\n"
  },
  {
    "path": "Makefile",
    "content": "PREFIX ?= /usr\nBINDIR ?= $(PREFIX)/bin\nDOCDIR ?= $(PREFIX)/share/doc\nMANDIR ?= $(PREFIX)/share/man\n\nOPTFLAGS = $(shell getconf LFS_CFLAGS) -D_FORTIFY_SOURCE=2 -O2 -fstack-protector --param=ssp-buffer-size=4\nWARNFLAGS = -Wall -Wextra -std=gnu99 -pedantic -Wformat -Werror=format-security\nDEBUGFLAGS = -g\nCFLAGS += $(OPTFLAGS) $(WARNFLAGS) $(DEBUGFLAGS)\n\n# Determine extra LDFLAGS\nOS := $(shell uname)\nifeq ($(findstring Darwin,$(OS)),Darwin)\n   skip_ldflags = yes\nendif\nifeq ($(findstring CYGWIN,$(OS)),CYGWIN)\n   skip_ldflags = yes\nendif\nifndef skip_ldflags\n   LDFLAGS += -Wl,-z,relro\nendif\n\nall: pcap pcap_kuznet pcapng\n\t$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) pcapfix.c pcap.o pcap_kuznet.o pcapng.o -o pcapfix\n\npcap: pcap.c\n\t$(CC) $(CPPFLAGS) $(CFLAGS) -c pcap.c -o pcap.o\n\npcap_kuznet: pcap_kuznet.c\n\t$(CC) $(CPPFLAGS) $(CFLAGS) -c pcap_kuznet.c -o pcap_kuznet.o\n\npcapng: pcapng.c\n\t$(CC) $(CPPFLAGS) $(CFLAGS) -c pcapng.c -o pcapng.o\n\n.PHONY: install\ninstall:\n\tinstall -pDm755 pcapfix $(DESTDIR)$(BINDIR)/pcapfix\n\tinstall -pDm644 pcapfix.1 $(DESTDIR)$(MANDIR)/man1/pcapfix.1\n\n.PHONY: uninstall\nuninstall:\n\trm -f $(DESTDIR)$(BINDIR)/pcapfix\n\trm -f $(DESTDIR)$(MANDIR)/man1/pcapfix.1\n\nclean:\n\trm -f *.o\n\trm -f pcapfix\n"
  },
  {
    "path": "README",
    "content": "pcapfix v1.1.7 README\n*********************\n\nPcapfix is a tool to repair your damaged or corrupted pcap and pcapng files.\nIt is written in C and released under the GNU General Public License.\n\nTo fix your pcap files the tool first checks for an intact pcap global header\nand repairs it if there are some corrupted bytes. It there seems to be no\nglobal header at all, pcapfix adds a self-created one at the beginning of the\nfile. In a second step the tool tries to find pcap packet headers inside the\nfile, below the global header. It checks if the values are correct (or seem\nto be correct) and tries to repair a packet if there is something wrong. \n\nTo fix your pcapng files the tool loops through all packet headers that can\nbe found in the file. It checks for mandatory Section Header Block and\nInterface Description Block and creates them if missing. Pcapfix checks for\ncorrect block sizes and valid option fields. If something is wrong, invalid\nfields are repaired (if possible) or skipped and adjusted to finally get a\nproper pcapng file.\n\nPlease send any further wishes, feature requests or problems in compiling\nand execution to ruport@f00l.de. Additionally You may send me pcap/pcapng\nfiles that could not be repaired too in order to improve pcapfix and get\nyour file repaired.\n\nFor further information visit the pcapfix homepage at http://f00l.de/pcapfix/.\n\nUSAGE\n=====\n\n./pcapfix [OPTIONS] filename\nOPTIONS:        -d        , --deep-scan \t  \tDeep Scan (default = 0) (pcap only!)\n\t\t-s        , --soft-mode\t\t\tSoft mode (packet detection)\n                -n        , --pcapng \t  \t\tForce File Format to PCAPNG\n\t\t-o <file> , --outfile <file>\t\tSet output file name\n                -t <nr>\t  , --data-link-type <nr>\tData Link Type (default = 1)\n                -v        , --verbose \t  \t\tVerbose output (default = 0)\n\nOutput file name\n................\nIf you want to perform the reparation process on the input file without creating a\nseparate output file - e.g. in case you are out of space, you can use the -o option\nand give the same name as the input file.\n\nWARNING: This process is DANGEROUS and may destroy your data. You should only use\nthis option if you know what you are doing and accept the risk of losing the input\nfile.\n\nDeep Scan Option\n................\n\nIn classic pcap files, pcapfix will only scan the first 262144 bytes (maximum\npacket length) for a proper first packet. If you want to force packet detection\neven above this limit (e.g. because your file has been heavily destroyed) you\ncan use the deep scan option (-d).\n\nThis option is not necessary for pcapng files because the whole file is arranged\nin blocks that are 'unlimited' by default. In result pcapfix will always scan\nthe whole pcapng file for further blocks.\n\n\nSoft Mode\n.........\n\nThere are programs that breach some pcap conventions when writing files.\nIgnoring those rules do not break the pcap file but they make it difficult for\npcapfix to identify the packets in case of broken files.\n\nBy default pcapfix uses hard mode. If you encounter problems when repairing\nfiles, try to switch to soft mode (-s). Pcapfix will then try to find the\npackets in a more tolerant way.\n\n\nPCAPNG Format\n.............\n\nPcapfix will try to identify the file format to repair (pcap / pcapng) before\ndoing any further checks. If the header itself is corrupted, it will assume the\nformat to be classic pcap. To change this behaviour you can force the tool to\ndo a pcapng-repair by supplying -n (--pcapng) option.\n\n\nVerbosity\n.........\n\nYou can use multiple -v options to increase verbosity.\nAn verbosity of 2 will result in very much output data during package search.\n\n\nASCII-mode transfered Files (FTP)\n.................................\n\nPcapfix is able to repair classic pcap files that have been transfered in\nascii-mode via FTP. In those files a proper pcap structure will be created\nonly to make them readable by wireshark etc. The data inside the packets\n(and some pcap headers) might still be corrupted. To repair those packets\na deeper look inside the packet structure (e.g. checksum) will be necessary.\n\n\nData Link Types\n...............\n\nYou can make pcapfix change / select your data link type by supplying -t option.\nAlthough you may select a data link type number between 0 and 255, only the\nfollowing types are assigned: If the data link type field is corrupt, pcapfix\nwill select LINKTYPE_ETHERNET by default.\n\nSee http://www.tcpdump.org/linktypes.html for futher information.\n\nNUMBER\tLINK_TYPE\n\n0\tLINKTYPE_NULL\n1\tLINKTYPE_ETHERNET\n6\tLINKTYPE_TOKEN_RING\n7\tLINKTYPE_ARCNET_BSD\n8\tLINKTYPE_SLIP\n9\tLINKTYPE_PPP\n10\tLINKTYPE_FDDI\n50\tLINKTYPE_PPP_HDLC\n51\tLINKTYPE_PPP_ETHER\n100\tLINKTYPE_ATM_RFC1483\n101\tLINKTYPE_RAW\n104\tLINKTYPE_C_HDLC\n105\tLINKTYPE_IEEE802_11\n107\tLINKTYPE_FRELAY\n108\tLINKTYPE_LOOP\n113\tLINKTYPE_LINUX_SLL\n114\tLINKTYPE_LTALK\n117\tLINKTYPE_PFLOG\n119\tLINKTYPE_PRISM_HEADER\n122\tLINKTYPE_IP_OVER_FC\n123\tLINKTYPE_SUNATM\n127\tLINKTYPE_IEEE802_11_RADIO\n129\tLINKTYPE_ARCNET_LINUX\n138\tLINKTYPE_APPLE_IP_OVER_IEEE1394\n139\tLINKTYPE_MTP2_WITH_PHDR\n140\tLINKTYPE_MTP2\n141\tLINKTYPE_MTP3\n142\tLINKTYPE_SCCP\n143\tLINKTYPE_DOCSIS\n144\tLINKTYPE_LINUX_IRDA\n147-162\tLINKTYPE_USER0-LINKTYPE-USER15\n163\tLINKTYPE_IEEE802_11_RADIO_AVS\n166\tLINKTYPE_PPP_PPPD\n169\tLINKTYPE_GPRS_LLC\n177\tLINKTYPE_LINUX_LAPD\n187\tLINKTYPE_BLUETOOTH_HCI_H4\n189\tLINKTYPE_USB_LINUX\n192\tLINKTYPE_PPI\n195\tLINKTYPE_IEEE802_15_4\n196\tLINKTYPE_SITA\n197\tLINKTYPE_ERF\n201\tLINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR\n202\tLINKTYPE_AX25_KISS\n203\tLINKTYPE_LAPD\n204\tLINKTYPE_PPP_WITH_DIR\n205\tLINKTYPE_C_HDLC_WITH_DIR\n206\tLINKTYPE_FRELAY_WITH_DIR\n209\tLINKTYPE_IPMB_LINUX\n215\tLINKTYPE_IEEE802_15_4_NONASK_PHY\n220\tLINKTYPE_USB_LINUX_MMAPPED\n224\tLINKTYPE_FC_2\n225\tLINKTYPE_FC_2_WITH_FRAME_DELIMS\n226\tLINKTYPE_IPNET\n227\tLINKTYPE_CAN_SOCKETCAN\n228\tLINKTYPE_IPV4\n229\tLINKTYPE_IPV6\n230\tLINKTYPE_IEEE802_15_4_NOFCS\n231\tLINKTYPE_DBUS\n235\tLINKTYPE_DVB_CI\n236\tLINKTYPE_MUX27010\n237\tLINKTYPE_STANAG_5066_D_PDU\n239\tLINKTYPE_NFLOG\n240\tLINKTYPE_NETANALYZER\n241\tLINKTYPE_NETANALYZER_TRANSPARENT\n242\tLINKTYPE_IPOIB\n243\tLINKTYPE_MPEG_2_TS\n244\tLINKTYPE_NG40\n245\tLINKTYPE_NFC_LLCP\n\nCOPYRIGHT\n=========\n\nCopyright 2012-2021 Robert Krause\n\nPcapfix is free software: you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or any later version.\n\nPcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nPcapfix. If not, see http://www.gnu.org/licenses/.\n"
  },
  {
    "path": "deb/build.sh",
    "content": "#!/bin/sh\n\ndie () {\n    >&2 echo \"$1\"\n    exit 1\n}\n\n\n(\n    rm -rf package || die \"Failed to remove old packages\"\n)\n\n(\n    cd ../\n    make -j \"$(nproc)\" || die \"Failed to build project\"\n    make DESTDIR=\"deb/package/\" install || die \"Failed to install project into package directory\"\n)\n\nmkdir -p package/DEBIAN/\nVERSION=\"$(head -n 1 ../README | sed -E \"s/^pcapfix v([[:digit:]]+.[[:digit:]]+.[[:digit:]]+) README$/\\1/\")\"\ncp control.template package/DEBIAN/control\nsed \"s/%VERSION%/$VERSION/\" -i package/DEBIAN/control\nsed \"s/%ARCHITECTURE%/$(dpkg --print-architecture)/\" -i package/DEBIAN/control\n\nmkdir -p package/usr/share/doc/pcapfix/\ncp copyright package/usr/share/doc/pcapfix/copyright\n\necho \"Building package...\"\ndpkg-deb --root-owner-group --build package pcapfix.deb || die \"Failed to build package\"\n\necho \"Package $(dpkg-deb --show pcapfix.deb | sed \"s/\\t/ /\") successful builded!\"\n"
  },
  {
    "path": "deb/control.template",
    "content": "Package: pcapfix\nVersion: %VERSION%\nArchitecture: %ARCHITECTURE%\nSection: utils\nPriority: optional\nHomepage: https://f00l.de/pcapfix/\nMaintainer: Robert Krause <ruport@f00l.de>\nDescription: pcapfix tries to repair your broken pcap and pcapng files\n  Pcapfix is a tool to repair your damaged or corrupted pcap and pcapng files.\n  It is written in C and released under the GNU General Public License.\n  .\n  To fix your pcap files the tool first checks for an intact pcap global header\n  and repairs it if there are some corrupted bytes. It there seems to be no\n  global header at all, pcapfix adds a self-created one at the beginning of the\n  file. In a second step the tool tries to find pcap packet headers inside the\n  file, below the global header. It checks if the values are correct (or seem\n  to be correct) and tries to repair a packet if there is something wrong. \n  .\n  To fix your pcapng files the tool loops through all packet headers that can\n  be found in the file. It checks for mandatory Section Header Block and\n  Interface Description Block and creates them if missing. Pcapfix checks for\n  correct block sizes and valid option fields. If something is wrong, invalid\n  fields are repaired (if possible) or skipped and adjusted to finally get a\n  proper pcapng file.\n  .\n  Please send any further wishes, feature requests or problems in compiling\n  and execution to ruport@f00l.de. Additionally You may send me pcap/pcapng\n  files that could not be repaired too in order to improve pcapfix and get\n  your file repaired.\n  .\n  For further information visit the pcapfix homepage at http://f00l.de/pcapfix/.\n"
  },
  {
    "path": "deb/copyright",
    "content": "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nSource: https://github.com/Rup0rt/pcapfix/blob/master/COPYING\nUpstream-Name: pcapfix\nUpstream-Contact: Robert Krause <ruport@f00l.de>\n\nFiles: *\nCopyright: Robert Krause <ruport@f00l.de>\nLicense:  GPL-3.0-or-later\n"
  },
  {
    "path": "pcap.c",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#include \"pcapfix.h\"\n#include \"pcap.h\"\n\n/* pcap file global vars */\nint nanoseconds = 0;            /* pcap file uses nanoseconds (instead of microseconds) */\n\n/*\n * Function:  is_plausible\n * -----------------------\n * check if the pcap packet header could be a plausible one by satisfying those conditions:\n * - packet size >= 16 bytes AND <= MAX_SNAPLEN bytes (included length AND original length) (conditions 1,2,3,4,5)\n * - included length <= original lenth (conditions 6,7,8,9)\n * - packet timestamp is NOT older OR younger than the prior packets timestamp -+ one day (conditions 10,11,12)\n * - usec (microseconds) field <= 1000000 (conditions 13)\n * - usec (nanoseconds) field <= 1000000000 (conditions 14)\n *\n * global_hdr: the filled pcap header struct to check for snaplen\n * hdr:        the filled packet header struct to check for plausibility\n * prior_ts:   the prior packets timestamp (seconds) to check for time relation (condition 6,7)\n *\n * returns:  0   success\n *          -X   error (condition X failed)\n *\n */\nint is_plausible(struct global_hdr_s global_hdr, struct packet_hdr_s hdr, unsigned int prior_ts) {\n  /* check for minimum packet size\n   * minimum packet size should be 16, but in some cases, e.g. local wlan capture, packet might\n   * even be smaller --> decreased minimum size to 10 */\n  unsigned int maxlen = 10;\n  if (global_hdr.network == 195) maxlen = 5;\t/* DLT 195 (IEEE 802.15.4) can have very small packets */\n  if (conint(hdr.incl_len) < maxlen) return(-1);\n  if (conint(hdr.orig_len) < maxlen) return(-2);\n\n  /* check packet limit with header field and max snaplen\n     in soft mode (and dlt 119) the packet detection accepts a wider range */\n  if (soft_mode || global_hdr.network == 119) {\n    /* in soft mode, global pcap snap length is ignored, instead MAX snaplen is used */\n\n    /* strange behavior for wlan: in some cases incl length seems to differ\n       not following the configured max snap length; this leads to dropping\n       valid wlan packets -> use soft mode for DLT 119 */\n    if (conint(hdr.incl_len) > PCAP_MAX_SNAPLEN) return(-3);\n  } else {\n    /* in hard mode (and not dlt 119), global pcap snap length is the limit in plausibility checks */\n    if (conint(hdr.incl_len) > conint(global_hdr.snaplen)) return(-4);\n  }\n  /* orig length should not be greater than pcap max snaplen (hard mode only) */\n  if (!soft_mode && conint(hdr.orig_len) > PCAP_MAX_SNAPLEN) return(-5);\n\n  /* if the packet original size is larger than the included length, then\n     the included length should be limited by the files snap length (hard mode only) */\n  if (!soft_mode && conint(hdr.orig_len) > conint(hdr.incl_len)) {\n    /* check for dlt 119 == wlan */\n    if (global_hdr.network == 119) {\n      /* strange behavior for wlan: in some cases incl length seems to differ\n         not following the configured max snap length; this leads to dropping\n         valid wlan packets -> ignore this check for DLT 119 */\n    } else {\n      if (conint(hdr.incl_len) != conint(global_hdr.snaplen)) return(-7);\n    }\n  }\n\n  /* the included length CAN NOT be larger than the original length */\n  /* check for LINKTYPE_LINUX_SLL (linux cooked) */\n  if (global_hdr.network == 113) {\n    /* linux cooked headers are appended to packet length, but not to orig length\n       so we need to remove it from incl_len before checking */\n    if (conint(hdr.incl_len)-16 > conint(hdr.orig_len)) return(-8);\n  } else if (conint(hdr.incl_len) > conint(hdr.orig_len)) return(-9);\n\n  /* check packet times (older) */\n  if (soft_mode) {\n    /* in soft mode, there is no limit for older packets */\n  } else {\n    /* in hard mode, packet must not be older than one day (related to prior packet) */\n    if ((prior_ts != 0) && (conint(hdr.ts_sec) > (prior_ts+86400))) return(-10);\n  }\n\n  /* check packet times (younger) */\n  if (soft_mode) {\n    /* in soft mode, packet must not be younger than one day (related to prior packet) */\n    if ((prior_ts >= 86400) && (conint(hdr.ts_sec) < (prior_ts-86400))) return(-11);\n  } else {\n    /* in hard mode, packets must not be younger than prior packet */\n    if ((prior_ts != 0) && (conint(hdr.ts_sec) < prior_ts)) return(-12);\n  }\n\n  /* check for nano/microseconds (hard mode only) */\n  if (!soft_mode) {\n    /* in hard mode */\n    if (nanoseconds == 0) {\n      /* usec (microseconds) must <= 1000000 */\n      if (conint(hdr.ts_usec) > 1000000) return(-13);\n    } else {\n      /* usec (nanoseconds) must be <= 1000000000 */\n      if (conint(hdr.ts_usec) > 1000000000) return(-14);\n    }\n  }\n\n  /* all conditions fullfilled ==> everything fine! */\n  return(0);\n}\n\n/*\n * Function:  check_header\n * -----------------------\n * this function takes a buffer and brute forces some possible ascii-corrupted bytes versus plausibility checks\n *\n * buffer:     the buffer that might contain the possible pcap packet header\n * size:       the size of the buffer (double pcap packet header size is a good choice)\n * priot_ts:   the prior packets timestamp (to check for plausibility)\n * global_hdr: the pointer to the pcap header\n * hdr:        the pointer to the packet header buffer (we use this to return the repaired header)\n *\n * returns: >=0   success (return value contains number of ascii corrupted bytes in hdr (we need this data to align the beginning of the packet body later)\n *           -1   error (no valid pcap header found inside buffer)\n *\n */\nint check_header(char *buffer, unsigned int size, unsigned int prior_ts, struct global_hdr_s *global_hdr, struct packet_hdr_s *hdr) {\n  unsigned int i; /* loop variable - first byte in buffer that could be beginning of packet */\n  int res;        /* return value */\n  char *tmp;      /* the temporary buffer that will be used for recursion */\n\n  /* does the buffer already contain a valid packet header (without any correction) ?? */\n  memcpy(hdr, buffer, sizeof(struct packet_hdr_s));\n  res = is_plausible(*global_hdr, *hdr, prior_ts);\n  if (res == 0) return(0);\n\n  if (verbose >= 2) printf(\"[-] Header plausibility check failed with error code %d\\n\", res);\n\n  /* we need to abort the recursion of there are too many possible ascii corrupted bytes at ones */\n  /* 32-25 = 7 bytes maximum in 32bytes of data! */\n  if (size <= 25) return(-1);\n\n  /* this loop will check the the buffer for occurence of 0x0D + 0x0A (UNIX to WINDOWS ascii corruption) */\n  for(i=0; i<sizeof(struct packet_hdr_s); i++) {\n    /* is there a 0x0D 0X0A combination at this position? */\n    if (buffer[i] == 0x0D && buffer[i+1] == 0x0A) {\n\n      /* allocate memory for recursion buffer */\n      tmp = malloc(size);\n\n      /* we cut out 0x0D because this byte could have been added due to ftp ascii transfer eg */\n      memcpy(tmp, buffer, i);\n      memcpy(tmp+i, buffer+i+1, size-i-1);\n\n      /* and invoke the header again without this 0x0D byte */\n      res = check_header(tmp, size-1, prior_ts, global_hdr, hdr);\n\n      /* free recursion buffer */\n      free(tmp);\n\n      /* if the check was successfull (maybe with multiple recursions) return the value added by one (body shift offset) */\n      if (res != -1) return(res+1);\n    }\n  }\n\n  /* the buffer (even after ascii corruption brute force) does not contain any valid pcap packet header */\n  return(-1);\n}\n\n/*\n * Function:  fix_pcap\n * -------------------\n * tries to fix a classic pcap file\n *\n * pcap:      file pointer to input file\n * pcap_fix:  file pointer to output file\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap(FILE *pcap, FILE *pcap_fix) {\n  struct global_hdr_s global_hdr;\t\t/* global header data */\n\n  /* we use a buffer to cache 1mb of writing... this way writing is faster and\n     we can read and write the file at the same time */\n  char *writebuffer;\n  off_t writepos = 0;\n\n  off_t bytes;\t\t\t\t\t/* read/written bytes counter */\n  off_t filesize;\t\t\t        /* filesize of input file in bytes */\n  unsigned short hdr_integ;\t\t\t/* integrity counter of global header */\n  int res;\t\t\t\t\t/* return code */\n\n  /* init write buffer */\n  writebuffer = malloc(1024000);\n\n  /* get size of input file */\n  fseeko(pcap, 0, SEEK_END);\n  filesize = ftello(pcap);\n  fseeko(pcap, 0, SEEK_SET);\n\n  /* BEGIN GLOBAL HEADER CHECK */\n\n  /* check space of pcap global header */\n  if (filesize < (off_t)sizeof(global_hdr)) {\n    printf(\"[-] File is too small to read pcap global header.\\n\");\n    free(writebuffer);\n    return(-2);\n  }\n\n  printf(\"[*] Analyzing Global Header...\\n\");\n  bytes = fread(&global_hdr, sizeof(global_hdr), 1, pcap);\t/* read first bytes of input file into struct */\n  if (bytes != 1) {\n    free(writebuffer);\n    return -3;\n  }\n\n  /* init integrity counter */\n  hdr_integ = 0;\n\n  /* check for pcap's magic bytes () */\n  if (global_hdr.magic_number == PCAP_MAGIC) {\n    /* we got a classic pcap file (non swapped) */\n    if (verbose) printf(\"[+] Magic number: 0x%x\\n\", global_hdr.magic_number);\n  } else if (global_hdr.magic_number == htonl(PCAP_MAGIC)) {\n    /* we got a classic pcap file (swapped) */\n    if (verbose) printf(\"[+] Magic number: 0x%x (SWAPPED)\\n\", global_hdr.magic_number);\n    swapped = 1;\n  } else if (global_hdr.magic_number == PCAP_NSEC_MAGIC) {\n    /* we got a classic pcap file that uses nanoseconds (non swapped) */\n    if (verbose) printf(\"[+] Magic number: 0x%x (NANOSECONDS)\\n\", global_hdr.magic_number);\n    nanoseconds = 1;\n  } else if (global_hdr.magic_number == htonl(PCAP_NSEC_MAGIC)) {\n    /* we got a classic pcap file that uses nanoseconds (swapped) */\n    if (verbose) printf(\"[+] Magic number: 0x%x (SWAPPED - NANOSECONDS)\\n\", global_hdr.magic_number);\n    swapped = 1;\n    nanoseconds = 1;\n  } else {\n    /* we are not able to determine the pcap magic */\n    hdr_integ++;\n    if (verbose) printf(\"[-] Magic number: 0x%x\\n\", global_hdr.magic_number);\n\n    /* assume input file is a classic pcap file (NO nanoseconds, NOT swapped) */\n    global_hdr.magic_number = PCAP_MAGIC;\n  }\n\n  /* check for major version number (2) */\n  if (conshort(global_hdr.version_major) == 2) {\t/* current major version is 2 */\n    if (verbose) printf(\"[+] Major version number: %hu\\n\", conshort(global_hdr.version_major));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Major version number: %hu\\n\", conshort(global_hdr.version_major));\n    global_hdr.version_major = conshort(2);\n  }\n\n  /* check for minor version number */\n  if (conshort(global_hdr.version_minor) == 4) {\t/* current minor version is 4 */\n    if (verbose) printf(\"[+] Minor version number: %hu\\n\", conshort(global_hdr.version_minor));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Minor version number: %hu\\n\", conshort(global_hdr.version_minor));\n    global_hdr.version_minor = conshort(4);\n  }\n\n  /* check for GTM to local correction */\n  if (conshort(global_hdr.thiszone) == 0) {\t/* in practise time stamps are always in GTM, so the correction is always zero */\n    if (verbose) printf(\"[+] GTM to local correction: %d\\n\", conint(global_hdr.thiszone));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] GTM to local correction: %d\\n\", conint(global_hdr.thiszone));\n    global_hdr.thiszone = conint(0);\n  }\n\n  /* check for accuracy of timestamps */\n  if (conint(global_hdr.sigfigs) == 0) {\t/* all capture tools set this to zero */\n    if (verbose) printf(\"[+] Accuracy of timestamps: %u\\n\", conint(global_hdr.sigfigs));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Accuracy of timestamps: %u\\n\", conint(global_hdr.sigfigs));\n    global_hdr.sigfigs = conint(0);\n  }\n\n  /* check for max packet length */\n  if ((conint(global_hdr.snaplen) > 0) && (conint(global_hdr.snaplen) <= PCAP_MAX_SNAPLEN)) {\t/* typically 262144 nowadays */\n    if (verbose) printf(\"[+] Max packet length: %u\\n\", conint(global_hdr.snaplen));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Max packet length: %u\\n\", conint(global_hdr.snaplen));\n    global_hdr.snaplen = conint(PCAP_MAX_SNAPLEN);\n  }\n\n  /* check for data link type (http://www.tcpdump.org/linktypes.html) */\n  if (conint(global_hdr.network) <= 301) {\t/* data link types are <= 301 */\n    if (verbose) printf(\"[+] Data link type: %u\\n\", conint(global_hdr.network));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Data link type: %u\\n\", conint(global_hdr.network));\n    /* if data link type is corrupt, we set it to ethernet (user supplied param will be processed afterwards) */\n    global_hdr.network = conint(1);\n  }\n\n  /* does the user provides a self-supplied data link type? if yes... change global header */\n  if (data_link_type != -1) {\n    printf(\"[+] Changing data link type to %d.\\n\", data_link_type);\n    global_hdr.network = conint(data_link_type);\n    hdr_integ++;\n  }\n\n  /* evaluate the integrity of the global header */\n  if (hdr_integ == 0) { /* no field has been corrupted? --> header is intact */\n    printf(\"[+] The global pcap header seems to be fine!\\n\");\n  } else if (hdr_integ >= 4) { /* there have been five or more (of seven) corrupted fields? --> header is missing */\n    printf(\"[-] The global pcap header seems to be missing ==> CORRECTED!\\n\");\n    /* we need to set the file pointer to the beginning of the file, because\n     * further packet search depends on this position and without a global\n     * header the first packet might begin there */\n    fseeko(pcap, 0, SEEK_SET);\n\n    /* set important header values to defaults */\n    global_hdr.snaplen = conint(PCAP_MAX_SNAPLEN);\n\n    if (data_link_type != -1) {\n      global_hdr.network = conint(data_link_type);\n    } else {\n      global_hdr.network = conint(1);\n    }\n  } else { /* there have been corrupted fields (less than five) --> header is corrupted */\n    printf(\"[-] The global pcap header seems to be corrupt! ==> CORRECTED\\n\");\n  }\n\n  /* write the (maybe changed) global header to output file */\n  memcpy(writebuffer, &global_hdr, sizeof(global_hdr));\n  writepos += sizeof(global_hdr);\n\n  /* END OF GLOBAL HEADER CHECK */\n\n  /* start checking packets now */\n  res = fix_pcap_packets(pcap, pcap_fix, filesize, global_hdr, hdr_integ, &writebuffer, writepos);\n  free(writebuffer);\n  return(res);\n}\n\n/*\n * Function:  fix_pcap_packets\n * ---------------------------\n * tries to fix pcap packets inside a pcap file\n *\n * pcap:        file pointer to input file\n * pcap_fix:    file pointer to output file\n * filesize:    input file size in bytes\n * global_hdr:  global header struct\n * hdr_integ:   global header integrity counter\n * writebuffer: buffer to write pcap packets into\n * writepos:    position in buffer to write next packet to\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap_packets(FILE *pcap, FILE *pcap_fix, off_t filesize, struct global_hdr_s global_hdr, unsigned short hdr_integ, char **writebuffer, off_t writepos) {\n  struct packet_hdr_s packet_hdr;\t\t/* packet header data */\n  struct packet_hdr_s next_packet_hdr;\t\t/* next packet header data to look forward */\n  char hdrbuffer[sizeof(packet_hdr)*2];\t\t/* the buffer that will be used to find a proper packet */\n  char *tmpbuf;\t\t\t\t\t/* temp write buffer */\n\n  char buffer[PCAP_MAX_SNAPLEN];\t\t/* the packet body */\n  off_t bytes;\t\t\t\t\t/* read/written bytes counter */\n\n  unsigned int count;\t\t\t\t/* packet counter */\n  unsigned int step = 1;\t\t\t/* step counter for progress bar */\n\n  off_t pos = 0;\t\t\t\t/* position of current packet header */\n  off_t nextpos = 0;\t\t        \t/* possible position of next packets header */\n\n  unsigned int last_correct_ts_sec = 0;\t\t/* timestamp of the last proper packet found (seconds) */\n  unsigned int last_correct_ts_usec = 0;\t/* timestamp of the last proper packet found (microseconds or nanoseconds) */\n\n  int ascii = 0;\t\t\t\t/* ascii counter for possible ascii-corrupted packets */\n  int corrupted = 0;\t\t\t\t/* corrupted packet counter for final output */\n\n  int res;\t\t\t\t\t/* the result of the header check == the offset of body shifting */\n\n  /* BEGIN PACKET CHECK */\n\n  printf(\"[*] Analyzing packets...\\n\");\n\n  /* this loop iterates the packets from top till down by checking the\n   * pcap packet headers on plausibility. if any packet header has got\n   * implausible information the packet will be handled as corrupted\n   * and pcapfix will brute force the next packet. if the packet header\n   * look plausible, pcapfix will check if the next packet is aligned and\n   * if not check for overlapping packets.\n   */\n\n  /* get current file pointer position */\n  pos = ftello(pcap);\n\n  /* loop the pcap files packets until pos has reacher end of file */\n  for (count=1; pos < filesize; count++) {\n\n    /* we only want the progress bar to be printed in non-verbose mode */\n    if ((verbose == 0) && (5*(float)pos/(float)filesize > step)) {\n      print_progress(pos, filesize);\n      step++;\n    }\n\n    /* check if a pcap packet header would fit into the file */\n    if (pos + (off_t)sizeof(packet_hdr) > filesize) {\n      printf(\"[-] Not enough bytes left in file ==> SKIPPING %\" FMT_OFF_T \" bytes.\\n\", filesize-pos);\n      corrupted++;\n\n      /* at least one packet has been found?? */\n      if (count == 1) {\n        printf(\"[-] No packet has been found!\\n\");\n        return(-2);\n      }\n\n      /* end of file reached */\n      pos = filesize;\n      break;\n    }\n\n    /* read the next packet header */\n    memset(hdrbuffer, 0, sizeof(hdrbuffer));\n    bytes = fread(hdrbuffer, sizeof(packet_hdr), 1, pcap);\n    if (bytes != 1) return -3;\n\n    /* read overlapping packet data into buffer if available */\n    bytes = fread(hdrbuffer+sizeof(packet_hdr), sizeof(packet_hdr), 1, pcap);\n    if (bytes != 1 && verbose >= 2) printf(\"[*] Skipping to read overlapping header data due to EOF\\n\");\n\n    /* check if the packet header looks proper */\n    res = check_header(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &packet_hdr);\n    if (res != -1) {\n\n      /* realign packet body (based on possible-ascii corrupted pcap header) */\n      pos += res;\n      fseeko(pcap, pos+sizeof(packet_hdr), SEEK_SET);\n\n      /* try to read the packet body AND check if there are still at least 16 bytes left for the next pcap packet header */\n      if ((fread(&buffer, conint(packet_hdr.incl_len), 1, pcap) == 0) || ((filesize-(pos+sizeof(packet_hdr)+conint(packet_hdr.incl_len)) > 0) && (filesize-(pos+sizeof(packet_hdr)+conint(packet_hdr.incl_len)) < sizeof(packet_hdr)))) {\n        /* fread returned an error (EOL while read the body) or the file is not large enough for the next pcap packet header (16bytes) */\n        /* thou the last packet has been cut of */\n\n        if (verbose >= 1) printf(\"[-] LAST PACKET MISMATCH (%u | %u | %u | %u)\\n\", conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n        /* correct the packets included length field to match the end of file */\n        packet_hdr.incl_len = conint(filesize-pos-sizeof(packet_hdr));\n\n        /* the original length must not be smaller than the included length */\n        if (conint(packet_hdr.incl_len) > conint(packet_hdr.orig_len)) packet_hdr.orig_len = packet_hdr.incl_len;\n\n        /* the included length must not be greater than filesize */\n        if (conint(packet_hdr.incl_len) > filesize-pos) packet_hdr.incl_len = filesize-pos;\n\n        /* print out information */\n        printf(\"[+] CORRECTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n        corrupted++;\n      }\n\n      /* OVERLAPPING DETECTION */\n      /* we do ONLY scan for overlapping if next packet is NOT aligned */\n\n      /* read next packet header */\n      bytes = fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap);\n\n      /* check if next packets header looks proper */\n      if (check_header(hdrbuffer, sizeof(hdrbuffer), conint(packet_hdr.ts_sec), &global_hdr, &next_packet_hdr) == -1) {\n\n        /* the next packets header is corrupted thou we are going to scan through the prior packets body to look for an overlapped packet header\n         * also look inside the next packets header + 16bytes of packet body, because we need to know HERE\n         * do not leave the loop if the first packet has not been found yet AND deep scan mode is activated */\n        for (nextpos=pos+(off_t)sizeof(packet_hdr)+1; (nextpos < pos+(off_t)sizeof(packet_hdr)+conint(packet_hdr.incl_len)+2*(off_t)sizeof(packet_hdr)) || (count == 1 && deep_scan == 1); nextpos++) {\n\n          /* read the possible next packets header */\n          fseeko(pcap, nextpos, SEEK_SET);\n          bytes = fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap);\n\n          /* check read success */\n          if (bytes == 0) break;\n\n          /* heavy verbose output :-) */\n          if (verbose >= 2) printf(\"[*] Trying Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n          /* check the header for plausibility */\n          res = check_header(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &next_packet_hdr);\n          if (res != -1) {\n\n            /* we found a proper header inside the packets body! */\n            if (verbose >= 1) printf(\"[-] FOUND OVERLAPPING data of Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n            /* correct the prior packets length information fields to align the overlapped packet */\n            packet_hdr.incl_len = conint(nextpos-(pos+sizeof(packet_hdr))+res);\t/* also include ascii corruption offset (res) */\n            packet_hdr.orig_len = packet_hdr.incl_len;\n\n            /* time correction for the FIRST packet only */\n            if (count == 1) {\n              if (conint(next_packet_hdr.ts_usec) > 0) {\n                /* next packets usec is > 0 ===> first packet will get same timestamp and usec - 1 */\n                packet_hdr.ts_sec = next_packet_hdr.ts_sec;\n                packet_hdr.ts_usec = conint(conint(next_packet_hdr.ts_usec)-1);\n              } else if(conint(next_packet_hdr.ts_sec) > 0) {\n                /* else: next packets timestamp i > 0 ===> firt packet will get timestamp -1 and maximum usec */\n                packet_hdr.ts_sec = conint(conint(next_packet_hdr.ts_sec)-1);\n                packet_hdr.ts_usec = conint(999999);\n              } else {\n                /* else: (next packets sec and usec are zero), this packet will get zero times as well */\n                packet_hdr.ts_sec = conint(0);\n                packet_hdr.ts_usec = conint(0);\n              }\n            }\n\n            /* print out information */\n            printf(\"[+] CORRECTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n            corrupted++;\n\n            /* overlapping seems to be a result of ascii-transferred pcap files via FTP */\n            ascii++;\n\n            break;\n          }\n        }\n      }\n\n      /* reset file fointer to next packet */\n      fseeko(pcap, pos+sizeof(packet_hdr)+conint(packet_hdr.incl_len), SEEK_SET);\n\n      /* we found a correct packet (and aligned it maybe) */\n      if (verbose >= 1) printf(\"[+] Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n      /* write this packet */\n\n      // check if there is enough space in buffer\n      off_t totalsize = sizeof(packet_hdr) + conint(packet_hdr.incl_len);\n      if (writepos+totalsize > 1024000) {\n        bytes = fwrite(*writebuffer, writepos, 1, pcap_fix);\n        writepos = 0;\n      }\n\n      /* check if writebuffer is large enough */\n      if (sizeof(packet_hdr) + conint(packet_hdr.incl_len) > 1024000) {\n        tmpbuf = malloc(sizeof(packet_hdr) + conint(packet_hdr.incl_len));\n        memcpy(tmpbuf, *writebuffer, 1024000);\n        free(*writebuffer);\n        writebuffer = &tmpbuf;\n      }\n\n      // put new bytes into write buffer\n      memcpy(*writebuffer+writepos, &packet_hdr, sizeof(packet_hdr));\n      writepos += sizeof(packet_hdr);\n      memcpy(*writebuffer+writepos, buffer, conint(packet_hdr.incl_len));\n      writepos += conint(packet_hdr.incl_len);\n\n      /* remember that this packets timestamp to evaluate futher timestamps */\n      last_correct_ts_sec = conint(packet_hdr.ts_sec);\n      last_correct_ts_usec = conint(packet_hdr.ts_usec);\n\n    } else {\n\n      /* PACKET IS CORRUPT */\n\n      if (verbose >= 1) printf(\"[-] CORRUPTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n      /* scan from the current position to the maximum packet size and look for a next proper packet header to align the corrupted packet\n       * also do not leave the loop if the first packet has not been found yet AND deep scan mode is activated */\n      for (nextpos=pos+(off_t)sizeof(packet_hdr)+1; (nextpos <= pos+(off_t)sizeof(packet_hdr)+PCAP_MAX_SNAPLEN) || (count == 1 && deep_scan == 1); nextpos++) {\n\n        /* read the possible next packets header */\n        fseeko(pcap, nextpos, SEEK_SET);\n        if (fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap) == 0) {\n\n          /* did we read over EOF AND havent found the first packet yet? then we need to abort! */\n          if ((count == 1) && (deep_scan == 1)) {\n\n            /* abort scan */\n            pos = 0;\n            corrupted = -1;\n            break;\n          }\n\n          printf(\"[*] End of file reached. Aligning last packet.\\n\");\n\n          /* check last packet for plausiblilty */\n          res = check_header(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &packet_hdr);\n          if (res != 0) {\n            printf(\"[-] Cannot align last packet, because it is broken.\\n\");\n            corrupted++;\n            count--;\n            break;\n          }\n\n          /* check passed */\n\n          /* align the last packet to match EOF */\n          packet_hdr.incl_len = conint(filesize-(pos+sizeof(packet_hdr)));\n          packet_hdr.orig_len = packet_hdr.incl_len;\n\n          /* if the is the first packet, we need to set timestamps to zero */\n          if (count == 1) {\n            packet_hdr.ts_sec = conint(0);\n            packet_hdr.ts_usec = conint(0);\n          } else {\t/* else take the last correct timestamp and usec plus one */\n            packet_hdr.ts_sec = conint(last_correct_ts_sec);\n            packet_hdr.ts_usec = conint(last_correct_ts_usec+1);\n          }\n\n          /* read the packets body (size based on the just found next packets position) */\n          fseeko(pcap, pos+sizeof(packet_hdr), SEEK_SET);\n          bytes = fread(&buffer, conint(packet_hdr.incl_len), 1, pcap);\n\n          // check if there is enough space in buffer\n          int totalsize = sizeof(packet_hdr) + conint(packet_hdr.incl_len);\n          if (writepos+totalsize > 1024000) {\n            bytes = fwrite(*writebuffer, writepos, 1, pcap_fix);\n            writepos = 0;\n          }\n\n          // put new bytes into write buffer\n          memcpy(*writebuffer+writepos, &packet_hdr, sizeof(packet_hdr));\n          writepos += sizeof(packet_hdr);\n          memcpy(*writebuffer+writepos, buffer, conint(packet_hdr.incl_len));\n          writepos += conint(packet_hdr.incl_len);\n\n          /* remember that this packets timestamp to evaluate futher timestamps */\n          last_correct_ts_sec = packet_hdr.ts_sec;\n          last_correct_ts_usec = packet_hdr.ts_usec;\n\n          /* print out information */\n          printf(\"[+] CORRECTED LAST Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n          corrupted++;\n\n          break;\n        }\n\n        /* shall we abort the whole scan?? */\n        if (corrupted == -1) break;\n\n        /* heavy verbose output :-) */\n        if (verbose >= 2) printf(\"[*] Trying Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n        /* check if next packets header looks proper */\n        res = check_header(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &next_packet_hdr);\n        if (res != -1) {\n\n          /* if we found a packet that is below the top MAX_SNAPLEN bytes (deep scan) we cut it off and take the second packet as first one */\n          if ((nextpos-(pos+sizeof(packet_hdr)) > PCAP_MAX_SNAPLEN) && (count == 1) && (deep_scan == 1)) {\n\n            if (verbose >= 1) printf(\"[+] (DEEP SCAN) FOUND FIRST Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n            /* set the filepoint to the top of the first packet to be read in next loop iteration */\n            fseeko(pcap, nextpos, SEEK_SET);\n\n            /* correct counter due to deep scan */\n            count--;\n\n          } else { /* found next packet (NO deep scan mode) */\n\n            /* we found the NEXT packets header, now we are able to align the corrupted packet */\n            if (verbose >= 1) printf(\"[+] FOUND NEXT Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n            /* correct the corrupted pcap packet header to match the just found next packet header */\n            packet_hdr.incl_len = conint(nextpos-(pos+sizeof(packet_hdr)));\n            packet_hdr.orig_len = packet_hdr.incl_len;\n\n            if (count == 1) { /* time correction for the FIRST packet */\n              if (conint(next_packet_hdr.ts_usec) > 0) {\n                /* next packets usec is > 0 ===> first packet will get same timestamp and usec - 1 */\n                packet_hdr.ts_sec = next_packet_hdr.ts_sec;\n                packet_hdr.ts_usec = conint(conint(next_packet_hdr.ts_usec)-1);\n              } else if(conint(next_packet_hdr.ts_sec) > 0) {\n                /* else: next packets timestamp i > 0 ===> firt packet will get timestamp -1 and maximum usec */\n                packet_hdr.ts_sec = conint(conint(next_packet_hdr.ts_sec)-1);\n                packet_hdr.ts_usec = conint(999999);\n              } else {\n                /* else: (next packets sec and usec are zero), this packet will get zero times as well */\n                packet_hdr.ts_sec = conint(0);\n                packet_hdr.ts_usec = conint(0);\n              }\n            } else { /* ALL packets except the first one will use the last correct packets timestamps */\n              packet_hdr.ts_sec = conint(last_correct_ts_sec);\n              packet_hdr.ts_usec = conint(last_correct_ts_usec+1);\n            }\n\n            /* read the packets body (size based on the just found next packets position) */\n            fseeko(pcap, pos+sizeof(packet_hdr), SEEK_SET);\n            bytes = fread(&buffer, conint(packet_hdr.incl_len), 1, pcap);\n\n            /* final check resulting packet for plausibility */\n            res = is_plausible(global_hdr, packet_hdr, last_correct_ts_sec);\n            if (res == 0) {\n\n              // check if there is enough space in buffer\n              int totalsize = sizeof(packet_hdr) + conint(packet_hdr.incl_len);\n              if (writepos+totalsize > 1024000) {\n                bytes = fwrite(*writebuffer, writepos, 1, pcap_fix);\n                writepos = 0;\n              }\n\n              // put new bytes into write buffer\n              memcpy(*writebuffer+writepos, &packet_hdr, sizeof(packet_hdr));\n              writepos += sizeof(packet_hdr);\n              memcpy(*writebuffer+writepos, buffer, conint(packet_hdr.incl_len));\n              writepos += conint(packet_hdr.incl_len);\n\n              /* remember that this packets timestamp to evaluate futher timestamps */\n              last_correct_ts_sec = conint(packet_hdr.ts_sec);\n              last_correct_ts_usec = conint(packet_hdr.ts_usec);\n\n              /* print out information */\n              printf(\"[+] CORRECTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n            } else {\n              /* prior packet is invalid */\n              printf(\"[-] Packet #%u at position %\" FMT_OFF_T \" is invalid ==> SKIPPING.\\n\", count, pos);\n            }\n\n          }\n\n          /* increase corruption counter */\n          corrupted++;\n\n          /* leave the next packet search loop */\n          break;\n        }\n\n      }\n\n      /* shall we abort the whole scan (due to deep scan did not succeed at all) */\n      if (corrupted == -1) break;\n\n      /* did the counter exceed the maximum packet size? */\n      if ((count == 1 && deep_scan == 0) && (nextpos > pos+(off_t)sizeof(packet_hdr)+PCAP_MAX_SNAPLEN)) {\n\n        /* PACKET COULD NOT BE REPAIRED! */\n\n        if (verbose >= 1) printf(\"[-] Cannot align corrupted packet! \\n\");\n        break;\n      }\n\n      /* maximum search range reached? -> skip packet and keep on searching */\n      if (deep_scan == 0 && (nextpos > pos+(off_t)sizeof(packet_hdr)+PCAP_MAX_SNAPLEN)) {\n        if (verbose >= 1) printf(\"[-] No next packet found within max packet range --> SKIPPING!\\n\");\n\n        /* reset counter because no packet found */\n        count--;\n      }\n\n    }\n\n    /* get current file pointer position to start next loop iteration */\n    pos = ftello(pcap);\n\n  }\n\n  // write remaining data into buffer\n  bytes = fwrite(*writebuffer, writepos, 1, pcap_fix);\n  writepos = 0;\n\n  if (verbose == 0) { print_progress(pos, filesize); }\n\n  /* did we reach the end of pcap file? */\n  if (pos != filesize) { /* no ==> data missing == FAILED */\n    printf(\"[-] Reached EOF without finding more packets!\\n\");\n    corrupted = -1;\t/* the file could not be repaired */\n  }\n\n  /* END PACKET CHECK */\n\n  /* EVALUATE RESULT */\n\n  if ((hdr_integ == 0) && (corrupted == 0)) { /* check allover failure / integrity count and corrupted counter */\n\n   /* no errors (header + packets correct) */\n   return(0);\n\n  } else if (corrupted == -1) {\t/* check vor very high packet failure value ==> no recovery possible */\n\n    /* file could NOT be repaired */\n\n    if (count == 1) {\n\n      /* even the first packet was corrupted and no other packet could be found */\n      return(-1);\n\n    } else {\n\n      /* the first packet was intact, but recovery is not possible nevertheless */\n      return(-2);\n\n    }\n\n  } else {\n    /* check if we found at least one packet */\n    if (count == 1) {\n      /* even the first packet was corrupted and no other packet could be found */\n      return(-1);\n    }\n\n    /* file has been successfully repaired (corruption fixed) */\n\n    printf(\"[*] Wrote %u packets to file.\\n\", count-1);\n\n    /* are there any packets that might have been transferred in ascii mode? */\n    if (ascii) {\n      printf(\"[!] This corruption seems to be a result of an ascii-mode transferred pcap file via FTP.\\n\");\n      printf(\"[!] The pcap structure of those files can be repaired, but the data inside might still be corrupted!\\n\");\n    }\n\n    return(hdr_integ+corrupted);\n\n  }\n\n}\n"
  },
  {
    "path": "pcap.h",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#ifndef PF_PCAP\n#define PF_PCAP\n\n#define PCAP_MAGIC 0xa1b2c3d4\t\t\t/* the magic of the pcap global header (non swapped) */\n#define PCAP_MAGIC_SWAPPED 0xd4c3b2a1\t\t/* the magic of the pcap global header (non swapped) */\n#define PCAPNG_MAGIC 0x0a0d0d0a\t\t\t/* the magic of the pcap global header (non swapped) */\n#define PCAP_NSEC_MAGIC 0xa1b23c4d\t\t/* the magic of the pcap global header (nanoseconds - non swapped) */\n#define PCAP_MAX_SNAPLEN 262144\t\t\t/* the maximum snap length, should be 256K instead of 64K nowadays */\n\n/* Global header (http://v2.nat32.com/pcap.htm) */\nstruct global_hdr_s {\n  u_int32_t magic_number;   /* magic number */\n  u_int16_t version_major;  /* major version number */\n  u_int16_t version_minor;  /* minor version number */\n  int32_t thiszone;       \t/* GMT to local correction */\n  u_int32_t sigfigs;        /* accuracy of timestamps */\n  u_int32_t snaplen;        /* max length of captured packets, in octets */\n  u_int32_t network;        /* data link type */\n};\n\n/* Packet header (http://v2.nat32.com/pcap.htm) */\nstruct packet_hdr_s {\n  u_int32_t ts_sec;         /* timestamp seconds */\n  u_int32_t ts_usec;        /* timestamp microseconds */\n  u_int32_t incl_len;       /* number of octets of packet saved in file */\n  u_int32_t orig_len;       /* actual length of packet */\n};\n\n/*\n * Function:  is_plausible\n * -----------------------\n * check if the pcap packet header could be a plausible one by satisfying those conditions:\n * - packet size >= 16 bytes AND <= MAX_SNAPLEN bytes (included length AND original length) (conditions 1,2,3,4)\n * - included length <= original lenth (condition 5)\n * - packet timestamp is NOT older OR younger than the prior packets timestamp -+ one day (conditions 6,7)\n * - usec (microseconds) field <= 1000000 (conditions 8)\n * - usec (nanoseconds) field <= 1000000000 (conditions 9)\n *\n * global_hdr: the filled pcap header to check for snaplen\n * hdr:        the filled packet header struct to check for plausibility\n * prior_ts:   the prior packets timestamp (seconds) to check for time relation (condition 6,7)\n *\n * returns:  0   success\n *          -X   error (condition X failed)\n *\n */\nint is_plausible(struct global_hdr_s global_hdr, struct packet_hdr_s hdr, unsigned int prior_ts);\n\n/*\n * Function:  check_header\n * -----------------------\n * this function takes a buffer and brute forces some possible ascii-corrupted bytes versus plausibility checks\n *\n * buffer:     the buffer that might contain the possible pcap packet header\n * size:       the size of the buffer (double pcap packet header size is a good choice)\n * priot_ts:   the prior packets timestamp (to check for plausibility)\n * global_hdr: the pointer to the pcap buffer\n * hdr:        the pointer to the packet header buffer (we use this to return the repaired header)\n *\n * returns: >=0   success (return value contains number of ascii corrupted bytes in hdr (we need this data to align the beginning of the packet body later)\n *           -1   error (no valid pcap header found inside buffer)\n *\n */\nint check_header(char *buffer, unsigned int size, unsigned int prior_ts, struct global_hdr_s *global_hdr, struct packet_hdr_s *hdr);\n\n/*\n * Function:  fix_pcap\n * -------------------\n * tries to fix a classic pcap file\n *\n * pcap:      file pointer to input file\n * pcap_fix:  file pointer to output file\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap(FILE *pcap, FILE *pcap_fix);\n\n/*\n * Function:  fix_pcap_packets\n * ---------------------------\n * tries to fix pcap packets inside a pcap file\n *\n * pcap:        file pointer to input file\n * pcap_fix:    file pointer to output file\n * filesize:    input file size in bytes\n * global_hdr:  global header struct\n * hdr_integ:   global header integrity counter\n * writebuffer: buffer to write pcap packets into\n * writepos:    position in buffer to write next packet to\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap_packets(FILE *pcap, FILE *pcap_fix, off_t filesize, struct global_hdr_s global_hdr, unsigned short hdr_integ, char **writebuffer, off_t writepos);\n\n#endif\n"
  },
  {
    "path": "pcap_kuznet.c",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#include \"pcapfix.h\"\n#include \"pcap_kuznet.h\"\n\n/*\n * Function:  is_plausible\n * -----------------------\n * check if the pcap packet header could be a plausible one by satisfying those conditions:\n * - packet size >= 16 bytes AND <= MAX_SNAPLEN bytes (included length AND original length) (conditions 1,2,3,4,5)\n * - included length <= original lenth (conditions 6,7,8,9)\n * - packet timestamp is NOT older OR younger than the prior packets timestamp -+ one day (conditions 10,11,12)\n * - usec (microseconds) field <= 1000000 (conditions 13)\n * - usec (nanoseconds) field <= 1000000000 (conditions 14)\n *\n * global_hdr: the filled pcap header struct to check for snaplen\n * hdr:        the filled packet header struct to check for plausibility\n * prior_ts:   the prior packets timestamp (seconds) to check for time relation (condition 6,7)\n *\n * returns:  0   success\n *          -X   error (condition X failed)\n *\n */\nint is_plausible_kuznetzov(struct global_hdr_s global_hdr, struct packet_hdr_kuznet_s hdr, unsigned int prior_ts) {\n  /* check for minimum packet size\n   * minimum packet size should be 16, but in some cases, e.g. local wlan capture, packet might\n   * even be smaller --> decreased minimum size to 10 */\n  if (conint(hdr.incl_len) < 10) return(-1);\n  if (conint(hdr.orig_len) < 10) return(-2);\n\n  /* check packet limit with header field and max snaplen\n     in soft mode (and dlt 119) the packet detection accepts a wider range */\n  if (soft_mode || global_hdr.network == 119) {\n    /* in soft mode, global pcap snap length is ignored, instead MAX snaplen is used */\n\n    /* strange behavior for wlan: in some cases incl length seems to differ\n       not following the configured max snap length; this leads to dropping\n       valid wlan packets -> use soft mode for DLT 119 */\n    if (conint(hdr.incl_len) > PCAP_MAX_SNAPLEN) return(-3);\n  } else {\n    /* in hard mode (and not dlt 119), global pcap snap length is the limit in plausibility checks */\n    if (conint(hdr.incl_len) > conint(global_hdr.snaplen)) return(-4);\n  }\n  /* orig length should not be greater than pcap max snaplen */\n  if (conint(hdr.orig_len) > PCAP_MAX_SNAPLEN) return(-5);\n\n  /* if the packet original size is larger than the included length, then\n     the included length should be limited by the files snap length */\n  if (conint(hdr.orig_len) > conint(hdr.incl_len)) {\n    /* check for dlt 119 == wlan */\n    if (global_hdr.network == 119) {\n      /* strange behavior for wlan: in some cases incl length seems to differ\n         not following the configured max snap length; this leads to dropping\n         valid wlan packets -> ignore this check for DLT 119 */\n    } else {\n      if (conint(hdr.incl_len) != conint(global_hdr.snaplen)) return(-7);\n    }\n  }\n\n  /* the included length CAN NOT be larger than the original length */\n  /* check for LINKTYPE_LINUX_SLL (linux cooked) */\n  if (global_hdr.network == 113) {\n    /* linux cooked headers are appended to packet length, but not to orig length\n       so we need to remove it from incl_len before checking */\n    if (conint(hdr.incl_len)-16 > conint(hdr.orig_len)) return(-8);\n  } else if (conint(hdr.incl_len) > conint(hdr.orig_len)) return(-9);\n\n  /* check packet times (older) */\n  if (soft_mode) {\n    /* in soft mode, there is no limit for older packets */\n  } else {\n    /* in hard mode, packet must not be older than one day (related to prior packet) */\n    if ((prior_ts != 0) && (conint(hdr.ts_sec) > (prior_ts+86400))) return(-10);\n  }\n\n  /* check packet times (younger) */\n  if (soft_mode) {\n    /* in soft mode, packet must not be younger than one day (related to prior packet) */\n    if ((prior_ts >= 86400) && (conint(hdr.ts_sec) < (prior_ts-86400))) return(-11);\n  } else {\n    /* in hard mode, packets must not be younger than prior packet */\n    if ((prior_ts != 0) && (conint(hdr.ts_sec) < prior_ts)) return(-12);\n  }\n\n  /* check for nano/microseconds (hard mode only) */\n  if (!soft_mode) {\n    /* in hard mode */\n    /* usec (microseconds) must <= 1000000 */\n    /* kuznetzov never uses nanoseconds */\n    if (conint(hdr.ts_usec) > 1000000) return(-13);\n  }\n\n  /* all conditions fullfilled ==> everything fine! */\n  return(0);\n}\n\n/*\n * Function:  check_header\n * -----------------------\n * this function takes a buffer and brute forces some possible ascii-corrupted bytes versus plausibility checks\n *\n * buffer:     the buffer that might contain the possible pcap packet header\n * size:       the size of the buffer (double pcap packet header size is a good choice)\n * priot_ts:   the prior packets timestamp (to check for plausibility)\n * global_hdr: the pointer to the pcap header\n * hdr:        the pointer to the packet header buffer (we use this to return the repaired header)\n *\n * returns: >=0   success (return value contains number of ascii corrupted bytes in hdr (we need this data to align the beginning of the packet body later)\n *           -1   error (no valid pcap header found inside buffer)\n *\n */\nint check_header_kuznetzov(char *buffer, unsigned int size, unsigned int prior_ts, struct global_hdr_s *global_hdr, struct packet_hdr_kuznet_s *hdr) {\n  unsigned int i; /* loop variable - first byte in buffer that could be beginning of packet */\n  int res;        /* return value */\n  char *tmp;      /* the temporary buffer that will be used for recursion */\n\n  /* does the buffer already contain a valid packet header (without any correction) ?? */\n  memcpy(hdr, buffer, sizeof(struct packet_hdr_kuznet_s));\n  res = is_plausible_kuznetzov(*global_hdr, *hdr, prior_ts);\n  if (res == 0) return(0);\n\n  if (verbose >= 2) printf(\"[-] Header plausibility check failed with error code %d\\n\", res);\n\n  /* we need to abort the recursion of there are too many possible ascii corrupted bytes at ones */\n  /* 32-25 = 7 bytes maximum in 32bytes of data! */\n  if (size <= 25) return(-1);\n\n  /* this loop will check the the buffer for occurence of 0x0D + 0x0A (UNIX to WINDOWS ascii corruption) */\n  for(i=0; i<sizeof(struct packet_hdr_kuznet_s); i++) {\n    /* is there a 0x0D 0X0A combination at this position? */\n    if (buffer[i] == 0x0D && buffer[i+1] == 0x0A) {\n\n      /* allocate memory for recursion buffer */\n      tmp = malloc(size);\n\n      /* we cut out 0x0D because this byte could have been added due to ftp ascii transfer eg */\n      memcpy(tmp, buffer, i);\n      memcpy(tmp+i, buffer+i+1, size-i-1);\n\n      /* and invoke the header again without this 0x0D byte */\n      res = check_header_kuznetzov(tmp, size-1, prior_ts, global_hdr, hdr);\n\n      /* free recursion buffer */\n      free(tmp);\n\n      /* if the check was successfull (maybe with multiple recursions) return the value added by one (body shift offset) */\n      if (res != -1) return(res+1);\n    }\n  }\n\n  /* the buffer (even after ascii corruption brute force) does not contain any valid pcap packet header */\n  return(-1);\n}\n\n/*\n * Function:  fix_pcap\n * -------------------\n * tries to fix a classic pcap file\n *\n * pcap:      file pointer to input file\n * pcap_fix:  file pointer to output file\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap_kuznetzov(FILE *pcap, FILE *pcap_fix) {\n  struct global_hdr_s global_hdr;\t\t/* global header data */\n\n  /* we use a buffer to cache 1mb of writing... this way writing is faster and\n     we can read and write the file at the same time */\n  char *writebuffer;\n  off_t writepos = 0;\n\n  off_t bytes;\t\t\t\t/* read/written bytes counter */\n  off_t filesize;\t\t\t\t/* filesize of input file in bytes */\n  unsigned short hdr_integ;\t\t\t/* integrity counter of global header */\n\n  /* init write buffer */\n  writebuffer = malloc(1024000);\n\n  /* get size of input file */\n  fseeko(pcap, 0, SEEK_END);\n  filesize = ftello(pcap);\n  fseeko(pcap, 0, SEEK_SET);\n\n  /* BEGIN GLOBAL HEADER CHECK */\n\n  /* check space of pcap global header */\n  if (filesize < (off_t)sizeof(global_hdr)) {\n    printf(\"[-] File is too small to read pcap global header.\\n\");\n    return(-2);\n  }\n\n  printf(\"[*] Analyzing Global Header...\\n\");\n  bytes = fread(&global_hdr, sizeof(global_hdr), 1, pcap);\t/* read first bytes of input file into struct */\n  if (bytes != 1) return -3;\n\n  /* init integrity counter */\n  hdr_integ = 0;\n\n  /* check for pcap's magic bytes () */\n  if (global_hdr.magic_number == PCAP_EXT_MAGIC) {\n    /* we got a KUZNETZOV extended tcpdump magic (non swapped) */\n    if (verbose) printf(\"[+] Magic number: 0x%x (KUZNETZOV)\\n\", global_hdr.magic_number);\n  } else if (global_hdr.magic_number == htonl(PCAP_EXT_MAGIC)) {\n    /* we got a KUZNETZOV extended tcpdump magic (swapped) */\n    if (verbose) printf(\"[+] Magic number: 0x%x (KUZNETZOV - SWAPPED)\\n\", global_hdr.magic_number);\n    swapped = 1;\n  } else {\n    /* we are not able to determine the pcap magic */\n    hdr_integ++;\n    if (verbose) printf(\"[-] Magic number: 0x%x\\n\", global_hdr.magic_number);\n\n    /* in this special case of kuznetzov, we do not try to assume it is a pcap file */\n    return(-1);\n  }\n\n  /* check for major version number (2) */\n  if (conshort(global_hdr.version_major) == 2) {\t/* current major version is 2 */\n    if (verbose) printf(\"[+] Major version number: %hu\\n\", conshort(global_hdr.version_major));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Major version number: %hu\\n\", conshort(global_hdr.version_major));\n    global_hdr.version_major = conshort(2);\n  }\n\n  /* check for minor version number */\n  if (conshort(global_hdr.version_minor) == 4) {\t/* current minor version is 4 */\n    if (verbose) printf(\"[+] Minor version number: %hu\\n\", conshort(global_hdr.version_minor));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Minor version number: %hu\\n\", conshort(global_hdr.version_minor));\n    global_hdr.version_minor = conshort(4);\n  }\n\n  /* check for GTM to local correction */\n  if (conshort(global_hdr.thiszone) == 0) {\t/* in practise time stamps are always in GTM, so the correction is always zero */\n    if (verbose) printf(\"[+] GTM to local correction: %d\\n\", conint(global_hdr.thiszone));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] GTM to local correction: %d\\n\", conint(global_hdr.thiszone));\n    global_hdr.thiszone = conint(0);\n  }\n\n  /* check for accuracy of timestamps */\n  if (conint(global_hdr.sigfigs) == 0) {\t/* all capture tools set this to zero */\n    if (verbose) printf(\"[+] Accuracy of timestamps: %u\\n\", conint(global_hdr.sigfigs));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Accuracy of timestamps: %u\\n\", conint(global_hdr.sigfigs));\n    global_hdr.sigfigs = conint(0);\n  }\n\n  /* check for max packet length */\n  if ((conint(global_hdr.snaplen) > 0) && (conint(global_hdr.snaplen) <= PCAP_MAX_SNAPLEN)) {\t/* typically 262144 nowadays */\n    if (verbose) printf(\"[+] Max packet length: %u\\n\", conint(global_hdr.snaplen));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Max packet length: %u\\n\", conint(global_hdr.snaplen));\n    global_hdr.snaplen = conint(PCAP_MAX_SNAPLEN);\n  }\n\n  /* check for data link type (http://www.tcpdump.org/linktypes.html) */\n  if (conint(global_hdr.network) <= 251) {\t/* data link types are <= 251 */\n    if (verbose) printf(\"[+] Data link type: %u\\n\", conint(global_hdr.network));\n  } else {\n    hdr_integ++;\n    if (verbose) printf(\"[-] Data link type: %u\\n\", conint(global_hdr.network));\n    /* if data link type is corrupt, we set it to ethernet (user supplied param will be processed afterwards) */\n    global_hdr.network = conint(1);\n  }\n\n  /* does the user provides a self-supplied data link type? if yes... change global header */\n  if (data_link_type != -1) {\n    printf(\"[+] Changing data link type to %d.\\n\", data_link_type);\n    global_hdr.network = conint(data_link_type);\n    hdr_integ++;\n  }\n\n  /* evaluate the integrity of the global header */\n  if (hdr_integ == 0) { /* no field has been corrupted? --> header is intact */\n    printf(\"[+] The global pcap header seems to be fine!\\n\");\n  } else if (hdr_integ >= 4) { /* there have been five or more (of seven) corrupted fields? --> header is missing */\n    printf(\"[-] The global pcap header seems to be missing ==> CORRECTED!\\n\");\n    /* we need to set the file pointer to the beginning of the file, because\n     * further packet search depends on this position and without a global\n     * header the first packet might begin there */\n    fseeko(pcap, 0, SEEK_SET);\n\n    /* set important header values to defaults */\n    global_hdr.snaplen = conint(PCAP_MAX_SNAPLEN);\n\n    if (data_link_type != -1) {\n      global_hdr.network = conint(data_link_type);\n    } else {\n      global_hdr.network = conint(1);\n    }\n  } else { /* there have been corrupted fields (less than five) --> header is corrupted */\n    printf(\"[-] The global pcap header seems to be corrupt! ==> CORRECTED\\n\");\n  }\n\n  /* write the (maybe changed) global header to output file */\n  memcpy(writebuffer, &global_hdr, sizeof(global_hdr));\n  writepos += sizeof(global_hdr);\n\n  /* END OF GLOBAL HEADER CHECK */\n\n  /* start handling packets */\n  return(fix_pcap_packets_kuznetzov(pcap, pcap_fix, filesize, global_hdr, hdr_integ, writebuffer, writepos));\n}\n\n/*\n * Function:  fix_pcap_packets\n * ---------------------------\n * tries to fix pcap packets inside a pcap file\n *\n * pcap:        file pointer to input file\n * pcap_fix:    file pointer to output file\n * filesize:    input file size in bytes\n * global_hdr:  global header struct\n * hdr_integ:   global header integrity counter\n * writebuffer: buffer to write pcap packets into\n * writepos:    position in buffer to write next packet to\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap_packets_kuznetzov(FILE *pcap, FILE *pcap_fix, off_t filesize, struct global_hdr_s global_hdr, unsigned short hdr_integ, char *writebuffer, off_t writepos) {\n  struct packet_hdr_kuznet_s packet_hdr;\t/* packet header data */\n  struct packet_hdr_kuznet_s next_packet_hdr;\t/* next packet header data to look forward */\n  char hdrbuffer[sizeof(packet_hdr)*2];\t\t/* the buffer that will be used to find a proper packet */\n\n  char buffer[PCAP_MAX_SNAPLEN];\t\t/* the packet body */\n  off_t bytes;\t\t\t\t\t/* read/written bytes counter */\n\n  unsigned int count;\t\t\t\t/* packet counter */\n  unsigned int step = 1;\t\t\t/* step counter for progress bar */\n\n  off_t pos = 0;\t\t\t\t/* position of current packet header */\n  off_t nextpos = 0;\t\t\t        /* possible position of next packets header */\n\n  unsigned int last_correct_ts_sec = 0;\t\t/* timestamp of the last proper packet found (seconds) */\n  unsigned int last_correct_ts_usec = 0;\t/* timestamp of the last proper packet found (microseconds or nanoseconds) */\n\n  int ascii = 0;\t\t\t\t/* ascii counter for possible ascii-corrupted packets */\n  int corrupted = 0;\t\t\t\t/* corrupted packet counter for final output */\n\n  int res;\t\t\t\t\t/* the result of the header check == the offset of body shifting */\n\n  /* BEGIN PACKET CHECK */\n\n  printf(\"[*] Analyzing packets...\\n\");\n\n  /* this loop iterates the packets from top till down by checking the\n   * pcap packet headers on plausibility. if any packet header has got\n   * implausible information the packet will be handled as corrupted\n   * and pcapfix will brute force the next packet. if the packet header\n   * look plausible, pcapfix will check if the next packet is aligned and\n   * if not check for overlapping packets.\n   */\n\n  /* get current file pointer position */\n  pos = ftello(pcap);\n\n  /* loop the pcap files packets until pos has reacher end of file */\n  for (count=1; pos < filesize; count++) {\n\n    /* we only want the progress bar to be printed in non-verbose mode */\n    if ((verbose == 0) && (5*(float)pos/(float)filesize > step)) {\n      print_progress(pos, filesize);\n      step++;\n    }\n\n    /* check if a pcap packet header would fit into the file */\n    if (pos + (off_t)sizeof(hdrbuffer) > filesize) {\n      printf(\"[-] Not enough bytes left in file ==> SKIPPING %\" FMT_OFF_T \" bytes.\\n\", filesize-pos);\n      corrupted++;\n\n      /* at least one packet has been found?? */\n      if (count == 1) {\n        printf(\"[-] No packet has been found!\\n\");\n        return(-2);\n      }\n\n      /* end of file reached */\n      pos = filesize;\n      break;\n    }\n\n    /* read the next packet header */\n    bytes = fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap);\n    if (bytes != 1) return -3;\n\n    /* check if the packet header looks proper */\n    res = check_header_kuznetzov(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &packet_hdr);\n    if (res != -1) {\n\n      /* realign packet body (based on possible-ascii corrupted pcap header) */\n      pos += res;\n      fseeko(pcap, pos+sizeof(packet_hdr), SEEK_SET);\n\n      /* try to read the packet body AND check if there are still at least 24 bytes left for the next pcap packet header */\n      if ((fread(&buffer, conint(packet_hdr.incl_len), 1, pcap) == 0) || ((filesize-(pos+sizeof(packet_hdr)+conint(packet_hdr.incl_len)) > 0) && (filesize-(pos+sizeof(packet_hdr)+conint(packet_hdr.incl_len)) < sizeof(packet_hdr)))) {\n        /* fread returned an error (EOL while read the body) or the file is not large enough for the next pcap packet header (24bytes) */\n        /* thou the last packet has been cut of */\n\n        if (verbose >= 1) printf(\"[-] LAST PACKET MISMATCH (%u | %u | %u | %u)\\n\", conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n        /* correct the packets included length field to match the end of file */\n        packet_hdr.incl_len = conint(filesize-pos-sizeof(packet_hdr));\n\n        /* the original length must not be smaller than the included length */\n        if (conint(packet_hdr.incl_len) > conint(packet_hdr.orig_len)) packet_hdr.orig_len = packet_hdr.incl_len;\n\n        /* print out information */\n        printf(\"[+] CORRECTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n        corrupted++;\n      }\n\n      /* OVERLAPPING DETECTION */\n      /* we do ONLY scan for overlapping if next packet is NOT aligned */\n\n      /* read next packet header */\n      bytes = fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap);\n\n      /* check if next packets header looks proper */\n      if (check_header_kuznetzov(hdrbuffer, sizeof(hdrbuffer), conint(packet_hdr.ts_sec), &global_hdr, &next_packet_hdr) == -1) {\n\n        /* the next packets header is corrupted thou we are going to scan through the prior packets body to look for an overlapped packet header\n         * also look inside the next packets header + 24bytes of packet body, because we need to know HERE\n         * do not leave the loop if the first packet has not been found yet AND deep scan mode is activated */\n        for (nextpos=pos+(off_t)sizeof(packet_hdr)+1; (nextpos < pos+(off_t)sizeof(packet_hdr)+conint(packet_hdr.incl_len)+2*(off_t)sizeof(packet_hdr)) || (count == 1 && deep_scan == 1); nextpos++) {\n\n          /* read the possible next packets header */\n          fseeko(pcap, nextpos, SEEK_SET);\n          bytes = fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap);\n\n          /* check read success */\n          if (bytes == 0) break;\n\n          /* heavy verbose output :-) */\n          if (verbose >= 2) printf(\"[*] Trying Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n          /* check the header for plausibility */\n          res = check_header_kuznetzov(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &next_packet_hdr);\n          if (res != -1) {\n\n            /* we found a proper header inside the packets body! */\n            if (verbose >= 1) printf(\"[-] FOUND OVERLAPPING data of Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n            /* correct the prior packets length information fields to align the overlapped packet */\n            packet_hdr.incl_len = conint(nextpos-(pos+sizeof(packet_hdr))+res);\t/* also include ascii corruption offset (res) */\n            packet_hdr.orig_len = packet_hdr.incl_len;\n\n            /* time correction for the FIRST packet only */\n            if (count == 1) {\n              if (conint(next_packet_hdr.ts_usec) > 0) {\n                /* next packets usec is > 0 ===> first packet will get same timestamp and usec - 1 */\n                packet_hdr.ts_sec = next_packet_hdr.ts_sec;\n                packet_hdr.ts_usec = conint(conint(next_packet_hdr.ts_usec)-1);\n              } else if(conint(next_packet_hdr.ts_sec) > 0) {\n                /* else: next packets timestamp i > 0 ===> firt packet will get timestamp -1 and maximum usec */\n                packet_hdr.ts_sec = conint(conint(next_packet_hdr.ts_sec)-1);\n                packet_hdr.ts_usec = conint(999999);\n              } else {\n                /* else: (next packets sec and usec are zero), this packet will get zero times as well */\n                packet_hdr.ts_sec = conint(0);\n                packet_hdr.ts_usec = conint(0);\n              }\n            }\n\n            /* print out information */\n            printf(\"[+] CORRECTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n            corrupted++;\n\n            /* overlapping seems to be a result of ascii-transferred pcap files via FTP */\n            ascii++;\n\n            break;\n          }\n        }\n      }\n\n      /* reset file fointer to next packet */\n      fseeko(pcap, pos+sizeof(packet_hdr)+conint(packet_hdr.incl_len), SEEK_SET);\n\n      /* we found a correct packet (and aligned it maybe) */\n      if (verbose >= 1) printf(\"[+] Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n      /* write this packet */\n\n      // check if there is enough space in buffer\n      int totalsize = sizeof(packet_hdr) + conint(packet_hdr.incl_len);\n      if (writepos+totalsize > 1024000) {\n        bytes = fwrite(writebuffer, writepos, 1, pcap_fix);\n        writepos = 0;\n      }\n\n      // put new bytes into write buffer\n      memcpy(writebuffer+writepos, &packet_hdr, sizeof(packet_hdr));\n      writepos += sizeof(packet_hdr);\n      memcpy(writebuffer+writepos, buffer, conint(packet_hdr.incl_len));\n      writepos += conint(packet_hdr.incl_len);\n\n      /* remember that this packets timestamp to evaluate futher timestamps */\n      last_correct_ts_sec = conint(packet_hdr.ts_sec);\n      last_correct_ts_usec = conint(packet_hdr.ts_usec);\n\n    } else {\n\n      /* PACKET IS CORRUPT */\n\n      if (verbose >= 1) printf(\"[-] CORRUPTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n      /* scan from the current position to the maximum packet size and look for a next proper packet header to align the corrupted packet\n       * also do not leave the loop if the first packet has not been found yet AND deep scan mode is activated */\n      for (nextpos=pos+(off_t)sizeof(packet_hdr)+1; (nextpos <= pos+(off_t)sizeof(packet_hdr)+PCAP_MAX_SNAPLEN) || (count == 1 && deep_scan == 1); nextpos++) {\n\n        /* read the possible next packets header */\n        fseeko(pcap, nextpos, SEEK_SET);\n        if (fread(hdrbuffer, sizeof(hdrbuffer), 1, pcap) == 0) {\n\n          /* did we read over EOF AND havent found the first packet yet? then we need to abort! */\n          if ((count == 1) && (deep_scan == 1)) {\n\n            /* abort scan */\n            pos = 0;\n            corrupted = -1;\n            break;\n          }\n\n          printf(\"[*] End of file reached. Aligning last packet.\\n\");\n\n          /* check last packet for plausiblilty */\n          res = check_header_kuznetzov(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &packet_hdr);\n          if (res != 0) {\n            printf(\"[-] Cannot align last packet, because it is broken.\\n\");\n            corrupted++;\n            count--;\n            break;\n          }\n\n          /* check passed */\n\n          /* align the last packet to match EOF */\n          packet_hdr.incl_len = conint(filesize-(pos+sizeof(packet_hdr)));\n          packet_hdr.orig_len = packet_hdr.incl_len;\n\n          /* if the is the first packet, we need to set timestamps to zero */\n          if (count == 1) {\n            packet_hdr.ts_sec = conint(0);\n            packet_hdr.ts_usec = conint(0);\n          } else {\t/* else take the last correct timestamp and usec plus one */\n            packet_hdr.ts_sec = conint(last_correct_ts_sec);\n            packet_hdr.ts_usec = conint(last_correct_ts_usec+1);\n          }\n\n          /* read the packets body (size based on the just found next packets position) */\n          fseeko(pcap, pos+sizeof(packet_hdr), SEEK_SET);\n          bytes = fread(&buffer, conint(packet_hdr.incl_len), 1, pcap);\n\n          // check if there is enough space in buffer\n          int totalsize = sizeof(packet_hdr) + conint(packet_hdr.incl_len);\n          if (writepos+totalsize > 1024000) {\n            bytes = fwrite(writebuffer, writepos, 1, pcap_fix);\n            writepos = 0;\n          }\n\n          // put new bytes into write buffer\n          memcpy(writebuffer+writepos, &packet_hdr, sizeof(packet_hdr));\n          writepos += sizeof(packet_hdr);\n          memcpy(writebuffer+writepos, buffer, conint(packet_hdr.incl_len));\n          writepos += conint(packet_hdr.incl_len);\n\n          /* remember that this packets timestamp to evaluate futher timestamps */\n          last_correct_ts_sec = packet_hdr.ts_sec;\n          last_correct_ts_usec = packet_hdr.ts_usec;\n\n          /* print out information */\n          printf(\"[+] CORRECTED LAST Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n          corrupted++;\n\n          break;\n        }\n\n        /* shall we abort the whole scan?? */\n        if (corrupted == -1) break;\n\n        /* heavy verbose output :-) */\n        if (verbose >= 2) printf(\"[*] Trying Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n        /* check if next packets header looks proper */\n        res = check_header_kuznetzov(hdrbuffer, sizeof(hdrbuffer), last_correct_ts_sec, &global_hdr, &next_packet_hdr);\n        if (res != -1) {\n\n          /* if we found a packet that is below the top MAX_SNAPLEN bytes (deep scan) we cut it off and take the second packet as first one */\n          if ((nextpos-(pos+sizeof(packet_hdr)) > PCAP_MAX_SNAPLEN) && (count == 1) && (deep_scan == 1)) {\n\n            if (verbose >= 1) printf(\"[+] (DEEP SCAN) FOUND FIRST Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n            /* set the filepoint to the top of the first packet to be read in next loop iteration */\n            fseeko(pcap, nextpos, SEEK_SET);\n\n            /* correct counter due to deep scan */\n            count--;\n\n          } else { /* found next packet (NO deep scan mode) */\n\n            /* we found the NEXT packets header, now we are able to align the corrupted packet */\n            if (verbose >= 1) printf(\"[+] FOUND NEXT Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", (count+1), nextpos, conint(next_packet_hdr.ts_sec), conint(next_packet_hdr.ts_usec), conint(next_packet_hdr.incl_len), conint(next_packet_hdr.orig_len));\n\n            /* correct the corrupted pcap packet header to match the just found next packet header */\n            packet_hdr.incl_len = conint(nextpos-(pos+sizeof(packet_hdr)));\n            packet_hdr.orig_len = packet_hdr.incl_len;\n\n            if (count == 1) { /* time correction for the FIRST packet */\n              if (conint(next_packet_hdr.ts_usec) > 0) {\n                /* next packets usec is > 0 ===> first packet will get same timestamp and usec - 1 */\n                packet_hdr.ts_sec = next_packet_hdr.ts_sec;\n                packet_hdr.ts_usec = conint(conint(next_packet_hdr.ts_usec)-1);\n              } else if(conint(next_packet_hdr.ts_sec) > 0) {\n                /* else: next packets timestamp i > 0 ===> firt packet will get timestamp -1 and maximum usec */\n                packet_hdr.ts_sec = conint(conint(next_packet_hdr.ts_sec)-1);\n                packet_hdr.ts_usec = conint(999999);\n              } else {\n                /* else: (next packets sec and usec are zero), this packet will get zero times as well */\n                packet_hdr.ts_sec = conint(0);\n                packet_hdr.ts_usec = conint(0);\n              }\n            } else { /* ALL packets except the first one will use the last correct packets timestamps */\n              packet_hdr.ts_sec = conint(last_correct_ts_sec);\n              packet_hdr.ts_usec = conint(last_correct_ts_usec+1);\n            }\n\n            /* read the packets body (size based on the just found next packets position) */\n            fseeko(pcap, pos+sizeof(packet_hdr), SEEK_SET);\n            bytes = fread(&buffer, conint(packet_hdr.incl_len), 1, pcap);\n\n            /* final check resulting packet for plausibility */\n            res = is_plausible_kuznetzov(global_hdr, packet_hdr, last_correct_ts_sec);\n            if (res == 0) {\n\n              // check if there is enough space in buffer\n              int totalsize = sizeof(packet_hdr) + conint(packet_hdr.incl_len);\n              if (writepos+totalsize > 1024000) {\n                bytes = fwrite(writebuffer, writepos, 1, pcap_fix);\n                writepos = 0;\n              }\n\n              // put new bytes into write buffer\n              memcpy(writebuffer+writepos, &packet_hdr, sizeof(packet_hdr));\n              writepos += sizeof(packet_hdr);\n              memcpy(writebuffer+writepos, buffer, conint(packet_hdr.incl_len));\n              writepos += conint(packet_hdr.incl_len);\n\n              /* remember that this packets timestamp to evaluate futher timestamps */\n              last_correct_ts_sec = conint(packet_hdr.ts_sec);\n              last_correct_ts_usec = conint(packet_hdr.ts_usec);\n\n              /* print out information */\n              printf(\"[+] CORRECTED Packet #%u at position %\" FMT_OFF_T \" (%u | %u | %u | %u).\\n\", count, pos, conint(packet_hdr.ts_sec), conint(packet_hdr.ts_usec), conint(packet_hdr.incl_len), conint(packet_hdr.orig_len));\n\n            } else {\n              /* prior packet is invalid */\n              printf(\"[-] Packet #%u at position %\" FMT_OFF_T \" is invalid ==> SKIPPING.\\n\", count, pos);\n            }\n\n          }\n\n          /* increase corruption counter */\n          corrupted++;\n\n          /* leave the next packet search loop */\n          break;\n        }\n\n      }\n\n      /* shall we abort the whole scan (due to deep scan did not succeed at all) */\n      if (corrupted == -1) break;\n\n      /* did the counter exceed the maximum packet size? */\n      if ((count == 1 && deep_scan == 0) && (nextpos > pos+(off_t)sizeof(packet_hdr)+PCAP_MAX_SNAPLEN)) {\n\n        /* PACKET COULD NOT BE REPAIRED! */\n\n        if (verbose >= 1) printf(\"[-] Cannot align corrupted packet! \\n\");\n        break;\n      }\n\n      /* maximum search range reached? -> skip packet and keep on searching */\n      if (deep_scan == 0 && (nextpos > pos+(off_t)sizeof(packet_hdr)+PCAP_MAX_SNAPLEN)) {\n        if (verbose >= 1) printf(\"[-] No next packet found within max packet range --> SKIPPING!\\n\");\n\n        /* reset counter because no packet found */\n        count--;\n      }\n\n    }\n\n    /* get current file pointer position to start next loop iteration */\n    pos = ftello(pcap);\n\n  }\n\n  // write remaining data into buffer\n  bytes = fwrite(writebuffer, writepos, 1, pcap_fix);\n  writepos = 0;\n\n  if (verbose == 0) { print_progress(pos, filesize); }\n\n  /* did we reach the end of pcap file? */\n  if (pos != filesize) { /* no ==> data missing == FAILED */\n    printf(\"[-] Reached EOF without finding more packets!\\n\");\n    corrupted = -1;\t/* the file could not be repaired */\n  }\n\n  /* END PACKET CHECK */\n\n  /* EVALUATE RESULT */\n\n  if ((hdr_integ == 0) && (corrupted == 0)) { /* check allover failure / integrity count and corrupted counter */\n\n   /* no errors (header + packets correct) */\n   return(0);\n\n  } else if (corrupted == -1) {\t/* check vor very high packet failure value ==> no recovery possible */\n\n    /* file could NOT be repaired */\n\n    if (count == 1) {\n\n      /* even the first packet was corrupted and no other packet could be found */\n      return(-1);\n\n    } else {\n\n      /* the first packet was intact, but recovery is not possible nevertheless */\n      return(-2);\n\n    }\n\n  } else {\n    /* check if we found at least one packet */\n    if (count == 1) {\n      /* even the first packet was corrupted and no other packet could be found */\n      return(-1);\n    }\n\n    /* file has been successfully repaired (corruption fixed) */\n\n    printf(\"[*] Wrote %u packets to file.\\n\", count-1);\n\n    /* are there any packets that might have been transferred in ascii mode? */\n    if (ascii) {\n      printf(\"[!] This corruption seems to be a result of an ascii-mode transferred pcap file via FTP.\\n\");\n      printf(\"[!] The pcap structure of those files can be repaired, but the data inside might still be corrupted!\\n\");\n    }\n\n    return(hdr_integ+corrupted);\n\n  }\n\n}\n"
  },
  {
    "path": "pcap_kuznet.h",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#ifndef PF_PCAP_KUZNET\n#define PF_PCAP_KUZNET\n\n#define PCAP_EXT_MAGIC 0xa1b2cd34               /* the magic of the extended pcap global header (non swapped) */\n#define PCAP_EXT_MAGIC_SWAPPED 0x34cdb2a1\t/* the magic of the extended pcap global header (swapped) */\n\n#include \"pcap.h\"\n\n/* KUZNETZOV Packet Header\n   https://wiki.wireshark.org/Development/LibpcapFileFormat#modified-pcap */\nstruct packet_hdr_kuznet_s {\n  u_int32_t ts_sec;         /* timestamp seconds */\n  u_int32_t ts_usec;        /* timestamp microseconds */\n  u_int32_t incl_len;       /* number of octets of packet saved in file */\n  u_int32_t orig_len;       /* actual length of packet */\n  int32_t index;\n  u_int16_t protocol;\n  u_int8_t pkt_type;\n};\n\n/*\n * Function:  is_plausible\n * -----------------------\n * check if the pcap packet header could be a plausible one by satisfying those conditions:\n * - packet size >= 16 bytes AND <= MAX_SNAPLEN bytes (included length AND original length) (conditions 1,2,3,4)\n * - included length <= original lenth (condition 5)\n * - packet timestamp is NOT older OR younger than the prior packets timestamp -+ one day (conditions 6,7)\n * - usec (microseconds) field <= 1000000 (conditions 8)\n * - usec (nanoseconds) field <= 1000000000 (conditions 9)\n *\n * global_hdr: the filled pcap header to check for snaplen\n * hdr:        the filled packet header struct to check for plausibility\n * prior_ts:   the prior packets timestamp (seconds) to check for time relation (condition 6,7)\n *\n * returns:  0   success\n *          -X   error (condition X failed)\n *\n */\nint is_plausible_kuznet(struct global_hdr_s global_hdr, struct packet_hdr_s hdr, unsigned int prior_ts);\n\n/*\n * Function:  check_header\n * -----------------------\n * this function takes a buffer and brute forces some possible ascii-corrupted bytes versus plausibility checks\n *\n * buffer:     the buffer that might contain the possible pcap packet header\n * size:       the size of the buffer (double pcap packet header size is a good choice)\n * priot_ts:   the prior packets timestamp (to check for plausibility)\n * global_hdr: the pointer to the pcap buffer\n * hdr:        the pointer to the packet header buffer (we use this to return the repaired header)\n *\n * returns: >=0   success (return value contains number of ascii corrupted bytes in hdr (we need this data to align the beginning of the packet body later)\n *           -1   error (no valid pcap header found inside buffer)\n *\n */\nint check_header_kuznetzov(char *buffer, unsigned int size, unsigned int prior_ts, struct global_hdr_s *global_hdr, struct packet_hdr_kuznet_s *hdr);\n\n/*\n * Function:  fix_pcap\n * -------------------\n * tries to fix a classic pcap file\n *\n * pcap:      file pointer to input file\n * pcap_fix:  file pointer to output file\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap_kuznetzov(FILE *pcap, FILE *pcap_fix);\n\n/*\n * Function:  fix_pcap_packets\n * ---------------------------\n * tries to fix pcap packets inside a pcap file\n *\n * pcap:        file pointer to input file\n * pcap_fix:    file pointer to output file\n * filesize:    input file size in bytes\n * global_hdr:  global header struct\n * hdr_integ:   global header integrity counter\n * writebuffer: buffer to write pcap packets into\n * writepos:    position in buffer to write next packet to\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF reached while reading input file)\n *\n */\nint fix_pcap_packets_kuznetzov(FILE *pcap, FILE *pcap_fix, off_t filesize, struct global_hdr_s global_hdr, unsigned short hdr_integ, char *writebuffer, off_t writepos);\n\n#endif\n"
  },
  {
    "path": "pcapfix.1",
    "content": ".TH PCAPFIX 1 \"03 JUL 2021\"\n\n.SH \"NAME\"\npcapfix \\- repair pcap and pcapng files\n\n.SH \"SYNOPSIS\"\n\\fBpcapfix\\fP [\\-d] [\\-n] [\\-o filename] [\\-t DATA_LINK_TYPE] [\\-v] filename\n\n.SH \"DESCRIPTION\"\nPcapfix is a tool to repair your damaged or corrupted pcap and pcapng files. It is written in C and released under the GNU General Public License.\n\nTo fix your pcap files the tool first checks for an intact pcap global header and repairs it if there are some corrupted bytes. It there seems to be no global header at all, pcapfix adds a self-created one at the beginning of the file. In a second step the tool tries to find pcap packet headers inside the file, below the global header. It checks if the values are correct (or seem to be correct) and tries to repair a packet if there is something wrong.\n\nTo fix your pcapng files the tool loops through all packet headers that can be found in the file. It checks for mandatory Section Header and Interface Description Block and creates them if missing. Pcapfix checks for correct block sizes and valid option fields. If something is wrong, invalid fields are repaired (if possible) or skipped and adjusted to finally get a proper pcapng file.\n\n.SH \"OPTIONS\"\n.TP 5\n\\-d, \\-\\-deep\\-scan\nForce deep scan (default = 0)\n.br\n\\-s, \\-\\-soft\\-mode\nSwitch to soft mode packet detection (default = 0)\n.br\nThis option will force pcapfix to scan for any packet inside the whole file (instead of the first 262144 (max snaplen) bytes only).\n.TP\n\\-n, \\-\\-pcapng\nForce File Format to PCAPNG (default = 0)\n.br\nThis option will force pcapfix to repair the input file as it were in pcapng format (useful for destroyed file headers).\n.TP\n\\-o, \\-\\-outfile <filename>\nSet the output file name. Default will be input file prepended by \"fixed_\".\n.TP\n\\-t, \\-\\-data\\-link\\-type <nr>\nData Link Type (default = 1)\n.br\n(See NOTES section below.)\n.TP\n\\-v, \\-\\-verbose\nEnable verbose output (default = 0)\n.br\nYou can use multiple \\-v options to increase verbosity.\n.br\nAn verbosity of 2 will result in very much output data during package search.\n\n.SH \"EXAMPLES\"\n.TP 5\nRepair the pcap file using deep scan mode, because large blocks of the file are corrupted.\npcapfix \\-d file.pcap\n.TP\nRepair the file damaged_file.pcapng using verbose output.\npcapfix \\-v damaged_file.pcapng\n.TP\nRepair the file wlan_traffic.pcap and force the data link type to be 119 (PRISM HEADER).\npcapfix \\-t 119 wlan_traffic.pcap\n.TP\nRepair the file damaged.pcapng which file header is corrupted and force its format to be pcapng.\npcapfix \\-n damaged.pcapng\n\n.SH \"NOTES\"\n.TP 5\n\\fIOutput file name\\fP\n\nIf you want to perform the reparation process on the input file without creating a separate output file - e.g. in case you are out of space, you can use the -o option and give the same name as the input file.\n\nWARNING: This process is DANGEROUS and may destroy your data. You should only use this option if you know what you are doing and accept the risk of losing the input file.\n\n.TP\n\\fIDeep scan\\fP\n\nIn classic pcap files, pcapfix will only scan the first 262144 bytes (maximum packet length) for a proper first packet. If you want to force packet detection even above this limit (e.g. because your file has been heavily destroyed) you can use the deep scan option (\\-d).\n\nThis option is not necessary for pcapng files because the whole file is arranged in blocks that are 'unlimited' by default. In result pcapfix will always scan the whole pcapng file for further blocks.\n\n.TP\n\\fISoft mode\\fP\n\nThere are programs that breach some pcap conventions when writing files. Ignoring those rules do not break the pcap file but they make it difficult for pcapfix to identify the packets in case of broken files.\n\nBy default pcapfix uses hard mode. If you encounter problems when repairing files, try to switch to soft mode (-s). Pcapfix will then try to find the packets in a more tolerant way.\n\n.TP\n\\fIPCAPNG Format\\fP\n\nPcapfix will try to identify the file format to repair (pcap / pcapng) before doing any further checks. If the header itself is corrupted, it will assume the format to be classic pcap. To change this behaviour you can force the tool to do a pcapng-repair by supplying \\-n (\\-\\-pcapng) option.\n\n.TP\n\\fIVerbosity\\fP\n\nYou can use multiple \\-v options to increase verbosity. An verbosity of 2 will result in very much output data during package search.\n\n.TP\n\\fIASCII-mode transferred Files (FTP)\\fP\n\nPcapfix is able to repair pcap files that have been transferred in ascii-mode via FTP. In those files a proper pcap structure will be created only to make them readable by wireshark etc. The data inside the packets (and some pcap headers) might still be corrupted. To repair those packets a deeper look inside the packet structure (e.g. checksum) will be necessary.\n\n.TP\n\\fIData Link Types\\fP\n\nYou can make pcapfix change / select your data link type by supplying \\-t option. Although you may select a data link type number between 0 and 255, only the following types are assigned: If the data link type field is corrupt, pcapfix will select LINKTYPE_ETHERNET by default.\n\nSee http://www.tcpdump.org/linktypes.html for further information.\n\nNUMBER\tLINK_TYPE\n\n0\tLINKTYPE_NULL\n.br\n1\tLINKTYPE_ETHERNET\n.br\n6\tLINKTYPE_TOKEN_RING\n.br\n7\tLINKTYPE_ARCNET_BSD\n.br\n8\tLINKTYPE_SLIP\n.br\n9\tLINKTYPE_PPP\n.br\n10\tLINKTYPE_FDDI\n.br\n50\tLINKTYPE_PPP_HDLC\n.br\n51\tLINKTYPE_PPP_ETHER\n.br\n100\tLINKTYPE_ATM_RFC1483\n.br\n101\tLINKTYPE_RAW\n.br\n104\tLINKTYPE_C_HDLC\n.br\n105\tLINKTYPE_IEEE802_11\n.br\n107\tLINKTYPE_FRELAY\n.br\n108\tLINKTYPE_LOOP\n.br\n113\tLINKTYPE_LINUX_SLL\n.br\n114\tLINKTYPE_LTALK\n.br\n117\tLINKTYPE_PFLOG\n.br\n119\tLINKTYPE_PRISM_HEADER\n.br\n122\tLINKTYPE_IP_OVER_FC\n.br\n123\tLINKTYPE_SUNATM\n.br\n127\tLINKTYPE_IEEE802_11_RADIO\n.br\n129\tLINKTYPE_ARCNET_LINUX\n.br\n138\tLINKTYPE_APPLE_IP_OVER_IEEE1394\n.br\n139\tLINKTYPE_MTP2_WITH_PHDR\n.br\n140\tLINKTYPE_MTP2\n.br\n141\tLINKTYPE_MTP3\n.br\n142\tLINKTYPE_SCCP\n.br\n143\tLINKTYPE_DOCSIS\n.br\n144\tLINKTYPE_LINUX_IRDA\n.br\n147-162\tLINKTYPE_USER0-LINKTYPE-USER15\n.br\n163\tLINKTYPE_IEEE802_11_RADIO_AVS\n.br\n166\tLINKTYPE_PPP_PPPD\n.br\n169\tLINKTYPE_GPRS_LLC\n.br\n177\tLINKTYPE_LINUX_LAPD\n.br\n187\tLINKTYPE_BLUETOOTH_HCI_H4\n.br\n189\tLINKTYPE_USB_LINUX\n.br\n192\tLINKTYPE_PPI\n.br\n195\tLINKTYPE_IEEE802_15_4\n.br\n196\tLINKTYPE_SITA\n.br\n197\tLINKTYPE_ERF\n.br\n201\tLINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR\n.br\n202\tLINKTYPE_AX25_KISS\n.br\n203\tLINKTYPE_LAPD\n.br\n204\tLINKTYPE_PPP_WITH_DIR\n.br\n205\tLINKTYPE_C_HDLC_WITH_DIR\n.br\n206\tLINKTYPE_FRELAY_WITH_DIR\n.br\n209\tLINKTYPE_IPMB_LINUX\n.br\n215\tLINKTYPE_IEEE802_15_4_NONASK_PHY\n.br\n220\tLINKTYPE_USB_LINUX_MMAPPED\n.br\n224\tLINKTYPE_FC_2\n.br\n225\tLINKTYPE_FC_2_WITH_FRAME_DELIMS\n.br\n226\tLINKTYPE_IPNET\n.br\n227\tLINKTYPE_CAN_SOCKETCAN\n.br\n228\tLINKTYPE_IPV4\n.br\n229\tLINKTYPE_IPV6\n.br\n230\tLINKTYPE_IEEE802_15_4_NOFCS\n.br\n231\tLINKTYPE_DBUS\n.br\n235\tLINKTYPE_DVB_CI\n.br\n236\tLINKTYPE_MUX27010\n.br\n237\tLINKTYPE_STANAG_5066_D_PDU\n.br\n239\tLINKTYPE_NFLOG\n.br\n240\tLINKTYPE_NETANALYZER\n.br\n241\tLINKTYPE_NETANALYZER_TRANSPARENT\n.br\n242\tLINKTYPE_IPOIB\n.br\n243\tLINKTYPE_MPEG_2_TS\n.br\n244\tLINKTYPE_NG40\n.br\n245\tLINKTYPE_NFC_LLCP\n\n.SH \"DEVELOPMENT\"\nThis tool is still under development! Please send any further wishes, feature requests or problems in compiling and execution to ruport@f00l.de. Additionally You may send me pcap/pcapng files that could not be repaired too in order to improve pcapfix and get your file repaired.\n\nFor further information visit the pcapfix homepage at http://f00l.de/pcapfix/.\n\n.SH \"MESSAGES AND EXIT CODES\"\n 1\t, file was corrupted and has been repaired\n.br\n 0\t, file is proper; nothing to repair\n.br\n\\-1\t, invalid options / parameters given\n.br\n\\-2\t, cannot open input file for reading\n.br\n\\-3\t, cannot open output file for writing\n.br\n\\-4\t, input file is empty\n.br\n\\-5\t, input file is too small\n.br\n\\-6\t, file type not supported\n.br\n\\-11\t, not a pcap/pcapng file\n.br\n\\-12\t, unable to repair the file\n.br\n\\-13\t, EOF while reading input file\n.br\n\\-255\t, unknown error\n\n.SH \"HISTORY\"\n.TP 5\n1.1.7 - 03.07.2021\n* fixed security issues\n.TP\n1.1.6 - 13.06.2021\n* added security boundary checks in pcapng format\n.TP\n1.1.5 - 05.04.2021\n* snaplen checks are only performed in soft mode now\n.br\n* fixed repairs for dlt 195 (ieee 802.15.4 with fcs)\n.br\n* fixed (binary) file repair bug under Microsoft Windows\n.br\n* improved compiling on all platforms (thanks to mdeweerd)\n.TP\n1.1.4 - 22.01.2019\n* added support for extended pcap file format (kuznetzov)\n.br\n* fixed dtl 113 (linux cooked) handling (thanks to Andre Luyer)\n.br\n* improved hard and soft mode checks for younger/older packets\n.br\n* minor fixes and improvements\n.TP\n1.1.3 - 04.09.2018\n* implemtented soft mode (for plausibility checks)\n.TP\n1.1.2 - 16.07.2018\n* fixed cross compiling (thanks to Helmut Grohne)\n.br\n* increased maximum snap length to 262144\n.TP\n1.1.1 - 25.12.2017\n* added write buffers and support to perform repair process without creation of a separate output file\n.br\n* fixed another MacOS build problem\n.br\n* fixed minor bugs\n.TP\n1.1.0 - 31.08.2013\n* added checks for valid pcapng format (epb)\n.br\n* added \\-\\-outfile parameter to chose fixed file name\n.br\n* improved pcapng packet alignment (pb, spb, nrb)\n.br\n* improved pcapng option fields handling\n.br\n* improved status and verbosity outputs\n.br\n* fixed reparation bugs with swapped pcap files\n.br\n* fixed MacOS compile problem\n.br\n* fixed windows output file name extension missing\n.br\n* fixed many minor bugs\n.TP\n1.0.2 - 18.02.2013\n* added support for files larger than 2GB on 32bit systems\n.TP\n1.0.1 - 03.11.2013\n* added reparation block type id zero (pcapng)\n.br\n* added reparation of capture length inside EPB (pcapng)\n.br\n* set data link type to ethernet on missing header (pcap)\n.br\n* changed missing pcap header threshold             \n.br\n* fixed minor bugs\n.TP\n1.0.0 - 12.10.2013\n* added pcapng support\n.br\n* added nanoseconds support (Issue #1)\n.br\n* improved console output\n.br\n* minor bugs fixed\n.TP\n0.7.3 - 16.06.2013\n* added snoop file detection\n.br\n* added large file support on 32bit architectures\n.br\n* improved missing header detection\n.br\n* fixed compiling errors on hurd and kfreebsd architectures\n.br\n* fixed minor bugs\n.TP\n0.7.2 - 30.03.2013\n* compiles on Apple systems properly now\n.br\n* fixed problems installing man-pages (on some systems)\n.TP\n0.7.1 - 03.01.2013\n* REALLY fixed file pointer exception on windows64 systems\n.br\n* updated man-page\n.TP\n0.7 - 18.10.2012\n* added support for swapped (big endian) pcap files\n.br\n* compiles on OpenBSD properly now\n.br\n* fixed file pointer exception on windows64 systems\n.br\n* fixed detection bug when corrupted packet is larger than 65536 bytes\n.br\n* fixed minimal packet limit to cope with wlan traffic\n.TP\n0.6 - 20.05.2012\n* added deep scan option (\\-d) to force packet detection inside the whole file\n.br\n* detects ascii-corruption in pcap header (unix->win)\n.br\n* improved global header and packet checks (0 <= usec <= 1000000)\n.br\n* repair files that first packet is entirely corrupted\n.br\n* repair oversized packets\n.br\n* improved last packet mismatch correction\n.br\n* fixed reading packets over EOF\n.TP\n0.5 - 05.05.2012\n* repair files that packets were not saved chronologically\n.br\n* detect and repair overlapping packets\n.br\n* detect and repair cut-off pcap files\n.br\n* detect and repair ascii-mode transferred pcap files (pcap headers only!)\n.br\n* added progress bar\n.br\n* added man-page\n.TP\n0.4 - 27.04.2012\n* completely redesigned packet detection algorithm (replaced bottom-up-recovery with brute-force-packet-guessing)\n.br\n* improved detection rate by additional plausibility checks\n.br\n* increased speed when repairing large pcap files\n.TP\n0.3 - 31.03.2012\n* when recovering packets size will be checked to be smaller than 65536\n.br\n* added recognition when a file does not seem to be a pcap file at all\n.br\n* compiles on windows systems properly now (tested with dev-cpp)\n.br\n* added option to manually select data link type\n.TP\n0.2 - 11.03.2012\n* pcapfix compiles on 64bit systems correctly now\n.br\n* fixed segfault when no filename was given\n.br\n* fixed (input) file not found bug on directory differ\n.br\n* added recognition of other data link types beside ethernet in global header\n.br\n* added source code documentation\n.TP\n0.1 - 01.03.2012\n* this is the first version, everything has changed thou :-)\n\n.SH \"COPYRIGHT\"\nCopyright (c) 2012-2021 Robert Krause\n\nPcapfix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.\n\nPcapfix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n.SH \"AUTHOR\"\nWritten by Robert Krause <ruport@f00l.de>.\n"
  },
  {
    "path": "pcapfix.c",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n * Last Modified: 03.07.2021\n *\n *******************************************************************************\n *\n * Description:\n *\n * Pcapfix is a tool to repair your damaged or corrupted pcap and pcapng files.\n * It is written in C and released under the GNU General Public License.\n *\n * To fix your pcap files the tool first checks for an intact pcap global header\n * and repairs it if there are some corrupted bytes. It there seems to be no\n * global header at all, pcapfix adds a self-created one at the beginning of the\n * file. In a second step the tool tries to find pcap packet headers inside the\n * file, below the global header. It checks if the values are correct (or seem\n * to be correct) and tries to repair a packet if there is something wrong. \n *\n * To fix your pcapng files the tool loops through all packet headers that can\n * be found in the file. It checks for mandatory Section Header Block and\n * Interface Description Block and creates them if missing. Pcapfix checks for\n * correct block sizes and valid option fields. If something is wrong, invalid\n * fields are repaired (if possible) or skipped and adjusted to finally get a\n * proper pcapng file.\n *\n ******************************************************************************/\n\n#include \"pcapfix.h\"\n#include \"pcap.h\"\n#include \"pcap_kuznet.h\"\n#include \"pcapng.h\"\n\n#define VERSION \"1.1.7\"\t\t    /* pcapfix version */\n\n#define BTSNOOP_MAGIC 0x6E737462    /* btsnoop file magic (first 4 bytes) */\n#define SNOOP_MAGIC 0x6f6f6e73\t    /* snoop file magic (first 4 bytes) */\n#define NETMON_MAGIC 0x55424d47     /* netmon file magic */\n#define NETMON11_MAGIC 0x53535452   /* netmon 1.1 file magic */\n#define ETHERPEEK_MAGIC 0x7265767f  /* EtherPeek/AiroPeek/OmniPeek file magic */\n\n/* configuration variables */\nint deep_scan = 0;\t\t/* deep scan option (default: no deep scan) */\nint soft_mode = 0;\t\t/* soft mode option (default: no soft mode) */\nint keep_outfile = 0;\t\t/* keep output file even if nothing needed fixing (default: don't) */\nint verbose = 0;\t\t/* verbose output option (default: dont be verbose) */\nint swapped = 0;\t\t/* pcap file is swapped (big endian) */\nint data_link_type = -1;\t/* data link type (default: LINKTYPE_ETHERNET) */\nint pcapng = 0;\t\t\t/* file format to assume */\n\n/* header placeholder */\nunsigned int header_magic;\n\n/*\n * Function:  usage\n * ----------------\n * prints out the usage information of pcapfix\n * invoked when running without / with too less parameters\n *\n * in:  the name of pcapfix' binary file\n *\n */\nvoid usage(char *progname) {\n  printf(\"Usage: %s [OPTIONS] filename\\n\", progname);\n  printf(\"OPTIONS:\");\n  printf(  \"\\t-d        , --deep-scan          \\tDeep scan (pcap only)\\n\");\n  printf(\"\\t\\t-s        , --soft-mode          \\tSoft mode (packet detection)\\n\");\n  printf(\"\\t\\t-n        , --pcapng             \\tforce pcapng format\\n\");\n  printf(\"\\t\\t-o <file> , --outfile <file>     \\tset output file name\\n\");\n  printf(\"\\t\\t-k        , --keep-outfile       \\tdon't delete the output file if nothing needed to be fixed\\n\");\n  printf(\"\\t\\t-t <nr>   , --data-link-type <nr>\\tData link type\\n\");\n  printf(\"\\t\\t-v        , --verbose            \\tVerbose output\\n\");\n  printf(\"\\n\");\n}\n\n/*\n * Function:  conshort\n * -------------------\n * Convertes a short variable into correct byte order (if necessary)\n * depending on the global -swapped- settings of pcap data.\n *\n * This function MUST encapsulate all variables that might be swapped!\n *\n * var: the variable that shall be converted into correct byte order\n *\n * returns: the variable in correct byte order\n *\n */\nunsigned short conshort(unsigned short var) {\n  if (swapped == 0) return(var);\n  return(htons(var));\n}\n\n/*\n * Function:  conint\n * -----------------\n * Convertes an integer variable into correct byte order (if necessary)\n * depending on the global -swapped- settings of pcap data.\n *\n * This function MUST encapsulate all variables that might be swapped!\n *\n * var: the variable that shall be converted into correct byte order\n *\n * returns: the variable in correct byte order\n *\n */\nunsigned int conint(unsigned int var) {\n  if (swapped == 0) return(var);\n  return(htonl(var));\n}\n\n/*\n * Function:  print_progress\n * -------------------------\n * prints the progess line when using pcapfix in non-verbose mode\n *\n * pos:       the current filepointer position\n * filesize:  the size of the input pcap file in bytes\n *\n */\nvoid print_progress(off_t pos, off_t filesize) {\n  float percentage;\t/* pencentage variable */\n\n  /* calculate the current percentage of file analyzing progress */\n  percentage = (float)(100*(double)pos/(double)filesize);\n\n  /* print the first part of the line including percentage output */\n  printf(\"[*] Progress: %6.02f %%\\n\", percentage);\n}\n\n/*\n * Function:  main\n * ---------------\n * - takes arguments from command line\n * - opens input and output files\n * - checks for file format (pcap, pcapng, snoop, ...)\n * - runs fixing function depending on format\n * - evaluates result\n *\n * argc:  number of cmd line args\n * argv:  array of pointers to cmd line args\n *\n * returns:  1    success (filed repaired)\n *           0    success (nothing to fix)\n *          -1    error (parameters)\n *          -2    error (cannot open input file)\n *          -3    error (cannot open output file for writing)\n *          -4    error (input file is empty)\n *          -5    error (input file is too small)\n *          -6    error (filetype is known but not supported)\n *          -11   error (not a pcap file)\n *          -12   error (unable to recover pcap file)\n *          -13   error (EOF while reading input file)\n *          -255  error (unkown)\n *\n */\nint main(int argc, char *argv[]) {\n  FILE *pcap, *pcap_fix;\t\t/* input and output file */\n  int option_index = 0;\t\t\t/* getopt_long option index */\n  int c;                        /* getopts loop counter */\n  int res;                      /* return values */\n  char *filename;               /* filename of input file */\n  char *filebname;              /* filebasename of input file (without path) */\n  char *filename_fix = NULL;    /* filename of output file */\n  off_t bytes;\t\t        /* read/written blocks counter */\n  off_t filesize;\t        /* file size of input pcap file in bytes */\n\n  /* init getopt_long options struct */\n  struct option long_options[] = {\n    {\"deep-scan\", no_argument, 0, 'd'},            /* --deep-scan == -d */\n    {\"soft-mode\", no_argument, 0, 's'},            /* --soft-mode == -s */\n    {\"pcapng\", no_argument, 0, 'n'},               /* --pcapng == -n */\n    {\"outfile\", required_argument, 0, 'o'},        /* --outfile == -o */\n    {\"keep-outfile\", no_argument, 0, 'k'},         /* --keep-outfile == -k */\n    {\"data-link-type\", required_argument, 0, 't'}, /* --data-link-type == -t */\n    {\"verbose\", no_argument, 0, 'v'},              /* --verbose == -v */\n    {0, 0, 0, 0}\n  };\n\n  /* print out pcapfix header information */\n  printf(\"pcapfix %s (c) 2012-2021 Robert Krause\\n\\n\", VERSION);\n\n  /* scan for options and arguments */\n  while ((c = getopt_long(argc, argv, \":t:ko:v::d::s::n::\", long_options, &option_index)) != -1) {\n    switch (c) {\n      case 0:\t/* getopt_long options evaluation */\n        break;\n      case 'd':\t/* deep scan */\n        deep_scan++;\n        break;\n      case 's':\t/* soft mode */\n        soft_mode++;\n        break;\n      case 'k': /* keep outfile even if nothing needed fixing */\n        keep_outfile++;\n        break;\n      case 'n':\t/* pcapng format */\n        pcapng++;\n        break;\n      case 'o':\t/* output file name */\n        filename_fix = malloc(strlen(optarg)+1);\n\tstrcpy(filename_fix, optarg);\n        break;\n      case 't':\t/* data link type */\n        data_link_type = atoi(optarg);\n        break;\n      case 'v':\t/* verbose */\n        verbose++;\n        break;\n      case '?': /* unknown option */\n        usage(argv[0]);\n        return -1;\n      default:\n        abort();\n    }\n  }\n\n  /* filename is first argument */\n  filename = argv[optind++];\n\n  /* if filename is not set, output usage information */\n  if (filename == NULL) {\n    usage(argv[0]);\n    return(-1);\n  }\n\n  /* open input file */\n  printf(\"[*] Reading from file: %s\\n\", filename);\n  pcap = fopen(filename, \"rb\");\n  if (!pcap) {\n    perror(\"[-] Cannot open input file\");\n    return(-2);\n  }\n\n  /* check for preassigned fixed file name */\n  if (filename_fix == NULL) {\n\n    /* open output file */\n    /* we need to extract the basename first (windows and linux use different functions) */\n    filebname = malloc(strlen(filename)+1);\n    #ifdef __WIN32__\n      char *fileext = malloc(strlen(filename));   /* file extention to be used in output file as well */\n      _splitpath(filename, NULL, NULL, filebname, fileext);\t/* windown method (_splitpath) */\n      strcat(filebname, fileext);\n      free(fileext);\n    # else\n      strcpy(filebname, basename(filename));\t\t/* unix method (basename) */\n    #endif\n    filename_fix = malloc(strlen(filebname)+7);\t/* size of outputfile depends on inputfile's length */\n\n    /* prepare output file name: \"fixed_\" + inputfilename */\n    strcpy(filename_fix, \"fixed_\");\n    strcat(filename_fix, filebname);\n    free(filebname);\n  }\n\n  /* open the file for writing */\n\n  // is output == inputfile ?? if yes, then open for read / append\n  // if no, then open for writing only\n  if (strcmp(filename, filename_fix) == 0) pcap_fix = fopen(filename_fix, \"rb+\");\n  else pcap_fix = fopen(filename_fix, \"wb+\");\n\n  if (!pcap_fix) {\n    perror(\"[-] Cannot open output file for writing\");\n    return(-3);\n  }\n  printf(\"[*] Writing to file: %s\\n\", filename_fix);\n\n  /* basic checks of input file */\n\n  /* get file size */\n  fseeko(pcap, 0, SEEK_END);\n  filesize = ftello(pcap);\n  printf(\"[*] File size: %\" FMT_OFF_T \" bytes.\\n\", filesize);\n\n  /* check for empty file */\n  if (filesize == 0) {\n    printf(\"[-] The source file is empty.\\n\\n\");\n    fclose(pcap);\n    fclose(pcap_fix);\n\n    if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n    free(filename_fix);\n\n    return(-4);\n  }\n\n  /* reset file pointer to file begin */\n  fseeko(pcap, 0, SEEK_SET);\n\n  /* read header to header magic for further inspection */\n  bytes = fread(&header_magic, sizeof(header_magic), 1, pcap);\n  if (bytes == 0) {\n    printf(\"[-] Cannot read file header (file too small?).\\n\\n\");\n    fclose(pcap);\n    fclose(pcap_fix);\n\n    if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n    free(filename_fix);\n\n    return(-5);\n  }\n  fseeko(pcap, 0, SEEK_SET);\n\n  /* check for file type */\n  switch (header_magic) {\n\n    /* etherpeek file format --> often used with pcapfix but NOT supported (yet) */\n    case ETHERPEEK_MAGIC:\n      printf(\"[-] This is a EtherPeek/AiroPeek/OmniPeek file, which is not supported.\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to no changes failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      return(-6);\n\n    /* netmon file format --> often used with pcapfix but NOT supported (yet) */\n    case NETMON_MAGIC:\n    case NETMON11_MAGIC:\n      printf(\"[-] This is a NetMon file, which is not supported.\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to no changes failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      return(-6);\n\n    /* SNOOP file format --> often used with pcapfix but NOT supported (yet) */\n    case SNOOP_MAGIC:\n      printf(\"[-] This is a SNOOP file, which is not supported.\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to no changes failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      return(-6);\n\n    case BTSNOOP_MAGIC:\n      printf(\"[-] This is a BTSNOOP file, which is not supported.\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to no changes failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      return(-6);\n\n    /* extended pcap format (KUZNETZOV) */\n    case PCAP_EXT_MAGIC:\n    case PCAP_EXT_MAGIC_SWAPPED:\n      printf(\"[+] This is an extended tcpdump file.\\n\");\n      res = fix_pcap_kuznetzov(pcap, pcap_fix);\n\n      break;\n\n    /* PCAPNG format */\n    case PCAPNG_MAGIC:\n      printf(\"[+] This is a PCAPNG file.\\n\");\n      res = fix_pcapng(pcap, pcap_fix);\n      break;\n\n    /* classic PCAP format */\n    case PCAP_MAGIC:\n    case PCAP_MAGIC_SWAPPED:\n      printf(\"[+] This is a PCAP file.\\n\");\n      if (pcapng > 0) {\n        printf(\"[!] Your wish is my command! I will handle it as PCAPNG nevertheless.\\n\");\n        res = fix_pcapng(pcap, pcap_fix);\n      } else {\n        res = fix_pcap(pcap, pcap_fix);\n      }\n      break;\n\n    /* if the file type is unknown (maybe header corrupted) assume classic PCAP format */\n    default:\n      if (pcapng > 0) {\n        printf(\"[*] Unknown file type. Assuming PCAPNG format.\\n\");\n        res = fix_pcapng(pcap, pcap_fix);\n      } else {\n        printf(\"[*] Unknown file type. Assuming PCAP format.\\n\");\n        res = fix_pcap(pcap, pcap_fix);\n      }\n      break;\n  }\n\n  /* evaluate result of fixing function */\n  switch (res) {\n\n    /* no corruption found; all fields were valid */\n    case 0:\n      printf(\"[*] Your pcap file looks proper. Nothing to fix!\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to no changes failure */\n      if ((strcmp(filename, filename_fix) != 0) && (0 == keep_outfile)) remove(filename_fix);\n      free(filename_fix);\n\n      return(0);\n\n    /* there is NO indication that this has ever been a pcap file at all */\n    case -1:\n      printf(\"[-] FAILED: This file does not seem to be a pcap/pcapng file!\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      /* deep scan / soft mode dependent output */\n      if (deep_scan == 0 || soft_mode == 0) printf(\"If you are SURE that there are pcap packets inside, try with deep scan (-d) (pcap only!) and/or soft mode (-s) to find them!\\n\\n\");\n      else printf(\"There is REALLY no pcap packet inside this file!!!\\n\\n\");\n\n      return(res-10);\n\n    /* it seems to be a pcap file, but pcapfix can NOT repair it (yet) */\n    case -2:\n      printf(\"[-] FAILED: Unable to recover pcap file.\\n\\n\");\n\n      /* some hints for verbose mode and pcapfix improvement support */\n      if (!verbose) printf(\"Try executing pcapfix with -v option to trace the corruption!\\n\");\n      printf(\"You may help to improve pcapfix by sending your pcap file to ruport@f00l.de\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      return(res-10);\n\n    /* fread did not succeed; might be caused by early EOF; but it should NOT happen at all */\n    case -3:\n      printf(\"[-] FAILED: EOF while reading input file.\\n\\n\");\n\n      /* some hints for verbose mode and pcapfix improvement support */\n      if (!verbose) printf(\"Try executing pcapfix with -v option to trace the corruption!\\n\");\n      printf(\"You may help to improve pcapfix by sending your pcap file to ruport@f00l.de\\n\\n\");\n\n      /* close input and output files */\n      fclose(pcap);\n      fclose(pcap_fix);\n\n      /* delete output file due to failure */\n      if (strcmp(filename, filename_fix) != 0) remove(filename_fix);\n      free(filename_fix);\n\n      return(res-10);\n  }\n\n  /* file has been progressed properly. what is the result (number of corruptions)? */\n\n  if (res > 0) {\n    /* Successful repaired! (res > 0) */\n\n    fclose(pcap);\n    off_t finalpos = ftello(pcap_fix);\n    fclose(pcap_fix);\n    int success = truncate(filename_fix, finalpos);\n    if (success != 0) printf(\"[-] Truncating result file failed!\");\n    free(filename_fix);\n\n    printf(\"[+] SUCCESS: %d Corruption(s) fixed!\\n\\n\", res);\n    return(0);\n\n  } else {\n    /* Unknown Error (res < 0); this should NEVER happen! */\n\n    printf(\"[-] UNKNOWN ERROR (%d)\\n\\n\", res);\n    printf(\"Please report this bug to ruport@f00l.de (including -v -v output).\\n\\n\");\n    return(-255);\n\n  }\n\n}\n"
  },
  {
    "path": "pcapfix.h",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#ifndef PF_PCAPFIX\n#define PF_PCAPFIX\n\n#define _FILE_OFFSET_BITS 64\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <inttypes.h>\n\n#ifdef __WIN32__\n  #include <Winsock.h>   \t\t/* needed for htons,htonl on windows systems */\n\n  /* fseeko, ftello are unknown on mingw, use o64 instead */\n  #define fseeko fseeko64\n  #define ftello ftello64\n\n  /* compatibility for fixed size integer types on windows */\n  typedef uint8_t u_int8_t;\n  typedef uint16_t u_int16_t;\n  typedef uint32_t u_int32_t;\n\n  /* truncate does not exist under windows */\n  int truncate(const char *pathname, _off_t len);\n\n#else\n  #include <libgen.h>    \t\t/* needed for basename */\n  #include <arpa/inet.h>\t\t/* htons, htonl */\n#endif\n\n#define FMT_OFF_T \"jd\"  /* printf format for 'off_t' type */\n\n/*\n * Function:  conshort\n * -------------------\n * Convertes a short variable into correct byte order (if necessary)\n * depending on the global -swapped- settings of pcap data.\n *\n * This function MUST encapsulate all variables that might be swapped!\n *\n * var: the variable that shall be converted into correct byte order\n *\n * returns: the variable in correct byte order\n *\n */\nunsigned short conshort(unsigned short var);\n\n/*\n * Function:  conint\n * -----------------\n * Convertes an integer variable into correct byte order (if necessary)\n * depending on the global -swapped- settings of pcap data.\n *\n * This function MUST encapsulate all variables that might be swapped!\n *\n * var: the variable that shall be converted into correct byte order\n *\n * returns: the variable in correct byte order\n *\n */\nunsigned int conint(unsigned int var);\n\n/*\n * Function:  print_progress\n * -------------------------\n * prints the progess line when using pcapfix in non-verbose mode\n *\n * pos:       the current filepointer position\n * filesize:  the size of the input pcap file in bytes\n *\n */\nvoid print_progress(off_t pos, off_t filesize);\n\n/* global configuration variables */\nextern int deep_scan;\t\t/* deep scan option (default: no depp scan) */\nextern int verbose;\t\t/* verbose output option (default: dont be verbose) */\nextern int swapped;\t\t/* pcap file is swapped (big endian) */\nextern int data_link_type;\t/* data link type (default: LINKTYPE_ETHERNET) */\nextern int soft_mode;\t\t/* soft plausibility check (default: OFF) */\n\n#endif\n"
  },
  {
    "path": "pcapng.c",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#include \"pcapfix.h\"\n#include \"pcapng.h\"\n\n/* Header of all pcapng blocks */\nstruct block_header {\n\tu_int32_t\tblock_type;    /* block type */\n\tu_int32_t\ttotal_length;  /* block length */\n};\n\n/* Header of all pcapng options */\nstruct option_header {\n\tu_int16_t\t\toption_code;    /* option code - depending of block (0 - end of opts, 1 - comment are in common) */\n\tu_int16_t\t\toption_length;  /* option length - length of option in bytes (will be padded to 32bit) */\n};\n\n/* Section Header Block (SHB) - ID 0x0A0D0D0A */\nstruct section_header_block {\n\tu_int32_t\tbyte_order_magic;   /* byte order magic - indicates swapped data */\n\tu_int16_t\t\tmajor_version;  /* major version of pcapng (1 atm) */\n\tu_int16_t\t\tminor_version;  /* minor version of pcapng (0 atm) */\n\tint64_t\tsection_length;         /* length of section - can be -1 (parsing necessary) */\n};\n\n/* Interface Description Block (IDB) - ID 0x00000001 */\nstruct interface_description_block {\n\tu_int16_t\t\tlinktype;   /* the link layer type (was -network- in classic pcap global header) */\n\tu_int16_t\t\treserved;   /* 2 bytes of reserved data */\n\tu_int32_t\tsnaplen;        /* maximum number of bytes dumped from each packet (was -snaplen- in classic pcap global header */\n};\n\n/* Packet Block (PB) - ID 0x00000002 (OBSOLETE - EPB should be used instead) */\nstruct packet_block {\n\tu_int16_t\t\tinterface_id;   /* the interface the packet was captured from - identified by interface description block in current section */\n\tu_int16_t\t\tdrops_count;    /* packet dropped by IF and OS since prior packet */\n\tu_int32_t\ttimestamp_high;     /* high bytes of timestamp */\n\tu_int32_t\ttimestamp_low;      /* low bytes of timestamp */\n\tu_int32_t\tcaplen;             /* length of packet in the capture file (was -incl_len- in classic pcap packet header) */\n\tu_int32_t\tlen;                /* length of packet when transmitted (was -orig_len- in classic pcap packet header) */\n};\n\n/* Simple Packet Block (SPB) - ID 0x00000003 */\nstruct simple_packet_block {\n\tu_int32_t\tlen;  /* length of packet when transmitted (was -orig_len- in classic pcap packet header) */\n};\n\n/* Name Resolution Block (NRB) - ID 0x00000004 */\nstruct name_resolution_block {\n\tu_int16_t\t\trecord_type;    /* type of record (ipv4 / ipv6) */\n\tu_int16_t\t\trecord_length;  /* length of record value */\n};\n\n/* Interface Statistics Block - ID 0x00000005 */\nstruct interface_statistics_block {\n\tu_int32_t\tinterface_id;     /* the interface the stats refer to - identified by interface description block in current section */\n\tu_int32_t\ttimestamp_high;   /* high bytes of timestamp */\n\tu_int32_t\ttimestamp_low;    /* low bytes of timestamp */\n};\n\n/* Enhanced Packet Block (EPB) - ID 0x00000006 */\nstruct enhanced_packet_block {\n\tu_int32_t\tinterface_id;     /* the interface the packet was captured from - identified by interface description block in current section */\n\tu_int32_t\ttimestamp_high;   /* high bytes of timestamp */\n\tu_int32_t\ttimestamp_low;    /* low bytes of timestamp */\n\tu_int32_t\tcaplen;           /* length of packet in the capture file (was -incl_len- in classic pcap packet header) */\n\tu_int32_t\tlen;              /* length of packet when transmitted (was -orig_len- in classic pcap packet header) */\n};\n\n/*\n * Function:  fix_pcapng\n * ---------------------\n * tries to fix a pcapng file\n *\n * pcap:      file pointer to input file\n * pcap_fix:  file pointer to output file\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF while reading input file)\n *\n */\nint fix_pcapng(FILE *pcap, FILE *pcap_fix) {\n  struct block_header bh;                   /* Block Header */\n  struct option_header oh;                  /* Option Header */\n  struct section_header_block shb;          /* Section Header Block */\n  struct interface_description_block idb;   /* Interface Description Block */\n  struct packet_block pb;                   /* Packet Block */\n  struct simple_packet_block spb;           /* Simple Packet Block */\n  struct name_resolution_block nrb;         /* Name Resolution Block */\n  struct interface_statistics_block isb;    /* Interface Statistics Block */\n  struct enhanced_packet_block epb;         /* Enhanced Packet Block */\n\n  char *data;                               /* Storage for packet data */\n  char *new_block;                          /* Storage for new (maybe repaired) block to finally write into ouput file */\n\n  // we use a buffer to cache 1mb of writing... this way writing is faster and\n  // we can read and write the file at the same time\n  char *writebuffer, *tmpbuf;\n  off_t writepos = 0;\n\n  off_t bytes;                              /* written bytes/blocks counter */\n  off_t padding;                            /* calculation for padding bytes */\n  off_t pos;                                /* current block position in input file */\n  off_t filesize;                           /* size of input file */\n  unsigned int block_pos;                   /* current position inside -new_block- to write further data to */\n  unsigned int check;                       /* variable to check end of blocks sizes */\n  unsigned int count;                       /* option / record counter to create EOO/EOR if necessary */\n  unsigned int shb_num;                     /* number of SHB counter */\n  unsigned int idb_num;                     /* number of IDB counter */\n  unsigned int step;                        /* step counter for progress bar */\n  unsigned int packets;\n\n  off_t left;                               /* bytes left to proceed until current blocks end is reached */\n  int fixes;                                /* corruptions counter */\n  int res;                                  /* return values */\n\n  /* init write buffer */\n  writebuffer = malloc(1024000);\n\n  /* get file size of input file */\n  fseeko(pcap, 0, SEEK_END);\n  filesize = ftello(pcap);\n  fseeko(pcap, 0, SEEK_SET);\n\n  /* init variables */\n  pos = 0;            /* begin file check at position 0 */\n  packets = 0;\n  fixes = 0;          /* no corruptions fixed yet */\n  shb_num = 0;        /* no SHBs progressed yet */\n  idb_num = 0;        /* no IDBs progressed yet */\n  step = 1;           /* progress bar starts at 0 steps */\n\n  /* loop every block inside pcapng file until end of file is reached */\n\n  while ( pos < (off_t) (filesize-sizeof(bh))) {\n\n    /* print out progress bar if in non-verbose mode */\n    if ((verbose == 0) && (5*(float)pos/(float)filesize > step)) {\n      print_progress(pos, filesize);\n      step++;\n    }\n\n    /* read the header of the current block */\n    bytes = fread(&bh, sizeof(bh), 1, pcap);\n    if (bytes != 1) return -3;\n\n    /* check for invalid block length / file cut off OR block size < 12 bytes */\n    if (bh.total_length > filesize-pos || bh.total_length < 12) {\n      /* block size is invalid (too small / larger than bytes in input file) */\n\n      if (verbose >= 1) {\n        if (bh.total_length > filesize-pos) printf(\"[-] Block Length (%\" PRIu16 \") exceeds file size (%\" FMT_OFF_T \").\\n\", bh.total_length, filesize);\n        else printf(\"[-] Block Length (%\" PRIu16 \") is too small.\\n\", bh.total_length);\n      }\n\n      /* search for next valid block */\n      if (verbose >= 1) printf(\"[*] Trying to align next block...\\n\");\n      res = find_valid_block(pcap, filesize);\n\n      /* block found? */\n      if (res == 0) {\n        /* another valid block has been found in the file */\n\n        if (verbose >= 1) printf(\"[+] GOT Next Block at Position %\" FMT_OFF_T \"\\n\", ftello(pcap));\n\n        /* adjust total blocks length to match next block */\n        bh.total_length = ftello(pcap)-pos;\n\n      } else {\n        /* there are no more blocks inside the file */\n\n        if (verbose >= 1) printf(\"[*] No more valid Blocks found inside file! (maybe it was the last one)\\n\");\n\n        /* adjust total blocks length to end of file */\n        bh.total_length = filesize-pos;\n\n      }\n\n      if (bh.total_length < 12) {\n        printf(\"[-] Block too small ==> SKIPPING.\\n\");\n\n        /* reset input file pointer to next block */\n        fseeko(pcap, pos+bh.total_length, SEEK_SET);\n\n        continue;\n      }\n\n      if (verbose >= 1) printf(\"[*] Assuming this blocks size as %\" PRIu32 \" bytes.\\n\", bh.total_length);\n      else printf(\"[-] Invalid Block size => CORRECTED.\\n\");\n\n      /* reset input file pointer behind block header */\n      fseeko(pcap, pos+sizeof(struct block_header), SEEK_SET);\n\n      /* increase corruptions counter */\n      fixes++;\n    }\n\n    /* how many bytes are left until the final block size (end of block) is reached */\n    left = bh.total_length-sizeof(bh)-sizeof(check);\n\n    /* allocate memory for the new block - that will be written to repaired output file finally */\n    new_block = malloc(bh.total_length);\n\n    /* copy the current blocks header into repaired block */\n    memcpy(new_block, &bh, sizeof(bh));\n    block_pos = sizeof(bh);\n\n    /* what is the type of block at current position ? */\n    switch (bh.block_type) {\n\n      /* Section Header Block */\n      case TYPE_SHB:\n        if (verbose >= 1) printf(\"[*] FOUND: Section Header Block at position %\" FMT_OFF_T \" (%\" PRIu16 \" bytes)\\n\", pos, bh.total_length);\n\n        /* read section header block into struct */\n        bytes = fread(&shb, sizeof(shb), 1, pcap);\n        if (bytes != 1) return -3;\n        left -= sizeof(shb);\n\n        /* check for pcap's magic bytes () */\n        if (shb.byte_order_magic == BYTE_ORDER_MAGIC) {\n          if (verbose >= 1) printf(\"[+] Byte Order Magic: 0x%x\\n\", shb.byte_order_magic);\n        } else if (shb.byte_order_magic == htonl(BYTE_ORDER_MAGIC)) {\n          if (verbose >= 1) printf(\"[+] Byte Order Magic: 0x%x (SWAPPED)\\n\", shb.byte_order_magic);\n          swapped = 1;\n        } else {\n          printf(\"[-] Unknown Byte Order Magic: 0x%x ==> CORRECTED.\\n\", shb.byte_order_magic);\n          shb.byte_order_magic = BYTE_ORDER_MAGIC;\n          fixes++;\n        }\n\n        /* check for major version number (2) */\n        if (conshort(shb.major_version) == 1) {\t/* current major version is 2 */\n          if (verbose >= 1) printf(\"[+] Major version number: %hu\\n\", conshort(shb.major_version));\n        } else {\n          printf(\"[-] Major version number: %hu ==> CORRECTED.\\n\", conshort(shb.major_version));\n          shb.major_version = conshort(1);\n          fixes++;\n        }\n\n        /* check for minor version number */\n        if (conshort(shb.minor_version) == 0) {\t/* current minor version is 4 */\n          if (verbose >= 1) printf(\"[+] Minor version number: %hu\\n\", conshort(shb.minor_version));\n        } else {\n          printf(\"[-] Minor version number: %hu ==> CORRECTED.\\n\", conshort(shb.minor_version));\n          shb.minor_version = conshort(0);\n          fixes++;\n        }\n\n        /* section length */\n        if (shb.section_length == -1) {\n          if (verbose >= 1) printf(\"[*] Section length: %\" PRId64 \"\\n\", shb.section_length);\n\n        } else {\n          if (verbose >= 1) printf(\"[*] Section length: %\" PRId64 \" ==> SETTING TO -1\\n\", shb.section_length);\n          shb.section_length = -1;\n        }\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+sizeof(shb)) {\n          bh.total_length = block_pos+sizeof(shb);\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy section header block into repaired block */\n        memcpy(new_block+block_pos, &shb, sizeof(shb));\n        block_pos += sizeof(shb);\n\n        /* options */\n        count = 0 ;\n        while (left > 0) {\n          /* read option header into struct */\n          bytes = fread(&oh, sizeof(oh), 1, pcap);\n          if (bytes != 1) return -3;\n          left -= sizeof(oh);\n\n          /* which option did we get ? */\n          switch (oh.option_code) {\n            /* End of Options */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] OPTION: End of Options... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* Comment Option */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] OPTION: Comment... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* Hardware Information */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] OPTION: Hardware... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* Operating System Information */\n            case 0x03:\n              if (verbose >= 2) printf(\"[+] OPTION: Operating System... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* User Application Information */\n            case 0x04:\n              if (verbose >= 2) printf(\"[+] OPTION: Userappl... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n          }\n\n          /* Invalid Option? */\n          if (oh.option_code > 0x04) {\n            printf(\"[-] Unknown option code: 0x%04x (%\" PRIu16 \" bytes) ==> SKIPPING.\\n\", oh.option_code, oh.option_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* option is valid */\n\n          /* calculate padding for current option value */\n          padding = oh.option_length;\n          if (oh.option_length%4 != 0) padding += (4-oh.option_length%4);\n\n          /* check oversize */\n          if (padding > (unsigned)left) {\n            printf(\"[-] Option size (%\" FMT_OFF_T \") exceeds remaining block space (%\" FMT_OFF_T \"). ==> SKIPPING OPTION.\\n\", padding, left);\n            fixes++;\n\n            /* because this block oversizes, there should not be any further option */\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(oh)) {\n            bh.total_length = block_pos+sizeof(oh);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option header into repaired block */\n          memcpy(new_block+block_pos, &oh, sizeof(oh));\n          block_pos += sizeof(oh);\n\n          /* end of options? -> do not write any further */\n          if (oh.option_code == 0x00 && oh.option_length == 0x00) break;\n\n          /* read data of current option */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* write option data to repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n\n        }\n        break;\n\n      /* Packet Block */\n      case TYPE_PB:\n\tpackets++;\n\n        /* check oversize */\n        if (sizeof(pb) > (unsigned)left) {\n          printf(\"[-] Packet #%u exceeds size of block header (%zu > %\" FMT_OFF_T \") ==> SKIPPING.\\n\", packets, sizeof(pb), left);\n          /* set to \"invalid block\" */\n          bh.block_type = -1;\n          break;\n        }\n\n        /* check for the mandatory SBH that MUST be before any packet! */\n        if (shb_num == 0) {\n          /* no SBH before this packet, we NEED to create one */\n          printf(\"[-] No Section Block header found ==> CREATING.\\n\");\n          write_shb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          shb_num++;\n          fixes++;\n        }\n\n        if (verbose >= 1) printf(\"[*] FOUND Packet #%u: Packet Block at position %\" FMT_OFF_T \" (%\" PRIu16 \" bytes)\\n\", packets, pos, bh.total_length);\n\n        /* read packet block into struct */\n        bytes = fread(&pb, sizeof(pb), 1, pcap);\n        if (bytes != 1) return -3;\n        left -= sizeof(pb);\n\n        /* pre-check too large interface number (1024) */\n        if (pb.interface_id > 1024) {\n          /* interface id is unusal high --> this field is probably corrupted */\n          printf(\"[-] Probably corrupted Interface ID #%\" PRIu32 \" (too high?) ==> CORRECTED.\\n\", pb.interface_id);\n          pb.interface_id = 1;\n          fixes++;\n        }\n\n        /* check for the mandatory IDB that MUST identify every packets interface_id */\n        while (pb.interface_id >= idb_num) {\n          /* no IDB is identifying this packet, we need to create one - until the ID has been reached */\n          printf(\"[-] Missing IDB for Interface #%\" PRIu32 \" ==> CREATING (#%u).\\n\", pb.interface_id, idb_num);\n          write_idb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          idb_num++;\n          fixes++;\n        }\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+sizeof(pb)) {\n          bh.total_length = block_pos+sizeof(pb);\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy packet block into repaired block */\n        memcpy(new_block+block_pos, &pb, sizeof(pb));\n        block_pos += sizeof(pb);\n\n        /* check for oversized caplen */\n        if (pb.caplen > (unsigned)left) {\n          printf(\"[-] Capture length (%\" PRIu32 \") exceeds block size (%\" FMT_OFF_T \") ==> CORRECTED.\\n\", pb.caplen, left);\n          pb.caplen = left;\n        }\n\n        /* calculate padding for packet data */\n        padding = pb.caplen;\n        if (pb.caplen % 4 != 0) padding += (4 - pb.caplen % 4);\n\n        /* read packet data from input file */\n        data = malloc(padding);\n        bytes = fread(data, padding, 1, pcap);\n        left -= padding;\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+padding) {\n          bh.total_length = block_pos+padding;\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy packet data into repaired block */\n        memcpy(new_block+block_pos, data, padding);\n        block_pos += padding;\n\n        /* clean up memory */\n        free(data);\n\n        /* options */\n        count = 0;\n        while (left > 0) {\n\n          /* read options header */\n          bytes = fread(&oh, sizeof(oh), 1, pcap);\n          if (bytes != 1) return -3;\n          left -= sizeof(oh);\n\n          /* which option did we get ? */\n          switch (oh.option_code) {\n            /* End of Options */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] OPTION: End of Options... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* Comment Option */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] OPTION: Comment... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* Link Layer Flags */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] OPTION: Link Layer Flags... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n            /* Packet Hash */\n            case 0x03:\n              if (verbose >= 2) printf(\"[+] OPTION: Packet Hash... (%\" PRIu16 \" bytes)\\n\", oh.option_length);\n              break;\n          }\n\n          /* Invalid Option? */\n          if (oh.option_code > 0x03) {\n            printf(\"[-] Unknown option code: 0x%04\" PRIx16 \" (%\" PRIu16 \" bytes) ==> SKIPPING.\\n\", oh.option_code, oh.option_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* option is valid */\n\n          /* calculate padding for current option value */\n          padding = oh.option_length;\n          if (oh.option_length%4 != 0) padding += (4-oh.option_length%4);\n\n          /* check oversize */\n          if (padding > (unsigned)left) {\n            printf(\"[-] Option size (%\" FMT_OFF_T \") exceeds remaining block space (%\" FMT_OFF_T \"). ==> SKIPPING OPTION.\\n\", padding, left);\n            fixes++;\n\n            /* because this block oversizes, there should not be any further option */\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(oh)) {\n            bh.total_length = block_pos+sizeof(oh);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy options header into repaired block */\n          memcpy(new_block+block_pos, &oh, sizeof(oh));\n          block_pos += sizeof(oh);\n\n          /* end of options? -> do not write any further */\n          if (oh.option_code == 0x00 && oh.option_length == 0x00) break;\n\n          /* read data of current option */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option data to repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n        }\n        break;\n\n      /* Simple Packet Block */\n      case TYPE_SPB:\n\tpackets++;\n\n        /* check for the mandatory SBH that MUST be before any packet! */\n        if (shb_num == 0) {\n          /* no SBH before this packet, we NEED to create one */\n          printf(\"[-] No Section Block header found ==> CREATING.\\n\");\n          write_shb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          shb_num++;\n          fixes++;\n        }\n\n        if (verbose >= 1) printf(\"[*] FOUND Packet #%u: Simple Packet Block at position %\" FMT_OFF_T \" (%\" PRIu16 \" bytes)\\n\", packets, pos, bh.total_length);\n\n        /* read simple packet block */\n        bytes = fread(&spb, sizeof(spb), 1, pcap);\n        if (bytes != 1) return -3;\n        left -= sizeof(spb);\n\n        /* output data */\n        if (verbose >= 1) printf(\"[*] SPB original packet length: %u bytes\\n\", spb.len);\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+sizeof(spb)) {\n          bh.total_length = block_pos+sizeof(spb);\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy simple packet block into repaired file */\n        memcpy(new_block+block_pos, &spb, sizeof(spb));\n        block_pos += sizeof(spb);\n\n        /* calculate padding for packet data */\n        /* spb.len is NOT the length of packet inside file (origlen != caplen); we need to calculate caplen using block length (left) */\n        /* decrease by two to avoid oversize padding */\n        padding = left-2;\n        if (padding % 4 != 0) padding += (4 - left % 4);\n\n        /* read packet data from input file */\n        data = malloc(padding);\n        bytes = fread(data, padding, 1, pcap);\n        left -= padding;\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+padding) {\n          bh.total_length = block_pos+padding;\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy packet data into repaired block */\n        memcpy(new_block+block_pos, data, padding);\n        block_pos += padding;\n\n        /* clean up memory */\n        free(data);\n\n        break;\n\n      /* Interface Description Block */\n      case TYPE_IDB:\n\n        /* check for the mandatory SBH that MUST be before any packet! */\n        if (shb_num == 0) {\n          /* no SBH before this packet, we NEED to create one */\n          printf(\"[-] No Section Block header found ==> CREATING.\\n\");\n          write_shb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          shb_num++;\n          fixes++;\n        }\n\n        if (verbose >= 1) printf(\"[*] FOUND: Interface Description Block (%u bytes)\\n\", bh.total_length);\n\n        /* read interface description block */\n        bytes = fread(&idb, sizeof(idb), 1, pcap);\t/* read first bytes of input file into struct */\n        if (bytes != 1) return -3;\n        left -= sizeof(idb);\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+sizeof(idb)) {\n          bh.total_length = block_pos+sizeof(idb);\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy interface description block into repaired block */\n        memcpy(new_block+block_pos, &idb, sizeof(idb));\n        block_pos += sizeof(idb);\n\n        /* options */\n        count = 0;\n        while (left > 0) {\n\n          /* read options header */\n          bytes = fread(&oh, sizeof(oh), 1, pcap);\n          if (bytes != 1) return -3;\n          left -= sizeof(oh);\n\n          /* which option did we get? */\n          switch (oh.option_code) {\n            /* End of Options */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] OPTION: End of Options... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Comment Option */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] OPTION: Comment... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Interface Name */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] OPTION: Interface Name... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Interface Description */\n            case 0x03:\n              if (verbose >= 2) printf(\"[+] OPTION: Interface Description... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* IPv4 Address of Interface */\n            case 0x04:\n              if (verbose >= 2) printf(\"[+] OPTION: IPv4 Address... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* IPv6 Address of Interface */\n            case 0x05:\n              if (verbose >= 2) printf(\"[+] OPTION: IPv6 Address... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* MAC Address of Interface */\n            case 0x06:\n              if (verbose >= 2) printf(\"[+] OPTION: MAC Address... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* EUI Address of Interface */\n            case 0x07:\n              if (verbose >= 2) printf(\"[+] OPTION: EUI Address... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Interface Speed */\n            case 0x08:\n              if (verbose >= 2) printf(\"[+] OPTION: Interface Speed... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Resolution of Timestamps */\n            case 0x09:\n              if (verbose >= 2) printf(\"[+] OPTION: Resolution of Timestamps... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Timezone */\n            case 0x0a:\n              if (verbose >= 2) printf(\"[+] OPTION: Timezone... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Filter expression used */\n            case 0x0b:\n              if (verbose >= 2) printf(\"[+] OPTION: Filter expression... (%u bytes)\\n\",  oh.option_length);\n              break;\n            /* Operating System */\n            case 0x0c:\n              if (verbose >= 2) printf(\"[+] OPTION: Operating System... (%u bytes)\\n\",  oh.option_length);\n              break;\n            /* Frame Check Sequence Length */\n            case 0x0d:\n              if (verbose >= 2) printf(\"[+] OPTION: Frame Check Sequence Length... (%u bytes)\\n\",  oh.option_length);\n              break;\n            /* Timestamp Offset */\n            case 0x0e:\n              if (verbose >= 2) printf(\"[+] OPTION: Timestamp Offset... (%u bytes)\\n\",  oh.option_length);\n              break;\n          }\n\n          /* Invalid Option? */\n          if (oh.option_code > 0x0e) {\n            printf(\"[-] Unknown option code: 0x%04x (%u bytes) ==> SKIPPING.\\n\", oh.option_code, oh.option_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* option is valid */\n\n          /* calculate padding for current option value */\n          padding = oh.option_length;\n          if (oh.option_length%4 != 0) padding += (4-oh.option_length%4);\n\n          /* check oversize */\n          if (padding > (unsigned)left) {\n            printf(\"[-] Option size (%\" FMT_OFF_T \") exceeds remaining block space (%\" FMT_OFF_T \"). ==> SKIPPING OPTION.\\n\", padding, left);\n            fixes++;\n\n            /* because this block oversizes, there should not be any further option */\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(oh)) {\n            bh.total_length = block_pos+sizeof(oh);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy options header into repaired block */\n          memcpy(new_block+block_pos, &oh, sizeof(oh));\n          block_pos += sizeof(oh);\n\n          /* end of options? -> do not write any further*/\n          if (oh.option_code == 0x00 && oh.option_length == 0x00) break;\n\n          /* read option data */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* write option data into repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n        }\n        break;\n\n      /* Name Resolution Block */\n      case TYPE_NRB:\n\n        /* check for the mandatory SBH that MUST be before any packet! */\n        if (shb_num == 0) {\n          /* no SBH before this packet, we NEED to create one */\n          printf(\"[-] No Section Block header found ==> CREATING.\\n\");\n          write_shb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          shb_num++;\n          fixes++;\n        }\n\n        if (verbose >= 1) printf(\"[*] FOUND: Name Resolution Block at position %\" FMT_OFF_T \" (%\" PRIu16 \" bytes)\\n\", pos, bh.total_length);\n\n        /* process records */\n        count = 0;\n        while (left > 0) {\n\n          /* read name resolution block */\n          bytes = fread(&nrb, sizeof(nrb), 1, pcap);\t/* read first bytes of input file into struct */\n          if (bytes != 1) return -3;\n          left -= sizeof(nrb);\n\n          /* which type of record did we get? */\n          switch (nrb.record_type) {\n            /* End of Records */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] RECORD: End of Records... (%u bytes)\\n\", nrb.record_length);\n              break;\n            /* IPv4 Record */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] RECORD: IPv4 Record... (%u bytes)\\n\", nrb.record_length);\n              break;\n            /* IPv6 Record */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] RECORD: IPv6 Record... (%u bytes)\\n\", nrb.record_length);\n              break;\n          }\n\n          /* Invalid Record? */\n          if (nrb.record_type > 0x02) {\n            printf(\"[-] Unknown record type: 0x%04x (%u bytes) ==> SKIPPING.\\n\", nrb.record_type, nrb.record_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first record we check? */\n            if (count == 0) {\n              /* there are NO records inside this block; skipping EOR record */\n              if (verbose >= 1) printf(\"[*] No Records inside -> no need for End of Records...\\n\");\n              break;\n            }\n\n            /* there have been other records before this corruption, we need EOR record */\n\n            if (verbose >= 1) printf(\"[*] %u Records inside -> Finishing with End of Records...\\n\", count);\n\n            /* adjust option header to end of options */\n            nrb.record_type = 0x00;\n            nrb.record_length = 0x00;\n          }\n\n          /* record is valid */\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(nrb)) {\n            bh.total_length = block_pos+sizeof(nrb);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* write name resolution block into repaired block */\n          memcpy(new_block+block_pos, &nrb, sizeof(nrb));\n          block_pos += sizeof(nrb);\n\n          /* end of records? -> do not write any further */\n          if (nrb.record_type == 0x00 && nrb.record_length == 0x00) break;\n\n          /* calculate padding for current record value */\n          padding = nrb.record_length;\n          if (nrb.record_length % 4 != 0) padding += (4 - nrb.record_length % 4);\n\n          /* read record value from input file */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy record value into repaired buffer */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n\n        }\n\n        /* options */\n        count = 0;\n        while (left > 0) {\n\n          /* read options header */\n          bytes = fread(&oh, sizeof(oh), 1, pcap);\n          if (bytes != 1) return -3;\n          left -= sizeof(oh);\n\n          /* which option did we get? */\n          switch (oh.option_code) {\n            /* End of Options */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] OPTION: End of Options... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Comment Option */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] OPTION: Comment... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* DNS Server Name */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] OPTION: DNS Server... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* DNS Server IPv4 Address */\n            case 0x03:\n              if (verbose >= 2) printf(\"[+] OPTION: IPv4 Address of DNS Server... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* DNS Server IPv6 Address */\n            case 0x04:\n              if (verbose >= 2) printf(\"[+] OPTION: IPv6 Address of DNS Server... (%u bytes)\\n\", oh.option_length);\n              break;\n          }\n\n          /* Invalid Option? */\n          if (oh.option_code > 0x04) {\n            printf(\"[-] Unknown option code: 0x%04x (%u bytes) ==> SKIPPING.\\n\", oh.option_code, oh.option_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* option is valid */\n\n          /* calculate padding for current option value */\n          padding = oh.option_length;\n          if (oh.option_length%4 != 0) padding += (4-oh.option_length%4);\n\n          /* check oversize */\n          if (padding > (unsigned)left) {\n            printf(\"[-] Option size (%\" FMT_OFF_T \") exceeds remaining block space (%\" FMT_OFF_T \"). ==> SKIPPING OPTION.\\n\", padding, left);\n            fixes++;\n\n            /* because this block oversizes, there should not be any further option */\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(oh)) {\n            bh.total_length = block_pos+sizeof(oh);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option header into repaired block */\n          memcpy(new_block+block_pos, &oh, sizeof(oh));\n          block_pos += sizeof(oh);\n\n          /* end of options? -> do not write any further */\n          if (oh.option_code == 0x00 && oh.option_length == 0x00) break;\n\n          /* read option value from input file */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option value into repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n\n        }\n        break;\n\n      /* Interface Statistics Block */\n      case TYPE_ISB:\n\n        /* check for the mandatory SBH that MUST be before any packet! */\n        if (shb_num == 0) {\n          /* no SBH before this packet, we NEED to create one */\n          printf(\"[-] No Section Block header found ==> CREATING.\\n\");\n          write_shb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          shb_num++;\n          fixes++;\n        }\n\n        if (verbose >= 1) printf(\"[*] FOUND: Interface Statistics Block at position %\" FMT_OFF_T \" (%\" PRIu16 \" bytes)\\n\", pos, bh.total_length);\n\n        /* read interface statistics block */\n        bytes = fread(&isb, sizeof(isb), 1, pcap);\n        if (bytes != 1) return -3;\n        left -= sizeof(isb);\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+sizeof(isb)) {\n          bh.total_length = block_pos+sizeof(isb);\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy interface statistics block into repaired block */\n        memcpy(new_block+block_pos, &isb, sizeof(isb));\n        block_pos += sizeof(isb);\n\n        /* options */\n        count = 0;\n        while (left > 0) {\n\n          /* read options header */\n          bytes = fread(&oh, sizeof(oh), 1, pcap);\n          if (bytes != 1) return -3;\n          left -= sizeof(oh);\n\n          /* which option did we get? */\n          switch (oh.option_code) {\n            /* End of Options */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] OPTION: End of Options... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Comment Option */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] OPTION: Comment... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Capture Start Time */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] OPTION: Capture Start Time... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Capture End Time */\n            case 0x03:\n              if (verbose >= 2) printf(\"[+] OPTION: Capture End Time... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Packets received */\n            case 0x04:\n              if (verbose >= 2) printf(\"[+] OPTION: Packets received... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Packets dropped */\n            case 0x05:\n              if (verbose >= 2) printf(\"[+] OPTION: Packets dropped... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Packets accepted by Filter */\n            case 0x06:\n              if (verbose >= 2) printf(\"[+] OPTION: Filter packets accepted... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Packets dropped by Operating System */\n            case 0x07:\n              if (verbose >= 2) printf(\"[+] OPTION: Packets dropped by OS... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Packets delivered to user */\n            case 0x08:\n              if (verbose >= 2) printf(\"[+] OPTION: Packets delivered to user... (%u bytes)\\n\", oh.option_length);\n              break;\n          }\n\n          /* Invalid Option? */\n          if (oh.option_code > 0x08) {\n            printf(\"[-] Unknown option code: 0x%04x (%u bytes) ==> SKIPPING.\\n\", oh.option_code, oh.option_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* option is valid */\n\n          /* calculate padding for current option value */\n          padding = oh.option_length;\n          if (oh.option_length%4 != 0) padding += (4-oh.option_length%4);\n\n          /* check oversize */\n          if (padding > (unsigned)left) {\n            printf(\"[-] Option size (%\" FMT_OFF_T \") exceeds remaining block space (%\" FMT_OFF_T \"). ==> SKIPPING OPTION.\\n\", padding, left);\n            fixes++;\n\n            /* because this block oversizes, there should not be any further option */\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(oh)) {\n            bh.total_length = block_pos+sizeof(oh);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy options header into repaired block */\n          memcpy(new_block+block_pos, &oh, sizeof(oh));\n          block_pos += sizeof(oh);\n\n          /* end of options? -> do not write any further */\n          if (oh.option_code == 0x00 && oh.option_length == 0x00) break;\n\n          /* read option value from input file */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option value into repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n        }\n        break;\n\n      /* Enhanced Packet Block */\n      case TYPE_EPB:\n\tpackets++;\n\n        /* check for the mandatory SBH that MUST be before any packet! */\n        if (shb_num == 0) {\n          /* no SBH before this packet, we NEED to create one */\n          printf(\"[-] No Section Block header found ==> CREATING.\\n\");\n          write_shb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          shb_num++;\n          fixes++;\n        }\n\n        if (verbose >= 1) printf(\"[*] FOUND Packet #%u: Enhanced Packet Block at position %\" FMT_OFF_T \" (%\" PRIu16 \" bytes)\\n\", packets, pos, bh.total_length);\n\n        /* read enhanced packet block */\n        bytes = fread(&epb, sizeof(epb), 1, pcap);\n        if (bytes != 1) return -3;\n        left -= sizeof(epb);\n\n        /* pre-check too large interface number (1024) */\n        if (epb.interface_id > 1024) {\n          /* interface id is unusal high --> this field is probably corrupted */\n          printf(\"[-] Probably corrupted Interface ID #%u (too high?) ==> CORRECTED.\\n\", epb.interface_id);\n          epb.interface_id = 1;\n          fixes++;\n        }\n\n        /* check for the mandatory IDB that MUST identify every packets interface_id */\n        while (epb.interface_id >= idb_num) {\n          /* no IDB identifying this packet, we need to create one - until the ID is reached */\n          printf(\"[-] Missing IDB for Interface #%u ==> CREATING (#%u).\\n\", epb.interface_id, idb_num);\n          write_idb(pcap_fix, writebuffer, &writepos);\n\n          /* increase counters */\n          idb_num++;\n          fixes++;\n        }\n\n        /* check if packet capture size exceeds packet length */\n        if (epb.caplen > epb.len) {\n          printf(\"[-] Enhanced packet data exceeds packet capture length (%u > %u) ==> CORRECTED.\\n\", epb.caplen, epb.len);\n          epb.caplen = epb.len;\n\n          fixes++;\n        }\n\n        /* check if packet capture size exceeds packet length */\n        if (epb.caplen > left) {\n          printf(\"[-] Enhanced packet data exceeds total packet size (%\" PRIu32 \" > %\" FMT_OFF_T \") ==> CORRECTED.\\n\", epb.caplen, left);\n          epb.caplen = left;\n\n          fixes++;\n        }\n\n        /* check if enough space is aligned in memory block */\n        if (bh.total_length < block_pos+sizeof(epb)) {\n          bh.total_length = block_pos+sizeof(epb);\n          printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n          new_block = realloc(new_block, bh.total_length);\n          memcpy(new_block, &bh, sizeof(bh));\n          fixes++;\n        }\n\n        /* copy enhanced packet block into repaired buffer */\n        memcpy(new_block+block_pos, &epb, sizeof(epb));\n        block_pos += sizeof(epb);\n\n        /* check for zero capture length */\n        if (epb.caplen != 0) {\n\n          /* calculate padding for packet data */\n          padding = epb.caplen;\n          if (epb.caplen % 4 != 0) padding += (4 - epb.caplen % 4);\n\n          /* read packet data from input file */\n          data = malloc(padding);\n\n          bytes = fread(data, padding, 1, pcap);\n          if (bytes != 1) return -3;\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy packet data into repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n        }\n\n        /* options */\n        count = 0;\n        while (left > 0) {\n\n          /* read option header */\n          bytes = fread(&oh, sizeof(oh), 1, pcap);\n          if (bytes != 1) return -3;\n          left -= sizeof(oh);\n\n          /* which option did we get? */\n          switch (oh.option_code) {\n            /* End of Options */\n            case 0x00:\n              if (verbose >= 2) printf(\"[+] OPTION: End of Options... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Comment Option */\n            case 0x01:\n              if (verbose >= 2) printf(\"[+] OPTION: Comment... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Link Layer Flags */\n            case 0x02:\n              if (verbose >= 2) printf(\"[+] OPTION: Link Layer Flags... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Packet Hash */\n            case 0x03:\n              if (verbose >= 2) printf(\"[+] OPTION: Packet Hash... (%u bytes)\\n\", oh.option_length);\n              break;\n            /* Dropped Packets */\n            case 0x04:\n              if (verbose >= 2) printf(\"[+] OPTION: Dropped Packets Counter... (%u bytes)\\n\", oh.option_length);\n              break;\n          }\n\n          /* Invalid Option? */\n          if (oh.option_code > 0x04) {\n            printf(\"[-] Unknown option code: 0x%04x (%u bytes) ==> SKIPPING.\\n\", oh.option_code, oh.option_length);\n\n            /* increase corruptions counter */\n            fixes++;\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* option is valid */\n\n          /* calculate padding for current option value */\n          padding = oh.option_length;\n          if (oh.option_length%4 != 0) padding += (4-oh.option_length%4);\n\n          /* check oversize */\n          if (padding > (unsigned)left) {\n            printf(\"[-] Option size (%\" FMT_OFF_T \") exceeds remaining block space (%\" FMT_OFF_T \"). ==> SKIPPING OPTION.\\n\", padding, left);\n            fixes++;\n\n            /* because this block oversizes, there should not be any further option */\n\n            /* is this the first option we check? */\n            if (count == 0) {\n              /* there are NO options inside this block; skipping EOO option */\n              if (verbose >= 1) printf(\"[*] No Options inside -> no need for End of Options...\\n\");\n              break;\n            }\n\n            /* there have been other options before this corruption, we need EOO option */\n\n            if (verbose >= 1) printf(\"[*] %u Options inside -> Finishing with End of Options...\\n\", count);\n\n            /* adjust option header to end of options */\n            oh.option_code = 0x00;\n            oh.option_length = 0x00;\n          }\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+sizeof(oh)) {\n            bh.total_length = block_pos+sizeof(oh);\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option header into repaired block */\n          memcpy(new_block+block_pos, &oh, sizeof(oh));\n          block_pos += sizeof(oh);\n\n          /* end of options? -> do not write any further */\n          if (oh.option_code == 0x00 && oh.option_length == 0x00) break;\n\n          /* read option value from input file */\n          data = malloc(padding);\n          bytes = fread(data, padding, 1, pcap);\n          left -= padding;\n\n          /* check if enough space is aligned in memory block */\n          if (bh.total_length < block_pos+padding) {\n            bh.total_length = block_pos+padding;\n            printf(\"[-] Given block total length is too small ==> FIXED (%\" PRIu32 \")\\n\", bh.total_length);\n            new_block = realloc(new_block, bh.total_length);\n            memcpy(new_block, &bh, sizeof(bh));\n            fixes++;\n          }\n\n          /* copy option value into repaired block */\n          memcpy(new_block+block_pos, data, padding);\n          block_pos += padding;\n\n          /* clean up memory */\n          free(data);\n\n          count++;\n        }\n        break;\n\n    } /* end of switch - block header */\n\n    /* check for invalid block header type */\n    if ((bh.block_type != TYPE_SHB && bh.block_type > TYPE_EPB) || bh.block_type == 0x00000000) {\n      /* this block type is ńot know */\n\n      printf(\"[-] Unknown block type!: 0x%08x ==> SKIPPING.\\n\", bh.block_type);\n\n      /* increase corruption counter */\n      fixes++;\n\n      free(new_block);\n\n    } else {\n      /* this block type is valid */\n\n      /* write sizes of block header to correct positions */\n      block_pos += sizeof(bh.total_length);\n\n      /* check size of block */\n      if (bh.total_length < block_pos) {\n        if (verbose >= 2) printf(\"[*] Increasing block buffer to %u\\n\", block_pos);\n        tmpbuf = malloc(block_pos);\n        memcpy(tmpbuf, new_block, bh.total_length);\n        free(new_block);\n        new_block = tmpbuf;\n        bh.total_length = block_pos;\n      }\n\n      memcpy(new_block+4, &block_pos, sizeof(bh.total_length));\n      memcpy(new_block+block_pos-4, &block_pos, sizeof(bh.total_length));\n\n      /* check wether the real size matches the size formerly specified in block header */\n      if (block_pos != bh.total_length) {\n\n        /* specified size in block header does NOT match the real block size (maybe due to fixed corruptions) */\n        if (verbose >= 1) printf(\"[*] Block size adjusted (%u --> %u).\\n\", bh.total_length, block_pos);\n\n        /* increase corruption counter */\n        fixes++;\n      }\n\n      /* write repaired block into output file */\n      if (verbose >= 2) printf(\"[*] Writing block to buffer (%u bytes).\\n\", block_pos);\n\n      /* do we need to write the buffer to the file? */\n      if (writepos + block_pos > 1024000) {\n        bytes = fwrite(writebuffer, writepos, 1, pcap_fix);\n        writepos = 0;\n      }\n\n      /* check if writebuffer is large enough */\n      if (block_pos > 1024000) {\n        tmpbuf = malloc(block_pos);\n        memcpy(tmpbuf, writebuffer, 1024000);\n        free(writebuffer);\n        writebuffer = tmpbuf;\n      }\n\n      /* put new bytes into write buffer */\n      memcpy(writebuffer+writepos, new_block, block_pos);\n      writepos += block_pos;\n\n      free(new_block);\n\n      /* increate SHB / IDB counters */\n      if (bh.block_type == TYPE_SHB) shb_num++;\n      if (bh.block_type == TYPE_IDB) idb_num++;\n    }\n\n    /* did we process all bytes of the block - given by block length */\n    if (left == 0) {\n      /* all bytes processed */\n      if (verbose >= 2) printf(\"[+] End of Block reached... byte counter is correct!\\n\");\n    } else {\n      /* we did not read until end of block - maybe due to option skipping */\n      if (verbose >= 1) printf(\"[-] Did not hit the end of the block! (%\" FMT_OFF_T \" bytes left)\\n\", left);\n    }\n\n    /* check for correct block end (block size) */\n    bytes = fread(&check, sizeof(check), 1, pcap);\n\n    /* read the second block length field and check first block size field */\n    if (check == bh.total_length) {\n      /* first and second block header size do match */\n      if (verbose >= 2) printf(\"[+] Block size matches (%u)!\\n\", check);\n    } else {\n      /* block header sizes do not match! */\n\n      printf(\"[-] Block size mismatch (0x%08x != 0x%08x) ==> CORRECTED.\\n\", check, bh.total_length);\n      fixes++;\n\n      /* we did not hit the end of block - need to search for next one */\n\n      /* remeber current position to know how much bytes have been skipped */\n      bytes = ftello(pcap);\n\n      if (bytes != filesize) {\n\n        /* search for next valid block */\n        if (verbose >= 1) printf(\"[*] Trying to align next block...\\n\");\n        res = find_valid_block(pcap, filesize);\n\n        /* output information about overlapped/skipped bytes */\n        if (ftello(pcap) > (unsigned)bytes) printf(\"[-] Found %\" FMT_OFF_T \" bytes of unknown data ==> SKIPPING.\\n\", ftello(pcap)-bytes);\n        else printf(\"[-] Packet overlapps with %\" FMT_OFF_T \" bytes ==> CORRECTED.\\n\", bytes-ftello(pcap));\n\n        /* increase corruption counter */\n        fixes++;\n\n        /* did we find a next block at all? */\n        if (res == -1) {\n          /* EOF reached while searching --> no more blocks */\n          if (verbose >= 1) printf(\"[*] No more valid blocks found inside file! (maybe it was the last one)\\n\");\n          break;\n        }\n\n      }\n\n    }\n\n    /* set positon of next block */\n    pos = ftello(pcap);\n\n  }\n\n  /* write remaining data into buffer */\n  bytes = fwrite(writebuffer, writepos, 1, pcap_fix);\n  writepos = 0;\n\n  /* FILE HAS BEEN COMPLETELY CHECKED */\n  free(writebuffer);\n\n  /* did we write any SHB blocks at all?\n   * if not this seems to be no pcapng file! */\n  if (shb_num == 0) return(-1);\n\n  /* everything successfull - return number of fixes */\n  return(fixes);\n}\n\n/*\n * Function:  find_valid_block\n * ---------------------------\n * searches for the next valid block beginning at current file pointer position\n *\n * pcap:      file pointer to input file\n * filesize:  size of input file in bytes\n *\n * returns:  0   success (next block header has been found, file pointer is set to start of block)\n *          -1   error (reached EOF without finding a valid block)\n *\n */\nint find_valid_block(FILE *pcap, off_t filesize) {\n  off_t i;\n  unsigned int bytes;\n  unsigned int check;                       /* variable to check end of blocks sizes */\n  struct block_header bh;                   /* block header */\n  struct packet_block pb;                   /* Packet Block */\n  struct name_resolution_block nrb;         /* Name Resolution Block */\n  struct simple_packet_block spb;           /* Simple Packet Block */\n\n  /* bytewise processing of input file */\n  for (i=ftello(pcap)-4; i<filesize; i++) {\n    /* set file pointer to loop position */\n    fseeko(pcap, i, SEEK_SET);\n\n    /* read possbile block header */\n    bytes = fread(&bh, sizeof(bh), 1, pcap);\n    if (bytes != 1) return(-1);\n\n    /* check if:\n     * - block header is greater than minimal size (12)\n     * - block header type has a valid ID */\n    if (bh.total_length >= 12 && bh.block_type >= TYPE_IDB && bh.block_type <= TYPE_EPB) {\n      /* block header might be valid */\n\n      /* perform some block specific checks */\n\n      /* Packet Block Checks:\n       * - interface id <= 1024 */\n      if (bh.block_type == TYPE_PB) {\n        bytes = fread(&pb, sizeof(pb), 1, pcap);\n        if (bytes != 1) return(-1);\n\n        /* interface id check */\n        if (pb.interface_id > 1024) continue;\n      }\n\n      /* Simple Packet Block Checks:\n       * - max size <= MAX_SNAPLEN */\n      if (bh.block_type == TYPE_SPB) {\n        /* max size check */\n        if (bh.total_length > PCAPNG_MAX_SNAPLEN) continue;\n\n        bytes = fread(&spb, sizeof(spb), 1, pcap);\n        if (bytes != 1) return(-1);\n\n        /* check original packet lengths <= MAX_SNAPLEN */\n        if (spb.len > PCAPNG_MAX_SNAPLEN) continue;\n      }\n\n      /* Name Resolution Block Checks:\n       * - min size >= 16\n         - record size < block length\n         - record type ipv4,ipv6 or eeo */\n      if (bh.block_type == TYPE_NRB) {\n        bytes = fread(&nrb, sizeof(nrb), 1, pcap);\n        if (bytes != 1) return(-1);\n\n        /* max length check */\n        if (bh.total_length < 16) continue;\n\n        /* record length check */\n        if (nrb.record_length > bh.total_length) continue;\n\n        /* record type check (max is 0x02) */\n        if (nrb.record_type > 0x02) continue;\n      }\n\n      /* check if the second size value is valid too */\n      fseeko(pcap, i+bh.total_length-4, SEEK_SET);\n      bytes = fread(&check, sizeof(check), 1, pcap);\n      if (check == bh.total_length) {\n        /* also the second block size value is correct! */\n\n        if (verbose >= 1) printf(\"[+] FOUND: Block (Type: 0x%08\" PRIx32 \", Length: %u) at Position %\" FMT_OFF_T \"\\n\", bh.block_type, bh.total_length, i);\n\n        /* set pointer to next block position */\n        fseeko(pcap, i, SEEK_SET);\n        return(0);\n      }\n    }\n  }\n\n  /* finished loop without success -> no more blocks inside file */\n  return(-1);\n}\n\n/*\n * Function:  write_shb\n * --------------------\n * creates a raw section header block (SHB) and writes it into output file\n * (there will be no information inside except that it has been added by pcapfix)\n *\n * pcap_fix:  file pointer to output file\n *\n * returns:  0   success (new shb has been written to output file)\n *          -1   error (cannot write to output file)\n *\n */\nint write_shb(FILE *pcap_fix, char* writebuffer, off_t* writepos) {\n  struct block_header bh;           /* block header */\n  struct section_header_block shb;  /* section header block */\n  struct option_header oh;          /* options header */\n\n  off_t bytes;              /* written bytes/blocks counter */\n  unsigned int size = 0;            /* size of whole block */\n  unsigned int padding;             /* padding of data */\n  unsigned char *data;              /* data buffer */\n\n  /* this comment will be added to options to indicate that block has been arbitrary added\n   * we pad string with max of 4 zero bytes to ahjust memory alignment */\n  char comment[] = \"Added by pcapfix.\\x00\\x00\\x00\\x00\";\n\n  /* set block type to section header block */\n  bh.block_type = TYPE_SHB;\n\n  /* increase total size by block header size */\n  size += sizeof(struct block_header);\n\n  /* fill section header block with valid values */\n  shb.byte_order_magic = BYTE_ORDER_MAGIC;    /* we use a non-swapped BYTE_ORDER */\n  shb.major_version = 1;                      /* major pcapng version is 1 */\n  shb.minor_version = 0;                      /* minor pcapng version is 0 */\n\n  /* increase total size by section header block size */\n  size += sizeof(struct section_header_block);\n\n  /* prepare options header */\n  oh.option_code = 0x01;                /* this is a comment option */\n  oh.option_length = strlen(comment);   /* size equals the definied comment */\n\n  /* increase total size by options header size */\n  size += sizeof(struct option_header);\n\n  /* calculate padding for this options data */\n  padding = oh.option_length;\n  if (oh.option_length % 4 != 0) padding += (4 - oh.option_length % 4);\n\n  /* increase total size by options data size (including padding) */\n  size += padding;\n\n  /* increase size by 4 (end of options) */\n  size += 4;\n\n  /* increase size by 4 (second block_length field) */\n  size += 4;\n\n  /* set final size into block header field */\n  bh.total_length = size;\n\n  /* reserve memory for whole section header block (including block header) */\n  data = malloc(size);\n\n  /* store block header into buffer */\n  memcpy(data, &bh, sizeof(bh));\n  /* store section header block (header) into buffer */\n  memcpy(data+sizeof(bh), &shb, sizeof(shb));\n  /* store options header into buffer */\n  memcpy(data+sizeof(bh)+sizeof(shb), &oh, sizeof(oh));\n  /* store option data into buffer */\n  memcpy(data+sizeof(bh)+sizeof(shb)+sizeof(oh), comment, padding);\n  /* store end of options into buffer */\n  memset(data+sizeof(bh)+sizeof(shb)+sizeof(oh)+padding, 0, 4);\n  /* store second block_length field into buffer */\n  memcpy(data+sizeof(bh)+sizeof(shb)+sizeof(oh)+padding+4, &size, sizeof(size));\n\n  /* write whole buffer (new SHB) into buffer */\n\n  // check if there is enough space in buffer\n  if (*writepos + size > 1024000) {\n    bytes = fwrite(writebuffer, *writepos, 1, pcap_fix);\n    if (bytes != 1) return(-1);\n    *writepos = 0;\n  }\n\n  // put new bytes into write buffer\n  memcpy(writebuffer+(*writepos), data, size);\n  *writepos += size;\n\n  /* clean up memory */\n  free(data);\n\n  /* success */\n  return(0);\n}\n\n/*\n * Function:  write_idb\n * --------------------\n * creates a raw interface description block (IDB) and writes it into output file\n * (there will be no information inside except that it has been added by pcapfix)\n *\n * pcap_fix:  file pointer to output file\n *\n * returns:  0   success (new shb has been written to output file)\n *          -1   error (cannot write to output file)\n *\n */\nint write_idb(FILE *pcap_fix, char* writebuffer, off_t* writepos) {\n  struct block_header bh;                   /* block header */\n  struct interface_description_block idb;   /* interface description block */\n  struct option_header oh;                  /* options header */\n\n  off_t bytes;                      /* written bytes/blocks counter */\n  unsigned int size = 0;            /* size of whole block */\n  unsigned int padding;             /* padding of data */\n  unsigned char *data;              /* data buffer */\n\n  /* this comment will be added to options to indicate that block has been arbitrary added\n   * we pad string with max of 4 zero bytes to ahjust memory alignment */\n  char comment[] = \"Added by pcapfix.\\x00\\x00\\x00\\x00\";\n\n  /* set block type to interface description block */\n  bh.block_type = TYPE_IDB;\n\n  /* increase total size by block header size */\n  size += sizeof(struct block_header);\n\n  /* fill interface description block with valid values */\n\n  /* data link type */\n  if (data_link_type != -1) {\n    idb.linktype = data_link_type;  /* link layter type as set by user */\n  } else {\n    idb.linktype = 1;               /* link layter type to default (1 == ETHERNET) */\n  }\n\n  /* reserved is always zero */\n  idb.reserved = 0;\n\n  /* we set snaplen to maximum */\n  idb.snaplen = PCAPNG_MAX_SNAPLEN;\n\n  /* increase total size by interface desciption block (header) */\n  size += sizeof(struct interface_description_block);\n\n  /* prepare options header */\n  oh.option_code = 0x01;                /* this is a comment option */\n  oh.option_length = strlen(comment);   /* size equals the definied comment */\n\n  /* increase total size by options header size */\n  size += sizeof(struct option_header);\n\n  /* calculate padding for this options data */\n  padding = oh.option_length;\n  if (oh.option_length % 4 != 0) padding += (4 - oh.option_length % 4);\n\n  /* increase total size by options data size (including padding) */\n  size += padding;\n\n  /* increase size by 4 (end of options) */\n  size += 4;\n\n  /* increase size by 4 (second block_length field) */\n  size += 4;\n\n  /* set final size into block header field */\n  bh.total_length = size;\n\n  /* reserve memory for whole section header block (including block header) */\n  data = malloc(size);\n\n  /* store block header into buffer */\n  memcpy(data, &bh, sizeof(bh));\n  /* store interface description block (header) into buffer */\n  memcpy(data+sizeof(bh), &idb, sizeof(idb));\n  /* store options header into buffer */\n  memcpy(data+sizeof(bh)+sizeof(idb), &oh, sizeof(oh));\n  /* store option data into buffer */\n  memcpy(data+sizeof(bh)+sizeof(idb)+sizeof(oh), comment, padding);\n  /* store end of options into buffer */\n  memset(data+sizeof(bh)+sizeof(idb)+sizeof(oh)+padding, 0, 4);\n  /* store second block_length field into buffer */\n  memcpy(data+sizeof(bh)+sizeof(idb)+sizeof(oh)+padding+4, &size, sizeof(size));\n\n  /* write whole buffer (new SHB) into output file */\n\n  // check if there is enough space in buffer\n  if (*writepos + size > 1024000) {\n    bytes = fwrite(writebuffer, *writepos, 1, pcap_fix);\n    if (bytes != 1) return(-1);\n    *writepos = 0;\n  }\n\n  // put new bytes into write buffer\n  memcpy(writebuffer+(*writepos), data, size);\n  *writepos += size;\n\n  /* clean up memory */\n  free(data);\n\n  /* success */\n  return(0);\n}\n"
  },
  {
    "path": "pcapng.h",
    "content": "/*******************************************************************************\n *\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\n *\n * This file is part of Pcapfix.\n *\n * Pcapfix is free software: you can redistribute it and/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation, either version 3 of the License, or any later version.\n *\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along with\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\n *\n ******************************************************************************/\n\n#ifndef PF_PCAPNG\n#define PF_PCAPNG\n\n/* http://www.winpcap.org/ntar/draft/PCAP-DumpFileFormat.html */\n/* http://wiki.wireshark.org/Development/PcapNg */\n\n#define BYTE_ORDER_MAGIC 0x1a2b3c4d /* pcapng default byte order magic - non swapped */\n\n#define TYPE_SHB 0x0A0D0D0A         /* Section Header Block */\n#define TYPE_IDB 0x00000001         /* Interface Description Block */\n#define TYPE_PB  0x00000002         /* Packet Block */\n#define TYPE_SPB 0x00000003         /* Simple Packet Block */\n#define TYPE_NRB 0x00000004         /* Name Resolution Block */\n#define TYPE_ISB 0x00000005         /* Interface Statistics Block */\n#define TYPE_EPB 0x00000006         /* Enhanced Packet Block */\n\n#define PCAPNG_MAX_SNAPLEN 262144   /* maximum snap length */\n\n/*\n * Function:  fix_pcapng\n * ---------------------\n * tries to fix a pcapng file\n *\n * pcap:      file pointer to input file\n * pcap_fix:  file pointer to output file\n *\n * returns: >0   success (number of corruptions fixed)\n *           0   success (nothing to fix)\n *          -1   error (not a pcap file)\n *          -2   error (unable to repair)\n *          -3   error (EOF while reading input file)\n *\n */\nint fix_pcapng(FILE *pcap, FILE *pcap_fix);\n\n/*\n * Function:  find_valid_block\n * ---------------------------\n * searches for the next valid block beginning at current file pointer position\n *\n * pcap:      file pointer to input file\n * filesize:  size of input file in bytes\n *\n * returns:  0   success (next block header has been found, file pointer is set to start of block)\n *          -1   error (reached EOF without finding a valid block)\n *\n */\nint find_valid_block(FILE *pcap, off_t filesize);\n\n/*\n * Function:  write_shb\n * --------------------\n * creates a raw section header block (SHB) and writes it into output file\n * (there will be no information inside except that it has been added by pcapfix)\n *\n * pcap_fix:  file pointer to output file\n *\n * returns:  0   success (new shb has been written to output file)\n *          -1   error (cannot write to output file)\n *\n */\nint write_shb(FILE *pcap_fix, char* writebuffer, off_t* writepos);\n\n/*\n * Function:  write_idb\n * --------------------\n * creates a raw interface description block (IDB) and writes it into output file\n * (there will be no information inside except that it has been added by pcapfix)\n *\n * pcap_fix:  file pointer to output file\n *\n * returns:  0   success (new shb has been written to output file)\n *          -1   error (cannot write to output file)\n *\n */\nint write_idb(FILE *pcap_fix, char* writebuffer, off_t* writepos);\n\n#endif\n"
  },
  {
    "path": "winfunc.c",
    "content": "/*******************************************************************************\r\n *\r\n * Copyright (c) 2012-2021 Robert Krause (ruport@f00l.de)\r\n *\r\n * This file is part of Pcapfix.\r\n *\r\n * Pcapfix is free software: you can redistribute it and/or modify it under the\r\n * terms of the GNU General Public License as published by the Free Software\r\n * Foundation, either version 3 of the License, or any later version.\r\n *\r\n * Pcapfix is distributed in the hope that it will be useful, but WITHOUT ANY\r\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU General Public License along with\r\n * Pcapfix. If not, see http://www.gnu.org/licenses/.\r\n *\r\n ******************************************************************************/\r\n\r\n#include \"pcapfix.h\"\r\n\r\n#include <fcntl.h>\r\n\r\n/* truncate does not exist under windows */\r\nint truncate(const char *pathname, _off_t len){\r\n  int ret, err;\r\n  int fd = _open(pathname,_O_BINARY|_O_RDWR);\r\n  if (fd == -1) return fd;\r\n  ret = ftruncate(fd,len);\r\n  _close(fd);\r\n  return ret;\r\n}\r\n"
  }
]