[
  {
    "path": ".github/FUNDING.yml",
    "content": "ko_fi: thelazza\n"
  },
  {
    "path": ".gitignore",
    "content": "### Code ###\n.vscode/*\n!.vscode/tasks.json\n!.vscode/launch.json\n*.code-workspace\n\n### Python ###\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\npytestdebug.log\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\ndoc/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\npythonenv*\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# profiling data\n.prof\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       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                            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                       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                     END OF TERMS AND CONDITIONS\n\n            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    {project}  Copyright (C) {year}  {fullname}\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"
  },
  {
    "path": "README.md",
    "content": "\n\n# ![RecuperaBit](http://i.imgur.com/Q6mM385.jpg)\n\n<p><a class=\"badge-chip\" href=\"https://github.com/Lazza/RecuperaBit/blob/master/LICENSE.md\"><img alt=\"GPL-3.0 license\" src=\"https://badgen.net/github/license/Lazza/RecuperaBit\"></a>\n<a class=\"badge-chip\" href=\"https://github.com/Lazza/RecuperaBit/releases\"><img alt=\"Latest release\" src=\"https://badgen.net/github/release/Lazza/RecuperaBit\"></a>\n<a class=\"badge-chip\" href=\"https://github.com/Lazza/RecuperaBit/stargazers\"><img alt=\"Stars counter\" src=\"https://badgen.net/github/stars/Lazza/RecuperaBit\"></a>\n<a class=\"badge-chip\" href=\"https://project-types.github.io/#stadium\"><img alt=\"Stadium badge\" src=\"https://badgen.net/static/project type/stadium/orange\"></a>\n<a class=\"badge-chip\" href=\"https://ko-fi.com/thelazza\"><img alt=\"Donate on Ko-fi\" src=\"https://badgen.net/static/ko-fi/donate/yellow\"></a></p>\n\nA software which attempts to reconstruct file system structures and recover\nfiles. Currently it supports only NTFS.\n\nRecuperaBit attempts reconstruction of the directory structure regardless of:\n\n- missing partition table\n- unknown partition boundaries\n- partially-overwritten metadata\n- quick format\n\nYou can get more information about **the reconstruction algorithms** and the\narchitecture used in RecuperaBit by reading\n[my MSc thesis](https://www.scribd.com/doc/309337813/) or checking out [the\nslides](http://www.slideshare.net/TheLazza/recuperabit-forensic-file-system-reconstruction-given-partially-corrupted-metadata).\n\n## Usage\n\n    usage: main.py [-h] [-s SAVEFILE] [-w] [-o OUTPUTDIR] path\n\n    Reconstruct the directory structure of possibly damaged filesystems.\n\n    positional arguments:\n      path                  path to the disk image\n\n    optional arguments:\n      -h, --help            show this help message and exit\n      -s SAVEFILE, --savefile SAVEFILE\n                            path of the scan save file\n      -w, --overwrite       force overwrite of the save file\n      -o OUTPUTDIR, --outputdir OUTPUTDIR\n                            directory for restored contents and output files\n\nThe main argument is the `path` to a bitstream image of a disk or partition.\nRecuperaBit automatically determines the sectors from which partitions start.\n\nRecuperaBit does not modify the disk image, however it does read some parts of\nit multiple times through the execution. It should also work on real devices,\nsuch as `/dev/sda` but **this is not advised** for damaged drives. RecuperaBit\nmight worsen the situation by \"stressing\" a damaged drive or it could crash due\nto an I/O error.\n\nOptionally, a save file can be specified with `-s`. The first time, after the\nscanning process, results are saved in the file. After the first run, the file\nis read to only analyze interesting sectors and speed up the loading phase.\n\nOverwriting the save file can be forced with `-w`.\n\nRecuperaBit includes a small command line that allows the user to recover files\nand export the contents of a partition in CSV or\n[body file](http://wiki.sleuthkit.org/index.php?title=Body_file) format. These\nare exported in the directory specified by `-o` (or `recuperabit_output`).\n\n### Limitation\n\nCurrently RecuperaBit does not work with compressed files on an NTFS filesystem.\nIf you have deep knowledge of the inner workings of file compression on NTFS\nfilesystem, your help would be much appreciated, as available documentation is\nquite sparse on the topic.\n\n### Pypy\n\nRecuperaBit can be run with the standard cPython implementation, however speed\ncan be increased by using it with the Pypy interpreter and JIT compiler:\n\n    pypy3 main.py /path/to/disk.img\n\n### Recovery of File Contents\n\nFiles can be restored one at a time or recursively, starting from a directory.\nAfter the scanning process has completed, you can check the list of partitions\nthat can be recovered by issuing the following command at the prompt:\n\n    recoverable\n\nEach line shows information about a partition. Let's consider the following\noutput example:\n\n    Partition #0 -> Partition (NTFS, 15.00 MB, 11 files, Recoverable, Offset: 2048, Offset (b): 1048576, Sec/Clus: 8, MFT offset: 2080, MFT mirror offset: 17400)\n\nIf you want to recover files starting from a specific directory, you can either\nprint the tree on screen with the `tree` command (very verbose for large drives)\nor you can export a CSV list of files (see `help` for details).\n\nIf you rather want to extract all files from the *Root* and the *Lost Files*\nnodes, you need to know the identifier for the root directory, depending on\nthe file system type. The following are those of file systems supported by\nRecuperaBit:\n\n| File System Type | Root Id |\n|------------------|---------|\n| NTFS             | 5       |\n\nThe id for *Lost Files* is -1 **for every file system.**\n\nTherefore, to restore `Partition #0` in our example, you need to run:\n\n    restore 0 5\n    restore 0 -1\n\nThe files will be saved inside the output directory specified by `-o`.\n\n## License\n\nThis software is released under the GNU GPLv3. See `LICENSE` for more details.\n"
  },
  {
    "path": "__init__.py",
    "content": ""
  },
  {
    "path": "main.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Main RecuperaBit process.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nimport argparse\nimport codecs\nimport itertools\nimport locale\nimport logging\nimport os.path\nimport pickle\nimport sys\ntry:\n    import readline\n    readline # ignore unused import warning\nexcept ImportError:\n    pass\n\nfrom recuperabit import logic, utils\n# scanners\nfrom recuperabit.fs.ntfs import NTFSScanner\n\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from recuperabit.fs.core_types import Partition\n\n__author__ = \"Andrea Lazzarotto\"\n__copyright__ = \"(c) 2014-2021, Andrea Lazzarotto\"\n__license__ = \"GPLv3\"\n__version__ = \"1.1.6\"\n__maintainer__ = \"Andrea Lazzarotto\"\n__email__ = \"andrea.lazzarotto@gmail.com\"\n\n\n# classes of available scanners\nplugins = (\n    NTFSScanner,\n)\n\ncommands = (\n    ('help', 'Print this help message'),\n    ('recoverable', 'List recoverable partitions'),\n    ('recoverable_size <size>', 'List recoverable partitions based on the minimum <size>'),\n    ('other', 'List unrecoverable partitions'),\n    ('allparts', 'List all partitions'),\n    ('tree <part#>', 'Show contents of partition (tree)'),\n    ('csv <part#> <path>', 'Save a CSV representation in a file'),\n    ('bodyfile <part#> <path>', 'Save a body file representation in a file'),\n    ('tikzplot <part#> [<path>]', 'Produce LaTeX code to draw a Tikz figure'),\n    ('restore <part#> <file>', 'Recursively restore files from <file>'),\n    ('locate <part#> <text>', 'Print all file paths that match a string'),\n    ('traceback <part#> <file>', 'Print ids and paths for all ancestors of <file>'),\n    ('merge <part#> <part#>', 'Merge the two partitions into the first one'),\n    ('quit', 'Close the program')\n)\n\nrebuilt = set()\n\n\ndef list_parts(parts, shorthands, test):\n    \"\"\"List partitions corresponding to test.\"\"\"\n    for i, part in shorthands:\n        if test(parts[part]):\n            print('Partition #' + str(i), '->', parts[part])\n\n\ndef check_valid_part(num, parts, shorthands, rebuild=True):\n    \"\"\"Check if the required partition is valid.\"\"\"\n    try:\n        i = int(num)\n    except ValueError:\n        print('Value is not valid!')\n        return None\n    if i in range(len(shorthands)):\n        i, par = shorthands[i]\n        part = parts[par]\n        if rebuild and par not in rebuilt:\n            print('Rebuilding partition...')\n            part.rebuild()\n            rebuilt.add(par)\n            print('Done')\n        return part\n    print('No partition with given ID!')\n    return None\n\n\ndef interpret(cmd, arguments, parts: dict[int, 'Partition'], shorthands, outdir):\n    \"\"\"Perform command required by user.\"\"\"\n    if cmd == 'help':\n        print('Available commands:')\n        for name, desc in commands:\n            print('    %s%s' % (name.ljust(28), desc))\n    elif cmd == 'tree':\n        if len(arguments) != 1:\n            print('Wrong number of parameters!')\n        else:\n            part = check_valid_part(arguments[0], parts, shorthands)\n            if part is not None:\n                print('-'*10)\n                print(utils.tree_folder(part.root))\n                print(utils.tree_folder(part.lost))\n                print('-'*10)\n    elif cmd == 'bodyfile':\n        if len(arguments) != 2:\n            print('Wrong number of parameters!')\n        else:\n            part = check_valid_part(arguments[0], parts, shorthands)\n            if part is not None:\n                contents = [\n                    '# ---' + repr(part) + '---',\n                    '# Full paths'\n                ] + utils.bodyfile_folder(part.root) + [\n                    '# \\n# Orphaned files'\n                ] + utils.bodyfile_folder(part.lost)\n                fname = os.path.join(outdir, arguments[1])\n                try:\n                    with codecs.open(fname, 'w', encoding='utf8') as outfile:\n                        outfile.write('\\n'.join(contents))\n                        print('Saved body file to %s' % fname)\n                except IOError:\n                    print('Cannot open file %s for output!' % fname)\n    elif cmd == 'csv':\n        if len(arguments) != 2:\n            print('Wrong number of parameters!')\n        else:\n            part = check_valid_part(arguments[0], parts, shorthands)\n            if part is not None:\n                contents = utils.csv_part(part)\n                fname = os.path.join(outdir, arguments[1])\n                try:\n                    with codecs.open(fname, 'w', encoding='utf8') as outfile:\n                        outfile.write(\n                            '\\n'.join(contents)\n                        )\n                        print('Saved CSV file to %s' % fname)\n                except IOError:\n                    print('Cannot open file %s for output!' % fname)\n    elif cmd == 'tikzplot':\n        if len(arguments) not in (1, 2):\n            print('Wrong number of parameters!')\n        else:\n            part = check_valid_part(arguments[0], parts, shorthands)\n            if part is not None:\n                if len(arguments) > 1:\n                    fname = os.path.join(outdir, arguments[1])\n                    try:\n                        with codecs.open(fname, 'w') as outfile:\n                            outfile.write(utils.tikz_part(part) + '\\n')\n                            print('Saved Tikz code to %s' % fname)\n                    except IOError:\n                        print('Cannot open file %s for output!' % fname)\n                else:\n                    print(utils.tikz_part(part))\n    elif cmd == 'restore':\n        if len(arguments) != 2:\n            print('Wrong number of parameters!')\n        else:\n            partid = arguments[0]\n            part = check_valid_part(partid, parts, shorthands)\n            if part is not None:\n                index = arguments[1]\n                partition_dir = os.path.join(outdir, 'Partition' + str(partid))\n                myfile = None\n                try:\n                    indexi = int(index)\n                except ValueError:\n                    indexi = index\n                for i in [index, indexi]:\n                    myfile = part.get(i, myfile)\n                if myfile is None:\n                    print('The index is not valid')\n                else:\n                    logic.recursive_restore(myfile, part, partition_dir)\n    elif cmd == 'locate':\n        if len(arguments) != 2:\n            print('Wrong number of parameters!')\n        else:\n            part = check_valid_part(arguments[0], parts, shorthands)\n            if part is not None:\n                text = arguments[1]\n                results = utils.locate(part, text)\n                for node, path in results:\n                    desc = (\n                        ' [GHOST]' if node.is_ghost else\n                        ' [DELETED]' if node.is_deleted else ''\n                    )\n                    print('[%s]: %s%s' % (node.index, path, desc))\n    elif cmd == 'traceback':\n        if len(arguments) != 2:\n            print('Wrong number of parameters!')\n        else:\n            partid = arguments[0]\n            part = check_valid_part(partid, parts, shorthands)\n            if part is not None:\n                index = arguments[1]\n                myfile = None\n                try:\n                    indexi = int(index)\n                except ValueError:\n                    indexi = index\n                for i in [index, indexi]:\n                    myfile = part.get(i, myfile)\n                if myfile is None:\n                    print('The index is not valid')\n                else:\n                    while myfile is not None:\n                        print('[{}] {}'.format(myfile.index, myfile.full_path(part)))\n                        myfile = part.get(myfile.parent)\n    elif cmd == 'merge':\n        if len(arguments) != 2:\n            print('Wrong number of parameters!')\n        else:\n            part1 = check_valid_part(arguments[0], parts, shorthands, rebuild=False)\n            part2 = check_valid_part(arguments[1], parts, shorthands, rebuild=False)\n            if None in (part1, part2):\n                return\n            if part1.fs_type != part2.fs_type:\n                print('Cannot merge partitions with types (%s, %s)' % (part1.fs_type, part2.fs_type))\n                return\n            print('Merging partitions...')\n            utils.merge(part1, part2)\n            source_position = int(arguments[1])\n            destination_position = int(arguments[0])\n            _, par_source = shorthands[source_position]\n            _, par_destination = shorthands[destination_position]\n            del shorthands[source_position]\n            del parts[par_source]\n            for par in (par_source, par_destination):\n                try:\n                    rebuilt.remove(par)\n                except:\n                    pass\n            print('There are now %d partitions.' % (len(parts), ))\n    elif cmd == 'recoverable':\n        list_parts(parts, shorthands, lambda x: x.recoverable)\n    elif cmd == 'recoverable_size':\n        if len(arguments) != 1:\n            print('Wrong number of parameters!')\n        else:\n            list_parts(parts, shorthands, lambda x: x.size is not None and x.size > int(arguments[0]))\n    elif cmd == 'other':\n        list_parts(parts, shorthands, lambda x: not x.recoverable)\n    elif cmd == 'allparts':\n        list_parts(parts, shorthands, lambda x: True)\n    elif cmd == 'quit':\n        exit(0)\n    else:\n        print('Unknown command.')\n\n\ndef main():\n    \"\"\"Wrap the program logic inside a function.\"\"\"\n    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\n    print(r\"     ___                                ___ _ _   \")\n    print(r\"    | _ \\___ __ _  _ _ __  ___ _ _ __ _| _ |_) |_ \")\n    print(r\"    |   / -_) _| || | '_ \\/ -_) '_/ _` | _ \\ |  _|\")\n    print(r\"    |_|_\\___\\__|\\_,_| .__/\\___|_| \\__,_|___/_|\\__|\")\n    print(\"                    |_|   v{}\".format(__version__))\n    print('   ', __copyright__, '<%s>' % __email__)\n    print('    Released under the', __license__)\n    print('')\n\n    parser = argparse.ArgumentParser(\n        description='Reconstruct the directory structure of possibly damaged '\n                    'filesystems.'\n    )\n    parser.add_argument('path', type=str, help='path to the disk image')\n    parser.add_argument(\n        '-s', '--savefile', type=str, help='path of the scan save file'\n    )\n    parser.add_argument(\n        '-w', '--overwrite', action='store_true',\n        help='force overwrite of the save file'\n    )\n    parser.add_argument(\n        '-o', '--outputdir', type=str, help='directory for restored contents'\n        ' and output files'\n    )\n    args = parser.parse_args()\n\n    try:\n        image = open(args.path, 'rb')\n    except IOError:\n        logging.error('Unable to open image file!')\n        exit(1)\n\n    read_results = False\n    write_results = False\n\n    # Set output directory\n    if args.outputdir is None:\n        logging.info('No output directory specified, defaulting to '\n                     'recuperabit_output')\n        args.outputdir = 'recuperabit_output'\n\n    # Try to reload information from the savefile\n    if args.savefile is not None:\n        if args.overwrite:\n            logging.info('Results will be saved to %s', args.savefile)\n            write_results = True\n        else:\n            logging.info('Checking if results already exist.')\n            try:\n                savefile = open(args.savefile, 'rb')\n                logging.info('Results will be read from %s', args.savefile)\n                read_results = True\n            except IOError:\n                logging.info('Unable to open save file.')\n                logging.info('Results will be saved to %s', args.savefile)\n                write_results = True\n\n    if read_results:\n        logging.info('The save file exists. Trying to read it...')\n        try:\n            indexes = pickle.load(savefile)\n            savefile.close()\n        except IndexError:\n            logging.error('Malformed save file!')\n            exit(1)\n    else:\n        indexes = itertools.count()\n\n    # Ask for confirmation before beginning the process\n    try:\n        confirm = input('Type [Enter] to start the analysis or '\n                            '\"exit\" / \"quit\" / \"q\" to quit: ')\n    except EOFError:\n        print('')\n        exit(0)\n    if confirm in ('exit', 'quit', 'q'):\n        exit(0)\n\n    # Create the output directory\n    if not logic.makedirs(args.outputdir):\n        logging.error('Cannot create output directory!')\n        exit(1)\n\n    scanners = [pl(image) for pl in plugins]\n\n    logging.info('Analysis started! This is going to take time...')\n    interesting = utils.feed_all(image, scanners, indexes)\n\n    logging.info('First scan completed')\n\n    if write_results:\n        logging.info('Saving results to %s', args.savefile)\n        with open(args.savefile, 'wb') as savefile:\n            pickle.dump(interesting, savefile)\n\n    # Ask for partitions\n    parts: dict[int, 'Partition'] = {}\n    for scanner in scanners:\n        parts.update(scanner.get_partitions())\n\n    shorthands = list(enumerate(parts))\n\n    logging.info('%i partitions found.', len(parts))\n    while True:\n        print('\\nWrite command (\"help\" for details):')\n        try:\n            command = input('> ').split(' ')\n        except (EOFError, KeyboardInterrupt):\n            print('')\n            exit(0)\n        cmd = command[0]\n        arguments = command[1:]\n        interpret(cmd, arguments, parts, shorthands, args.outputdir)\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "recuperabit/__init__.py",
    "content": "# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "recuperabit/fs/__init__.py",
    "content": "# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "recuperabit/fs/constants.py",
    "content": "\"\"\"Information needed by multiple plugins.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nsector_size: int = 512\nmax_sectors: int = 256   # Maximum block size for recovery\n"
  },
  {
    "path": "recuperabit/fs/core_types.py",
    "content": "\"\"\"Recuperabit Core Types.\n\nThis module contains the class declarations of all objects which are used in\nthe Recuperabit meta file system. Each plug-in is supposed to extend the File\nand DiskScanner classes with subclasses implementing the missing methods.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nimport logging\nimport os.path\nfrom typing import Optional, Dict, Set, List, Tuple, Union, Any, Iterator\nfrom datetime import datetime\n\nfrom .constants import sector_size\n\nfrom ..utils import readable_bytes\n\n\nclass File(object):\n    \"\"\"Filesystem-independent representation of a file. Aka Node.\"\"\"\n    def __init__(self, index: Union[int, str], name: str, size: Optional[int], is_directory: bool = False,\n                 is_deleted: bool = False, is_ghost: bool = False) -> None:\n        self.index: Union[int, str] = index\n        self.name: str = name\n        self.size: Optional[int] = size\n        self.is_directory: bool = is_directory\n        self.is_deleted: bool = is_deleted\n        self.is_ghost: bool = is_ghost\n        self.parent: Optional[Union[int, str]] = None\n        self.mac: Dict[str, Optional[datetime]] = {\n            'modification': None,\n            'access': None,\n            'creation': None\n        }\n        self.children: Set['File'] = set()\n        self.children_names: Set[str] = set()     # Avoid name clashes breaking restore\n        self.offset: Optional[int] = None  # Offset from beginning of disk\n\n    def set_parent(self, parent: Optional[Union[int, str]]) -> None:\n        \"\"\"Set a pointer to the parent directory.\"\"\"\n        self.parent = parent\n\n    def set_mac(self, modification: Optional[datetime], access: Optional[datetime], creation: Optional[datetime]) -> None:\n        \"\"\"Set the modification, access and creation times.\"\"\"\n        self.mac['modification'] = modification\n        self.mac['access'] = access\n        self.mac['creation'] = creation\n\n    def get_mac(self) -> List[Optional[datetime]]:\n        \"\"\"Get the modification, access and creation times.\"\"\"\n        keys = ('modification', 'access', 'creation')\n        return [self.mac[k] for k in keys]\n\n    def set_offset(self, offset: Optional[int]) -> None:\n        \"\"\"Set the offset of the file record with respect to the disk image.\"\"\"\n        self.offset = offset\n\n    def get_offset(self) -> Optional[int]:\n        \"\"\"Get the offset of the file record with respect to the disk image.\"\"\"\n        return self.offset\n\n    def add_child(self, node: 'File') -> None:\n        \"\"\"Add a new child to this directory.\"\"\"\n        original_name = node.name\n        i = 0\n        # Check for multiple rebuilds\n        if node in self.children:\n            return\n        # Avoid name clashes\n        while node.name in self.children_names:\n            node.name = original_name + '_%03d' % i\n            i += 1\n        if node.name != original_name:\n            logging.warning(u'Renamed {} from {}'.format(node, original_name))\n        self.children.add(node)\n        self.children_names.add(node.name)\n\n    def full_path(self, part: 'Partition') -> str:\n        \"\"\"Return the full path of this file.\"\"\"\n        if self.parent is not None:\n            parent = part[self.parent]\n            return os.path.join(parent.full_path(part), self.name)\n        else:\n            return self.name\n\n    def get_content(self, partition: 'Partition') -> Optional[Union[bytes, Iterator[bytes]]]:\n        # pylint: disable=W0613\n        \"\"\"Extract the content of the file.\n\n        This method is intentionally not implemented because it depends on each\n        plug-in for a specific file system.\"\"\"\n        if self.is_directory or self.is_ghost:\n            return None\n        raise NotImplementedError\n\n    # pylint: disable=R0201\n    def ignore(self) -> bool:\n        \"\"\"The following method is used by the restore procedure to check\n        files that should not be recovered. For example, in NTFS file\n        $BadClus:$Bad shall not be recovered because it creates an output\n        with the same size as the partition (usually many GBs).\"\"\"\n        return False\n\n    def __repr__(self) -> str:\n        return (\n            u'File(#%s, ^^%s^^, %s, offset = %s sectors)' %\n            (self.index, self.parent, self.name, self.offset)\n        )\n\n\nclass Partition(object):\n    \"\"\"Simplified representation of the contents of a partition.\n\n    Parameter root_id represents the identifier assigned to the root directory\n    of a partition. This can be file system dependent.\"\"\"\n    def __init__(self, fs_type: str, root_id: Union[int, str], scanner: 'DiskScanner') -> None:\n        self.fs_type: str = fs_type\n        self.root_id: Union[int, str] = root_id\n        self.size: Optional[int] = None\n        self.offset: Optional[int] = None\n        self.root: Optional[File] = None\n        self.lost: File = File(-1, 'LostFiles', 0, is_directory=True, is_ghost=True)\n        self.files: Dict[Union[int, str], File] = {}\n        self.recoverable: bool = False\n        self.scanner: 'DiskScanner' = scanner\n\n    def add_file(self, node: File) -> None:\n        \"\"\"Insert a new file in the partition.\"\"\"\n        index = node.index\n        self.files[index] = node\n\n    def set_root(self, node: File) -> None:\n        \"\"\"Set the root directory.\"\"\"\n        if not node.is_directory:\n            raise TypeError('Not a directory')\n        self.root = node\n        self.root.set_parent(None)\n\n    def set_size(self, size: int) -> None:\n        \"\"\"Set the (estimated) size of the partition.\"\"\"\n        self.size = size\n\n    def set_offset(self, offset: int) -> None:\n        \"\"\"Set the offset from the beginning of the disk.\"\"\"\n        self.offset = offset\n\n    def set_recoverable(self, recoverable: bool) -> None:\n        \"\"\"State if the partition contents are also recoverable.\"\"\"\n        self.recoverable = recoverable\n\n    def rebuild(self) -> None:\n        \"\"\"Rebuild the partition structure.\n\n        This method processes the contents of files and it rebuilds the\n        directory tree as accurately as possible.\"\"\"\n        root_id = self.root_id\n        rootname = 'Root'\n\n        if root_id not in self.files:\n            self.files[root_id] = File(\n                root_id, rootname, 0, is_directory=True, is_ghost=True\n            )\n\n        # Convert keys to list to avoid RuntimeError\n        for identifier in list(self.files):\n            node = self.files[identifier]\n            if node.index == root_id:\n                self.set_root(node)\n                node.name = rootname\n            else:\n                parent_id = node.parent\n                exists = parent_id is not None\n                valid = parent_id in self.files\n                if exists and valid:\n                    parent_node = self.files[parent_id]\n                elif exists and not valid:\n                    parent_node = File(parent_id, 'Dir_' + str(parent_id),\n                                       0, is_directory=True, is_ghost=True)\n                    parent_node.set_parent(-1)\n                    self.files[parent_id] = parent_node\n                    self.lost.add_child(parent_node)\n                else:\n                    parent_node = self.lost\n                    node.set_parent(-1)\n                parent_node.add_child(node)\n        return\n\n    # pylint: disable=R0201\n    def additional_repr(self) -> List[Tuple[str, Any]]:\n        \"\"\"Return additional values to show in the string representation.\"\"\"\n        return []\n\n    def __repr__(self) -> str:\n        size = (\n            readable_bytes(self.size * sector_size)\n            if self.size is not None else '??? b'\n        )\n        data = [\n            ('Offset', self.offset),\n            (\n                'Offset (b)',\n                self.offset * sector_size\n                if self.offset is not None else None\n            ),\n        ]\n        data += self.additional_repr()\n        return u'Partition (%s, %s, %d files,%s %s)' % (\n            self.fs_type,\n            size,\n            len(self.files),\n            ' Recoverable,' if self.recoverable else '',\n            ', '.join(a+': '+str(b) for a, b in data)\n        )\n\n    def __getitem__(self, index: Union[int, str]) -> File:\n        if index in self.files:\n            return self.files[index]\n        if index == self.lost.index:\n            return self.lost\n        raise KeyError\n\n    def get(self, index: Union[int, str], default: Optional[File] = None) -> Optional[File]:\n        \"\"\"Get a file or the special LostFiles directory.\"\"\"\n        try:\n            return self.__getitem__(index)\n        except KeyError:\n            return default\n\n\nclass DiskScanner(object):\n    \"\"\"Abstract stub for the implementation of disk scanners.\"\"\"\n    def __init__(self, pointer: Any) -> None:\n        self.image: Any = pointer\n\n    def get_image(self) -> Any:\n        \"\"\"Return the image reference.\"\"\"\n        return self.image\n\n    @staticmethod\n    def get_image(scanner: 'DiskScanner') -> Any:\n        \"\"\"Static method to get image from scanner instance.\"\"\"\n        return scanner.image\n\n    def feed(self, index: int, sector: bytes) -> Optional[str]:\n        \"\"\"Feed a new sector.\"\"\"\n        raise NotImplementedError\n\n    def get_partitions(self) -> Dict[int, Partition]:\n        \"\"\"Get a list of the found partitions.\"\"\"\n        raise NotImplementedError\n"
  },
  {
    "path": "recuperabit/fs/ntfs.py",
    "content": "\"\"\"NTFS plug-in.\n\nThis plug-in contains the necessary logic to parse traces of NTFS file systems,\nincluding MFT entries and directory indexes.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nimport logging\nfrom collections import Counter\nfrom typing import Any, Dict, List, Optional, Tuple, Union, Iterator, Set\n\nfrom .constants import max_sectors, sector_size\nfrom .core_types import DiskScanner, File, Partition\nfrom .ntfs_fmt import (attr_header_fmt, attr_names, attr_nonresident_fmt,\n                      attr_resident_fmt, attr_types_fmt, attribute_list_parser,\n                      boot_sector_fmt, entry_fmt, indx_dir_entry_fmt, indx_fmt,\n                      indx_header_fmt)\n\nfrom ..logic import SparseList, approximate_matching\nfrom ..utils import merge, sectors, unpack\n\n# Some attributes may appear multiple times\nmultiple_attributes: Set[str] = set([\n    '$FILE_NAME',\n    '$DATA',\n    '$INDEX_ROOT',\n    '$INDEX_ALLOCATION',\n    '$BITMAP'\n])\n\n# Size of records in sectors\nFILE_size: int = 2\nINDX_size: int = 8\n\n\ndef best_name(entries: List[Tuple[int, str]]) -> Optional[str]:\n    \"\"\"Return the best file name available.\n\n    This function accepts a list of tuples formed by a namespace and a string.\n    In case of more than one choice, it returns preferrably the one in the NTFS\n    namespace (code == 3).\"\"\"\n    if len(entries) == 0:\n        return None\n\n    entries.sort()\n    if entries[-1][0] == 3:\n        name = entries[-1][1]\n    else:\n        name = entries[0][1]\n    return name if len(name) else None\n\n\ndef parse_mft_attr(attr: bytes) -> Tuple[Dict[str, Any], Optional[str]]:\n    \"\"\"Parse the contents of a MFT attribute.\"\"\"\n    header = unpack(attr, attr_header_fmt)\n    attr_type = header['type']\n\n    if attr_type not in attr_names:\n        return header, None\n\n    if header['non_resident']:\n        nonresident = unpack(attr, attr_nonresident_fmt)\n        if nonresident['runlist'] is None:\n            nonresident['runlist'] = list()\n        header.update(nonresident)\n    else:\n        resident = unpack(attr, attr_resident_fmt)\n        header.update(resident)\n        offset = header['content_off']\n        content = attr[offset:]\n\n    name = attr_names[attr_type]\n    if not header['non_resident'] and name in attr_types_fmt:\n        size = header['content_size']\n        data = unpack(content[:size], attr_types_fmt[name])\n        header['content'] = data\n\n    return header, name\n\n\ndef _apply_fixup_values(header: Dict[str, Any], entry: bytearray) -> None:\n    \"\"\"Apply the fixup values to FILE and INDX records.\"\"\"\n    offset = header['off_fixup']\n    for i in range(1, header['n_entries']):\n        pos = sector_size * i\n        entry[pos-2:pos] = entry[offset + 2*i:offset + 2*(i+1)]\n\n\ndef _attributes_reader(entry: bytes, offset: int) -> Dict[str, Any]:\n    \"\"\"Read every attribute.\"\"\"\n    attributes = {}\n    while offset < len(entry) - 16:\n        try:\n            attr, name = parse_mft_attr(entry[offset:])\n        except TypeError:\n            # The attribute was broken, we need to terminate here\n            return attributes\n        attr['dump_offset'] = offset\n        if attr['length'] == 0:\n            # End of attribute list\n            break\n        else:\n            offset = offset + attr['length']\n            if name is None:\n                # Skip broken/unknown attribute\n                continue\n            if name not in attributes:\n                if name not in multiple_attributes:\n                    attributes[name] = attr\n                else:\n                    attributes[name] = [attr]\n            else:\n                if name in multiple_attributes:\n                    attributes[name].append(attr)\n                else:\n                    logging.error('Cannot handle multiple attribute %s', name)\n    return attributes\n\n\ndef parse_file_record(entry: bytes) -> Dict[str, Any]:\n    \"\"\"Parse the contents of a FILE record (MFT entry).\"\"\"\n    header = unpack(entry, entry_fmt)\n    if (header['size_alloc'] is None or\n            header['size_alloc'] > len(entry) or\n            len(entry) < FILE_size*sector_size):\n        header['valid'] = False\n        return header\n\n    # Old versions of NTFS don't have a MFT record number.\n    if header['off_fixup'] < 48:\n        header['record_n'] = None\n\n    _apply_fixup_values(header, entry)\n\n    attributes = _attributes_reader(entry, header['off_first'])\n    header['valid'] = True\n    header['attributes'] = attributes\n    return header\n\n\ndef parse_indx_record(entry: bytes) -> Dict[str, Any]:\n    \"\"\"Parse the contents of a INDX record (directory index).\"\"\"\n    header = unpack(entry, indx_fmt)\n\n    _apply_fixup_values(header, entry)\n\n    node_data = unpack(entry[24:], indx_header_fmt)\n    node_data['off_start_list'] += 24\n    node_data['off_end_list'] += 24\n    node_data['off_end_buffer'] += 24\n    header.update(node_data)\n\n    offset = header['off_start_list']\n    entries = []\n    while offset < header['off_end_list']:\n        entry_data = unpack(entry[offset:], indx_dir_entry_fmt)\n        if entry_data['content_length']:\n            try:\n                file_name = unpack(\n                    entry[offset + 16:],\n                    attr_types_fmt['$FILE_NAME']\n                )\n            except (UnicodeDecodeError, TypeError):  # Invalid file name or invalid name length\n                break\n            # Perform checks to avoid false positives\n            name_ok = file_name['name'] is not None\n            namespace_ok = 0 <= file_name['namespace'] <= 3\n            size_ok = file_name['real_size'] <= file_name['allocated_size']\n            features_ok = not (\n                file_name['flags'] == 0 and\n                file_name['parent_seq'] > 1024\n            )\n            if name_ok and namespace_ok and size_ok and features_ok:\n                entry_data['file_info'] = file_name\n                entries.append(entry_data)\n            else:\n                break\n        if entry_data['entry_length']:\n            offset += entry_data['entry_length']\n        else:\n            break\n    header['entries'] = entries\n    header['valid'] = len(entries) > 0\n    return header\n\n\ndef _integrate_attribute_list(parsed: Dict[str, Any], part: 'NTFSPartition', image: Any) -> None:\n    \"\"\"Integrate missing attributes in the parsed MTF entry.\"\"\"\n    base_record = parsed['record_n']\n    attrs = parsed['attributes']\n    attr = attrs['$ATTRIBUTE_LIST']\n\n    spc = part.sec_per_clus\n    if 'runlist' in attr:\n        clusters_pos = 0\n        entries = []\n        size = attr['real_size']\n        for entry in attr['runlist']:\n            clusters_pos += entry['offset']\n            length = min(entry['length'] * spc * sector_size, size)\n            size -= length\n            real_pos = clusters_pos * spc + part.offset\n            dump = sectors(image, real_pos, length, 1)\n            entries += attribute_list_parser(dump)\n        attr['content'] = {'entries': entries}\n    else:\n        entries = attr['content']['entries']\n\n    # Divide entries by type\n    types = set(e['type'] for e in entries)\n    entries_by_type = {\n        t: set(\n            e['file_ref'] for e in entries\n            if e['type'] == t and e['file_ref'] is not None\n        )\n        for t in types\n    }\n    # Remove completely \"local\" types or empty lists\n    for num in list(entries_by_type):\n        files = entries_by_type[num]\n        if (\n            len(files) == 0 or\n            (len(files) == 1 and next(iter(files)) == base_record)\n        ):\n            del entries_by_type[num]\n\n    mft_pos = part.mft_pos\n    for num in entries_by_type:\n        # Read contents of child entries\n        for index in entries_by_type[num]:\n            real_pos = mft_pos + index * FILE_size\n            dump = sectors(image, real_pos, FILE_size)\n            child_parsed = parse_file_record(dump)\n            if 'attributes' not in child_parsed:\n                continue\n            # Update the main entry (parsed)\n            if child_parsed['base_record'] == base_record:\n                child_attrs = child_parsed['attributes']\n                for name in child_attrs:\n                    if name in multiple_attributes:\n                        try:\n                            attrs[name] += child_attrs[name]\n                        except KeyError:\n                            attrs[name] = child_attrs[name]\n                    else:\n                        attrs[name] = child_attrs[name]\n\n\nclass NTFSFile(File):\n    \"\"\"NTFS File.\"\"\"\n    def __init__(self, parsed: Dict[str, Any], offset: Optional[int], is_ghost: bool = False, ads: str = '') -> None:\n        index = parsed['record_n']\n        ads_suffix = ':' + ads if ads != '' else ads\n        if ads != '':\n            index = str(index) + ads_suffix\n        attrs = parsed['attributes']\n        filenames = attrs['$FILE_NAME']\n        datas = attrs.get('$DATA', [])\n\n        size = None\n        for attr in datas:\n            if attr['name'] == ads:\n                if 'real_size' in attr:\n                    size = attr['real_size']\n                elif not attr['non_resident']:\n                    size = attr['content_size']\n                break\n\n        filtered = [\n            f for f in filenames if 'content' in f and\n            f['content'] is not None and\n            'name_length' in f['content'] and\n            f['content']['name_length'] > 0 and\n            f['content']['name'] is not None\n        ]\n        name = best_name([\n            (f['content']['namespace'], f['content']['name'] + ads_suffix)\n            for f in filtered\n        ])\n        hasname = name is not None\n\n        if not hasname:\n            name = 'File_%s' % index\n\n        std_info = attrs.get('$STANDARD_INFORMATION')\n\n        is_dir = (parsed['flags'] & 0x02) > 0 and not len(ads)\n        is_del = (parsed['flags'] & 0x01) == 0\n        File.__init__(self, index, name, size, is_dir, is_del, is_ghost)\n\n        time_attribute = None\n\n        # Additional attributes\n        if hasname:\n            first = filtered[0]['content']\n            parent_id = first['parent_entry']\n            File.set_parent(self, parent_id)\n            File.set_offset(self, offset)\n            time_attribute = std_info or filtered[0]\n        if time_attribute and 'content' in time_attribute:\n            File.set_mac(\n                self, time_attribute['content']['modification_time'],\n                time_attribute['content']['access_time'],\n                time_attribute['content']['creation_time'],\n            )\n        self.ads = ads\n\n    @staticmethod\n    def _padded_bytes(image: Any, offset: int, size: int) -> bytes:\n        dump = sectors(image, offset, size, 1)\n        if len(dump) < size:\n            logging.warning(\n                'Failed to read byte(s). Padding with 0x00. Offset: {} Size: '\n                '{}'.format(offset, size))\n            dump += bytearray(b'\\x00' * (size - len(dump)))\n        return dump\n\n    def content_iterator(self, partition: 'NTFSPartition', image: Any, datas: List[Dict[str, Any]]) -> Iterator[bytes]:\n        \"\"\"Return an iterator for the contents of this file.\"\"\"\n        vcn = 0\n        spc = partition.sec_per_clus\n        for attr in datas:\n            diff = attr['start_VCN'] - vcn\n            if diff > 0:\n                # We do not try to fill with zeroes as this might produce huge useless files\n                logging.warning(\n                    u'Missing part for {} expected VCN {}, '\n                    u'got start_VCN={} ({} clusters skipped). '.format(\n                        self, vcn, attr['start_VCN'], diff,\n                    )\n                )\n                vcn += diff\n                yield b''\n            elif diff < 0:\n                # VCN went backwards: overlap, out-of-order, or cross-stream contamination\n                logging.warning(\n                    u'$DATA attribute VCN overlap for {}. '\n                    u'expected VCN {}, got start_VCN={}. '\n                    u'This may indicate attribute filtering error or MFT corruption.'.format(\n                        self, vcn, attr['start_VCN']\n                    )\n                )\n\n            clusters_pos = 0\n            size = attr['real_size']\n\n            if 'runlist' not in attr:\n                logging.error(\n                    u'Cannot restore {}, missing runlist'.format(self)\n                )\n                break\n\n            for entry in attr['runlist']:\n                length = min(entry['length'] * spc * sector_size, size)\n                size -= length\n                # Sparse runlist\n                if entry['offset'] is None:\n                    while length > 0:\n                        amount = min(max_sectors*sector_size, length)\n                        length -= amount\n                        yield b'\\x00' * amount\n                    continue\n                # Normal runlists\n                clusters_pos += entry['offset']\n                real_pos = clusters_pos * spc + partition.offset\n                # Avoid to fill memory with huge blocks\n                offset = 0\n                while length > 0:\n                    amount = min(max_sectors*sector_size, length)\n                    position = real_pos*sector_size + offset\n                    partial = self._padded_bytes(image, position, amount)\n                    length -= amount\n                    offset += amount\n                    yield bytes(partial)\n            vcn = attr['end_VCN'] + 1\n\n    def get_content(self, partition: 'NTFSPartition') -> Optional[Union[bytes, Iterator[bytes]]]:\n        \"\"\"Extract the content of the file.\n\n        This method works by extracting the $DATA attribute.\"\"\"\n        if self.is_ghost:\n            logging.error(u'Cannot restore ghost file {}'.format(self))\n            return None\n\n        image = DiskScanner.get_image(partition.scanner)\n        dump = sectors(image, File.get_offset(self), FILE_size)\n        parsed = parse_file_record(dump)\n\n        if not parsed['valid'] or 'attributes' not in parsed:\n            logging.error(u'Invalid MFT entry for {}'.format(self))\n            return None\n        attrs = parsed['attributes']\n        if ('$ATTRIBUTE_LIST' in attrs and\n                partition.sec_per_clus is not None):\n            _integrate_attribute_list(parsed, partition, image)\n        if '$DATA' not in attrs:\n            attrs['$DATA'] = []\n        datas = [d for d in attrs['$DATA'] if d['name'] == self.ads]\n        if not len(datas):\n            if not self.is_directory:\n                logging.error(u'Cannot restore $DATA attribute(s) '\n                              'for {}'.format(self))\n            return None\n\n        # TODO implemented compressed attributes\n        for d in datas:\n            if d['flags'] & 0x01:\n                logging.error(u'Cannot restore compressed $DATA attribute(s) '\n                              'for {}'.format(self))\n                return None\n            elif d['flags'] & 0x4000:\n                logging.warning(u'Found encrypted $DATA attribute(s) '\n                                'for {}'.format(self))\n\n        # Handle resident file content\n        if len(datas) == 1 and not datas[0]['non_resident']:\n            single = datas[0]\n            start = single['dump_offset'] + single['content_off']\n            end = start + single['content_size']\n            content = dump[start:end]\n            return bytes(content)\n        else:\n            if partition.sec_per_clus is None:\n                logging.error(u'Cannot restore non-resident $DATA '\n                              'attribute(s) for {}'.format(self))\n                return None\n            non_resident = sorted(\n                (d for d in datas if d['non_resident']),\n                key=lambda x: x['start_VCN']\n            )\n            if len(non_resident) != len(datas):\n                logging.warning(\n                    u'Found leftover resident $DATA attributes for '\n                    '{}. Only those non-resident parts will be restored.'.format(self)\n                )\n            return self.content_iterator(partition, image, non_resident)\n\n    def ignore(self) -> bool:\n        \"\"\"Determine which files should be ignored.\"\"\"\n        return (\n            (self.index == '8:$Bad') or\n            (self.parent == 11 and self.ads == '$J')    # $UsnJrnl\n        )\n\n\nclass NTFSPartition(Partition):\n    \"\"\"Partition with additional fields for NTFS recovery.\"\"\"\n    def __init__(self, scanner: 'NTFSScanner', position: Optional[int] = None) -> None:\n        Partition.__init__(self, 'NTFS', 5, scanner)\n        self.sec_per_clus: Optional[int] = None\n        self.mft_pos: Optional[int] = position\n        self.mftmirr_pos: Optional[int] = None\n\n    def additional_repr(self) -> List[Tuple[str, Any]]:\n        \"\"\"Return additional values to show in the string representation.\"\"\"\n        return [\n            ('Sec/Clus', self.sec_per_clus),\n            ('MFT offset', self.mft_pos),\n            ('MFT mirror offset', self.mftmirr_pos)\n        ]\n\n\nclass NTFSScanner(DiskScanner):\n    \"\"\"NTFS Disk Scanner.\"\"\"\n    def __init__(self, pointer: Any) -> None:\n        DiskScanner.__init__(self, pointer)\n        self.found_file: Set[int] = set()\n        self.parsed_file_review: Dict[int, Dict[str, Any]] = {}\n        self.found_indx: Set[int] = set()\n        self.parsed_indx: Dict[int, Dict[str, Any]] = {}\n        self.indx_list: Optional[SparseList[int]] = None\n        self.found_boot: List[int] = []\n        self.found_spc: List[int] = []\n\n    def feed(self, index: int, sector: bytes) -> Optional[str]:\n        \"\"\"Feed a new sector.\"\"\"\n        # check boot sector\n        if sector.endswith(b'\\x55\\xAA') and b'NTFS' in sector[:8]:\n            self.found_boot.append(index)\n            return 'NTFS boot sector'\n\n        # check file record\n        if sector.startswith((b'FILE', b'BAAD')):\n            self.found_file.add(index)\n            return 'NTFS file record'\n\n        # check index record\n        if sector.startswith(b'INDX'):\n            self.found_indx.add(index)\n            return 'NTFS index record'\n\n    @staticmethod\n    def add_indx_entries(entries: List[Dict[str, Any]], part: NTFSPartition) -> None:\n        \"\"\"Insert new ghost files which were not already found.\"\"\"\n        for rec in entries:\n            if (rec['record_n'] not in part.files and\n                    rec['$FILE_NAME'] is not None):\n                # Compatibility with the structure of a MFT entry\n                rec['attributes'] = {\n                    '$FILE_NAME': [{'content': rec['$FILE_NAME']}]\n                }\n                \"\"\"Although the structure of r is similar to that of a MFT\n                entry, flags were about the index, not about the file. We\n                don't know if the element is a directory or not, hence we\n                mark it as a file. It can be deduced if it is a directory\n                by looking at the number of children, after the\n                reconstruction.\"\"\"\n                rec['flags'] = 0x1\n                part.add_file(NTFSFile(rec, None, is_ghost=True))\n\n    def add_from_indx_root(self, parsed: Dict[str, Any], part: NTFSPartition) -> None:\n        \"\"\"Add ghost entries to part from INDEX_ROOT attributes in parsed.\"\"\"\n        for attribute in parsed['attributes']['$INDEX_ROOT']:\n            if (attribute.get('content') is None or\n                    attribute['content'].get('records') is None):\n                continue\n            self.add_indx_entries(attribute['content']['records'], part)\n\n    def most_likely_sec_per_clus(self) -> List[int]:\n        \"\"\"Determine the most likely value of sec_per_clus of each partition,\n        to speed up the search.\"\"\"\n        counter = Counter()\n        counter.update(self.found_spc)\n        counter.update(2**i for i in range(8))\n        return [i for i, _ in counter.most_common()]\n\n    def find_boundary(self, part: NTFSPartition, mft_address: int, multipliers: List[int]) -> Tuple[Optional[int], Optional[int]]:\n        \"\"\"Determine the starting sector of a partition with INDX records.\"\"\"\n        nodes = (\n            self.parsed_file_review[node.offset]\n            for node in part.files.values()\n            if node.offset in self.parsed_file_review and\n            '$INDEX_ALLOCATION' in\n            self.parsed_file_review[node.offset]['attributes']\n        )\n\n        text_list = self.indx_list\n        width = text_list.__len__()\n\n        base_pattern = {}\n        for parsed in nodes:\n            for attr in parsed['attributes']['$INDEX_ALLOCATION']:\n                clusters_pos = 0\n                if 'runlist' not in attr:\n                    continue\n                runlist = attr['runlist']\n                for entry in runlist:\n                    clusters_pos += entry['offset']\n                    base_pattern[clusters_pos] = parsed['record_n']\n        if not len(base_pattern):\n            return (None, None)\n\n        results = []\n        min_support = 2\n        for sec_per_clus in multipliers:\n            pattern = {\n                i * sec_per_clus: base_pattern[i]\n                for i in base_pattern\n            }\n\n            delta = min(pattern)\n            normalized = {\n                i-delta: pattern[i]\n                for i in pattern if i-delta <= width\n                # Avoid extremely long, useless patterns\n            }\n            if len(normalized) < min_support:\n                continue\n\n            pattern_list = SparseList(normalized)\n            solution = approximate_matching(\n                text_list, pattern_list, mft_address + delta, k=min_support\n            )\n            if solution is not None:\n                # Avoid negative offsets and ambiguous situations\n                solution[0] = [i-delta for i in solution[0] if i-delta >= 0]\n                if len(solution[0]) == 1:\n                    positions, amount, perc = solution\n                    results.append((positions, perc, sec_per_clus))\n                    # Reasonably, this is a correct match\n                    if perc > 0.25 and amount > 256:\n                        break\n                min_support = max(min_support, solution[1])\n\n        if len(results):\n            results.sort(key=lambda r: r[1])\n            positions, _, spc = results[0]\n            return (positions[0], spc)\n        else:\n            return (None, None)\n\n    def add_from_indx_allocation(self, parsed: Dict[str, Any], part: NTFSPartition) -> None:\n        \"\"\"Add ghost entries to part from INDEX_ALLOCATION attributes in parsed.\n\n        This procedure requires that the beginning of the partition has already\n        been discovered.\"\"\"\n        read_again = set()\n        for attr in parsed['attributes']['$INDEX_ALLOCATION']:\n            clusters_pos = 0\n            if 'runlist' not in attr:\n                continue\n            runlist = attr['runlist']\n            for entry in runlist:\n                clusters_pos += entry['offset']\n                real_pos = clusters_pos * part.sec_per_clus + part.offset\n                if real_pos in self.parsed_indx:\n                    content = self.parsed_indx[real_pos]\n                    # Check if the entry matches\n                    if parsed['record_n'] == content['parent']:\n                        discovered = set(\n                            c for c in content['children']\n                            if c not in part.files\n                        )\n                        # If there are new files, read the INDX again\n                        if len(discovered):\n                            read_again.add(real_pos)\n\n        img = DiskScanner.get_image(self)\n        for position in read_again:\n            dump = sectors(img, position, INDX_size)\n            entries = parse_indx_record(dump)['entries']\n            self.add_indx_entries(entries, part)\n\n    def add_from_attribute_list(self, parsed: Dict[str, Any], part: NTFSPartition, offset: int) -> None:\n        \"\"\"Add additional entries to part from attributes in ATTRIBUTE_LIST.\n\n        Files with many attributes may have additional attributes not in the\n        MFT entry. When this happens, it is necessary to find the other\n        attributes. They may contain additional information, such as $DATA\n        attributes for ADS. This procedure requires that the beginning of the\n        partition has already been discovered.\"\"\"\n        image = DiskScanner.get_image(self)\n        _integrate_attribute_list(parsed, part, image)\n\n        attrs = parsed['attributes']\n        if '$DATA' in attrs:\n            for attribute in attrs['$DATA']:\n                ads_name = attribute['name']\n                if ads_name and len(ads_name):\n                    part.add_file(NTFSFile(parsed, offset, ads=ads_name))\n\n    def add_from_mft_mirror(self, part: NTFSPartition) -> None:\n        \"\"\"Fix the first file records using the MFT mirror.\"\"\"\n        img = DiskScanner.get_image(self)\n        mirrpos = part.mftmirr_pos\n        if mirrpos is None:\n            return\n\n        for i in range(4):\n            node = part.get(i)\n            if node is None or node.is_ghost:\n                position = mirrpos + i * FILE_size\n                dump = sectors(img, position, FILE_size)\n                parsed = parse_file_record(dump)\n                if parsed['valid'] and '$FILE_NAME' in parsed['attributes']:\n                    node = NTFSFile(parsed, position)\n                    part.add_file(node)\n                    logging.info(\n                        u'Repaired MFT entry #%s - %s in partition at offset '\n                        '%s from backup', node.index, node.name, part.offset\n                    )\n\n    def finalize_reconstruction(self, part: NTFSPartition) -> None:\n        \"\"\"Finish information gathering from a file.\n\n        This procedure requires that the beginning of the\n        partition has already been discovered.\"\"\"\n        logging.info('Adding extra attributes from $ATTRIBUTE_LIST')\n        # Select elements with many attributes\n        many_attributes_it = (\n            node for node in list(part.files.values())\n            if node.offset in self.parsed_file_review and\n            '$ATTRIBUTE_LIST' in\n            self.parsed_file_review[node.offset]['attributes']\n        )\n        for node in many_attributes_it:\n            parsed = self.parsed_file_review[node.offset]\n            self.add_from_attribute_list(parsed, part, node.offset)\n\n        logging.info('Adding ghost entries from $INDEX_ALLOCATION')\n        # Select only elements with $INDEX_ALLOCATION\n        allocation_it = (\n            node for node in list(part.files.values())\n            if node.offset in self.parsed_file_review and\n            '$INDEX_ALLOCATION' in\n            self.parsed_file_review[node.offset]['attributes']\n        )\n        for node in allocation_it:\n            parsed = self.parsed_file_review[node.offset]\n            self.add_from_indx_allocation(parsed, part)\n\n    def get_partitions(self) -> Dict[int, NTFSPartition]:\n        \"\"\"Get a list of the found partitions.\"\"\"\n        partitioned_files: Dict[int, NTFSPartition] = {}\n        img = DiskScanner.get_image(self)\n\n        logging.info('Parsing MFT entries')\n        for position in self.found_file:\n            dump = sectors(img, position, FILE_size)\n            parsed = parse_file_record(dump)\n            attrs = parsed.get('attributes', {})\n            if not parsed['valid'] or '$FILE_NAME' not in attrs:\n                continue\n\n            # Partition files based on corresponding entry 0\n            if parsed['record_n'] is not None:\n                offset = position - parsed['record_n'] * FILE_size\n                try:\n                    part = partitioned_files[offset]\n                except KeyError:\n                    partitioned_files[offset] = NTFSPartition(self, offset)\n                    part = partitioned_files[offset]\n                attributes = parsed['attributes']\n                if '$DATA' in attributes:\n                    for attribute in attributes['$DATA']:\n                        ads_name = attribute['name']\n                        if ads_name:\n                            part.add_file(NTFSFile(parsed, position, ads=ads_name))\n                \"\"\"Add the file again, just in case the $DATA attributes are\n                missing.\"\"\"\n                part.add_file(NTFSFile(parsed, position))\n\n                # Handle information deduced from INDX records\n                if '$INDEX_ROOT' in attrs:\n                    self.add_from_indx_root(parsed, part)\n                # Save for later use\n                if '$INDEX_ALLOCATION' in attrs or '$ATTRIBUTE_LIST' in attrs:\n                    self.parsed_file_review[position] = parsed\n            # TODO [Future] handle files for which there is no record_number\n\n        # Parse INDX records\n        logging.info('Parsing INDX records')\n        for position in self.found_indx:\n            dump = sectors(img, position, INDX_size)\n            parsed = parse_indx_record(dump)\n            if not parsed['valid']:\n                continue\n\n            entries = parsed['entries']\n            referred = (el['file_info']['parent_entry'] for el in entries)\n            record_n = Counter(referred).most_common(1)[0][0]\n            # Save references for future access\n            self.parsed_indx[position] = {\n                'parent': record_n,\n                'children': set(el['record_n'] for el in entries)\n            }\n\n        indx_info = self.parsed_indx\n        self.indx_list = SparseList({\n            pos: indx_info[pos]['parent'] for pos in indx_info\n        })\n\n        # Extract boot record information\n        logging.info('Reading boot sectors')\n        for index in self.found_boot:\n            dump = sectors(img, index, 1)\n            parsed = unpack(dump, boot_sector_fmt)\n            sec_per_clus = parsed['sectors_per_cluster']\n            self.found_spc.append(sec_per_clus)\n            relative = parsed['MFT_addr'] * sec_per_clus\n            mirr_relative = parsed['MFTmirr_addr'] * sec_per_clus\n            part = None\n            # Look for matching partition, either as boot sector or backup\n            for delta in (0, parsed['sectors']):\n                index = index - delta\n                address = relative + index\n                # Set partition as recoverable\n                if address in partitioned_files:\n                    part = partitioned_files[address]\n                    part.set_recoverable(True)\n                    part.set_size(parsed['sectors'])\n                    part.offset = index\n                    part.sec_per_clus = sec_per_clus\n                    part.mftmirr_pos = mirr_relative + index\n                    break\n\n        # Repair MFT if the mirror is available\n        for address in list(partitioned_files):\n            # This could have been deleted in a previous iteration\n            if address not in partitioned_files:\n                continue\n            part = partitioned_files[address]\n            mirrpos = part.mftmirr_pos\n            if mirrpos is None:\n                entry = part.get(1)     # $MFTMirr\n                if entry is None:\n                    continue\n                else:\n                    # Infer MFT mirror position\n                    dump = sectors(img, entry.offset, FILE_size)\n                    mirror = parse_file_record(dump)\n                    if (mirror['valid'] and 'attributes' in mirror and\n                            '$DATA' in mirror['attributes']):\n                        datas = mirror['attributes']['$DATA']\n                        if (len(datas) == 1 and datas[0]['non_resident'] and\n                                'runlist' in datas[0] and\n                                len(datas[0]['runlist']) > 0 and\n                                'offset' in datas[0]['runlist'][0]):\n                            relative = datas[0]['runlist'][0]['offset']\n                            spc = part.sec_per_clus\n                            if spc is None:\n                                continue\n                            mirrpos = relative * spc + part.offset\n                            part.mftmirr_pos = mirrpos\n\n            self.add_from_mft_mirror(part)\n\n            # Remove bogus partitions generated by MFT mirrors\n            if mirrpos in partitioned_files:\n                bogus = partitioned_files[mirrpos]\n                # Check if it looks like a MFT mirror\n                if len(bogus.files) == 4 and max(bogus.files) < 4:\n                    logging.debug(\n                        'Dropping bogus NTFS partition with MFT '\n                        'position %d generated by MFT mirror of '\n                        'partition at offset %d',\n                        bogus.mft_pos, part.offset\n                    )\n                    partitioned_files.pop(mirrpos)\n\n        # Acquire additional information from $INDEX_ALLOCATION\n        logging.info('Finding partition geometry')\n        most_likely = self.most_likely_sec_per_clus()\n        for address in partitioned_files:\n            part = partitioned_files[address]\n            if part.offset is None:\n                # Find geometry by approximate string matching\n                offset, sec_per_clus = self.find_boundary(\n                    part, address, most_likely\n                )\n                if offset is not None:\n                    part.set_recoverable(True)\n                    part.offset = offset\n                    part.sec_per_clus = sec_per_clus\n            else:\n                offset, sec_per_clus = part.offset, part.sec_per_clus\n            if offset is not None:\n                logging.info(\n                    'Finalizing MFT reconstruction of partition at offset %i',\n                    offset\n                )\n                self.finalize_reconstruction(part)\n\n        # Merge pieces from fragmented MFT\n        for address in list(partitioned_files):\n            # This could have been deleted in a previous iteration\n            if address not in partitioned_files:\n                continue\n            part = partitioned_files[address]\n            entry = part.get(0)     # $MFT\n            if entry is None or part.sec_per_clus is None:\n                continue\n            dump = sectors(img, entry.offset, FILE_size)\n            parsed = parse_file_record(dump)\n            if not parsed['valid'] or 'attributes' not in parsed:\n                continue\n\n            if '$ATTRIBUTE_LIST' in parsed['attributes']:\n                _integrate_attribute_list(parsed, part, img)\n            attrs = parsed['attributes']\n            if '$DATA' not in attrs or len(attrs['$DATA']) < 1:\n                continue\n\n            if 'runlist' not in attrs['$DATA'][0]:\n                continue\n            runlist = attrs['$DATA'][0]['runlist']\n            if len(runlist) > 1:\n                logging.info(\n                    'MFT for partition at offset %d is fragmented. Trying to '\n                    'merge %d parts...', part.offset, len(runlist)\n                )\n                clusters_pos = runlist[0]['offset']\n                spc = part.sec_per_clus\n                size = runlist[0]['length']\n                for entry in runlist[1:]:\n                    clusters_pos += entry['offset']\n                    real_pos = clusters_pos * part.sec_per_clus + part.offset\n                    position = real_pos - size*spc\n                    if position in partitioned_files:\n                        piece = partitioned_files[position]\n                        if piece.offset is None or piece.offset == part.offset:\n                            conflicts = [\n                                i for i in piece.files if\n                                not piece.files[i].is_ghost and\n                                i in part.files and\n                                not part.files[i].is_ghost\n                            ]\n                            if not len(conflicts):\n                                logging.debug(\n                                    'Merging partition with MFT offset %d into'\n                                    ' %s (fragmented MFT)', piece.mft_pos, part\n                                )\n                                # Merge the partitions\n                                merge(part, piece)\n                                # Remove the fragment\n                                partitioned_files.pop(position)\n                            else:\n                                logging.debug(\n                                    'NOT merging partition with MFT offset %d into'\n                                    ' %s (possible fragmented MFT) due to conflicts', piece.mft_pos, part\n                                )\n                    size += entry['length']\n\n        return partitioned_files\n"
  },
  {
    "path": "recuperabit/fs/ntfs_fmt.py",
    "content": "\"\"\"NTFS format descriptors.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nfrom datetime import datetime, timezone, timedelta\n\nfrom ..utils import printable, unpack\n\n\ntime_start = datetime(1601, 1, 1, tzinfo=timezone.utc)\n\ndef printable_name(name):\n    \"\"\"Return a printable name decoded in UTF-16.\"\"\"\n    decoded = []\n    parts = (name[i:i+2] for i in range(0, len(name), 2))\n    for part in parts:\n        try:\n            decoded.append(part.decode('utf-16'))\n        except UnicodeDecodeError:\n            decoded.append('\\x00')\n    joined = ''.join(decoded)\n    # basic check for false positives\n    if '\\x00\\x00\\x00' in joined:\n        return None\n    return printable(joined, '#')\n\n\ndef windows_time(timestamp):\n    \"\"\"Convert a date-time value from Microsoft filetime to UTC.\"\"\"\n    try:\n        value = int.from_bytes(timestamp, byteorder='little', signed=False)\n        converted = time_start + timedelta(milliseconds = value//10000)\n        return converted\n    except (ValueError, OverflowError, OSError):\n        return None\n\n\ndef index_entries(dump):\n    \"\"\"Interpret the entries of an index.\"\"\"\n    offset = 0\n    entries = []\n    while offset < len(dump):\n        parsed = unpack(dump[offset:], indx_dir_entry_fmt)\n        filename = parsed['$FILE_NAME']\n        entry_length = parsed['entry_length']\n        valid_length = entry_length > 0\n        has_name = 'name' in filename\n        valid_name = has_name and len(filename['name']) > 0\n        if valid_length and valid_name:\n            if parsed['content_length']:\n                entries.append(parsed)\n            offset += entry_length\n        else:\n            break\n        # Last entry\n        if parsed['flags'] & 0x2:\n            break\n        # TODO handle carving of remnant entries in slack space\n    return entries\n\n\ndef index_root_parser(dump):\n    \"\"\"Parse the entries contained in a $INDEX_ROOT attribute.\"\"\"\n    header = unpack(dump, indx_header_fmt)\n    offset = header['off_start_list']\n    entries = index_entries(dump[offset:])\n    return entries\n\n\ndef runlist_unpack(runlist):\n    \"\"\"Parse an attribute runlist.\"\"\"\n    pieces = []\n    while len(runlist) and runlist[0] != 0:\n        off_bytes, len_bytes = divmod(runlist[0], 2**4)\n        end = len_bytes + off_bytes\n        decoded = unpack(runlist, [\n            ('length', ('i', 1, len_bytes)),\n            ('offset', ('+i', len_bytes + 1, end))\n        ])\n        if decoded['length'] is None or decoded['offset'] is None:\n            break\n        pieces.append(decoded)\n        runlist = runlist[end+1:]\n    return pieces\n\n\ndef attribute_list_parser(dump):\n    \"\"\"Parse entries contained in a $ATTRIBUTE_LIST attribute.\"\"\"\n    content = []\n    while len(dump):\n        decoded = unpack(dump, [\n            ('type', ('i', 0, 3)),\n            ('length', ('i', 4, 5)),\n            ('name_length', ('i', 6, 6)),\n            ('name_off', ('i', 7, 7)),\n            ('start_VCN', ('i', 8, 15)),\n            ('file_ref', ('i', 16, 19)),\n            ('id', ('i', 24, 24))\n        ])\n        length = decoded['length']\n        # Check either if the length is 0 or if it is None\n        if not length:\n            break\n        content.append(decoded)\n        dump = dump[length:]\n    return content\n\n\ndef try_filename(dump):\n    \"\"\"Try to parse a $FILE_NAME attribute.\"\"\"\n    try:\n        unpack(dump, attr_types_fmt['$FILE_NAME'])\n    except TypeError:   # Broken attribute\n        return {}\n\nentry_fmt = [\n    ('signature', ('s', 0, 3)),\n    ('off_fixup', ('i', 4, 5)),\n    ('n_entries', ('i', 6, 7)),\n    ('LSN', ('i', 8, 15)),\n    ('seq_val', ('i', 16, 17)),\n    ('link_count', ('i', 18, 19)),\n    ('off_first', ('i', 20, 21)),\n    ('flags', ('i', 22, 23)),\n    ('size_used', ('i', 24, 27)),\n    ('size_alloc', ('i', 28, 31)),\n    ('base_record', ('i', 32, 35)),\n    ('record_n', ('i', 44, 47))   # Available only for NTFS >= 3.1\n]\n\nboot_sector_fmt = [\n    ('OEM_name', ('s', 3, 10)),\n    ('bytes_per_sector', ('i', 11, 12)),\n    ('sectors_per_cluster', ('i', 13, 13)),\n    ('sectors', ('i', 40, 47)),\n    ('MFT_addr', ('i', 48, 55)),\n    ('MFTmirr_addr', ('i', 56, 63)),\n    ('MFT_entry_size', ('i', 64, 64)),\n    ('idx_size', ('i', 68, 68)),\n    ('signature', ('s', 510, 511))\n]\n\nindx_fmt = [\n    ('signature', ('s', 0, 3)),\n    ('off_fixup', ('i', 4, 5)),\n    ('n_entries', ('i', 6, 7)),\n    ('LSN', ('i', 8, 15)),\n    ('seq_val', ('i', 16, 17))\n]\n\nindx_header_fmt = [\n    ('off_start_list', ('i', 0, 3)),\n    ('off_end_list', ('i', 4, 7)),\n    ('off_end_buffer', ('i', 8, 11)),\n    ('flags', ('i', 12, 15))\n]\n\nindx_dir_entry_fmt = [\n    ('record_n', ('i', 0, 3)),\n    ('entry_length', ('i', 8, 9)),\n    ('content_length', ('i', 10, 11)),\n    ('flags', ('i', 12, 15)),\n    ('$FILE_NAME', (\n        try_filename, 16, lambda r: 15 + (\n            r['content_length'] if r['content_length'] is not None else 0\n        )\n    ))\n    # The following is not very useful so it's not worth computing\n    # 'VCN_child', (\n    #     lambda s: int(str(s[::-1]).encode('hex'),16) if len(s) else None,\n    #     lambda r: r['entry_length'] - (8 if r['flags'] & 0x1 else 0),\n    #     lambda r: r['entry_length']\n    # )\n]\n\nattr_header_fmt = [\n    ('type', ('i', 0, 3)),\n    ('length', ('i', 4, 7)),\n    ('non_resident', ('i', 8, 8)),\n    ('name_length', ('i', 9, 9)),\n    ('name_off', ('i', 10, 11)),\n    ('flags', ('i', 12, 13)),\n    ('id', ('i', 14, 15)),\n    ('name', (\n        printable_name,\n        lambda r: r['name_off'],\n        lambda r: r['name_off'] + r['name_length']*2 - 1\n    ))\n]\n\nattr_resident_fmt = [\n    ('content_size', ('i', 16, 19)),\n    ('content_off', ('i', 20, 21))\n]\n\nattr_nonresident_fmt = [\n    ('start_VCN', ('i', 16, 23)),\n    ('end_VCN', ('i', 24, 31)),\n    ('runlist_offset', ('i', 32, 33)),\n    ('compression_unit', ('i', 34, 35)),\n    ('allocated_size', ('i', 40, 47)),\n    ('real_size', ('i', 48, 55)),\n    ('initialized_size', ('i', 56, 63)),\n    ('runlist', (\n        runlist_unpack,\n        lambda r: r['runlist_offset'],\n        lambda r: r['allocated_size']\n    ))\n]\n\nattr_names = {\n    16: '$STANDARD_INFORMATION',\n    32: '$ATTRIBUTE_LIST',\n    48: '$FILE_NAME',\n    80: '$SECURITY_DESCRIPTOR',\n    96: '$VOLUME_NAME',\n    112: '$VOLUME_INFORMATION',\n    128: '$DATA',\n    144: '$INDEX_ROOT',\n    160: '$INDEX_ALLOCATION',\n    176: '$BITMAP'\n}\n\n# This structure extracts only interesting attributes.\nattr_types_fmt = {\n    '$STANDARD_INFORMATION': [\n        ('creation_time', (windows_time, 0, 7)),\n        ('modification_time', (windows_time, 8, 15)),\n        ('MFT_modification_time', (windows_time, 16, 23)),\n        ('access_time', (windows_time, 24, 31)),\n        ('flags', ('i', 32, 35))\n    ],\n    '$ATTRIBUTE_LIST': [\n        ('entries', (attribute_list_parser, 0, 1024))\n    ],\n    '$FILE_NAME': [\n        ('parent_entry', ('i', 0, 5)),\n        ('parent_seq', ('i', 6, 7)),\n        ('creation_time', (windows_time, 8, 15)),\n        ('modification_time', (windows_time, 16, 23)),\n        ('MFT_modification_time', (windows_time, 24, 31)),\n        ('access_time', (windows_time, 32, 39)),\n        ('allocated_size', ('i', 40, 47)),\n        ('real_size', ('i', 48, 55)),\n        ('flags', ('i', 56, 59)),\n        ('name_length', ('i', 64, 64)),\n        ('namespace', ('i', 65, 65)),\n        ('name', (printable_name, 66, lambda r: r['name_length']*2 + 65))\n    ],\n    '$INDEX_ROOT': [\n        ('attr_type', ('i', 0, 3)),\n        ('sorting_rule', ('i', 4, 7)),\n        ('record_bytes', ('i', 8, 11)),\n        ('record_clusters', ('i', 12, 12)),\n        ('records', (index_root_parser, 16, lambda r: r['record_bytes']))\n    ]\n}\n"
  },
  {
    "path": "recuperabit/logic.py",
    "content": "\"\"\"Filesystem-independent algorithmic logic.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nimport bisect\nimport codecs\nimport logging\nimport os\nimport os.path\nimport sys\nimport time\nimport types\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, Iterator, Set, Tuple, TypeVar, Generic\n\nT = TypeVar('T')\n\nif TYPE_CHECKING:\n    from .fs.core_types import File, Partition\n\n\nclass SparseList(Generic[T]):\n    \"\"\"List which only stores values at some places.\"\"\"\n    def __init__(self, data: Optional[Dict[int, T]] = None, default: Optional[T] = None) -> None:\n        self.keys: List[int] = []  # This is always kept in order\n        self.elements: Dict[int, T] = {}\n        self.default: Optional[T] = default\n        if data is not None:\n            self.keys = sorted(data)\n            self.elements.update(data)\n\n    def __len__(self) -> int:\n        try:\n            return self.keys[-1] + 1\n        except IndexError:\n            return 0\n\n    def __getitem__(self, index: int) -> Optional[T]:\n        return self.elements.get(index, self.default)\n\n    def __setitem__(self, index: int, item: T) -> None:\n        if item == self.default:\n            if index in self.elements:\n                del self.elements[index]\n                del self.keys[bisect.bisect_left(self.keys, index)]\n        else:\n            if index not in self.elements:\n                bisect.insort(self.keys, index)\n            self.elements[index] = item\n\n    def __contains__(self, element: T) -> bool:\n        return element in self.elements.values()\n\n    def __iter__(self) -> Iterator[int]:\n        return self.keys.__iter__()\n\n    def __repr__(self) -> str:\n        elems = []\n        prevk = 0\n        if len(self.elements) > 0:\n            k = self.keys[0]\n            elems.append(str(k) + ' -> ' + repr(self.elements[k]))\n            prevk = self.keys[0]\n        for i in range(1, len(self.elements)):\n            nextk = self.keys[i]\n            if nextk <= prevk + 2:\n                while prevk < nextk - 1:\n                    elems.append('__')\n                    prevk += 1\n                elems.append(repr(self.elements[nextk]))\n            else:\n                elems.append('\\n... ' + str(nextk) + ' -> ' +\n                             repr(self.elements[nextk]))\n            prevk = nextk\n\n        return '[' + ', '.join(elems) + ']'\n\n    def iterkeys(self) -> Iterator[int]:\n        \"\"\"An iterator over the keys of actual elements.\"\"\"\n        return self.__iter__()\n\n    def iterkeys_rev(self) -> Iterator[int]:\n        \"\"\"An iterator over the keys of actual elements (reversed).\"\"\"\n        i = len(self.keys)\n        while i > 0:\n            i -= 1\n            yield self.keys[i]\n\n    def itervalues(self) -> Iterator[T]:\n        \"\"\"An iterator over the elements.\"\"\"\n        for k in self.keys:\n            yield self.elements[k]\n\n    def wipe_interval(self, bottom: int, top: int) -> None:\n        \"\"\"Remove elements between bottom and top.\"\"\"\n        new_keys = set()\n        if bottom > top:\n            for k in self.keys:\n                if top <= k < bottom:\n                    new_keys.add(k)\n                else:\n                    del self.elements[k]\n        else:\n            for k in self.keys:\n                if bottom <= k < top:\n                    del self.elements[k]\n                else:\n                    new_keys.add(k)\n        self.keys = sorted(new_keys)\n\n\ndef preprocess_pattern(pattern: SparseList[T]) -> Dict[T, List[int]]:\n    \"\"\"Preprocess a SparseList for approximate string matching.\n\n    This function performs preprocessing for the Baeza-Yates--Perleberg\n    fast and practical approximate string matching algorithm.\"\"\"\n    result: Dict[T, List[int]] = {}\n    length = pattern.__len__()\n    for k in pattern:\n        name = pattern[k]\n        if name not in result:\n            result[name] = [length-k-1]\n        elif name != result[name][-1]:\n            result[name].append(length-k-1)\n    return result\n\n\ndef approximate_matching(records: SparseList[T], pattern: SparseList[T], stop: int, k: int = 1) -> Optional[List[Union[Set[int], int, float]]]:\n    \"\"\"Find the best match for a given pattern.\n\n    The Baeza-Yates--Perleberg algorithm requires a preprocessed pattern. This\n    function takes as input a SparseList of records and pattern that will be\n    preprocessed. The records in the SparseList should be formed by single\n    elements. If they have another shape, e.g. tuples of the form\n    (namespace, name), the get function can be used to tell the algorithm how\n    to access them. k is the minimum value for support.\"\"\"\n\n    msize = pattern.__len__()\n    if records.__len__() == 0 or msize == 0:\n        return None\n\n    lookup = preprocess_pattern(pattern)\n    count: SparseList[int] = SparseList(default=0)\n    match_offsets: Set[int] = set()\n\n    i = 0\n    j = 0   # previous value of i\n\n    # logging.debug('Starting approximate matching up to %i', stop)\n    # Loop only on indexes where there are elements\n    for i in records:\n        if i > stop+msize-1:\n            break\n\n        # zero-out the parts that were skipped\n        count.wipe_interval(j % msize, i % msize)\n        j = i\n\n        offsets = set(lookup.get(records[i], []))\n        for off in offsets:\n            count[(i + off) % msize] += 1\n            score = count[(i + off) % msize]\n            if score == k:\n                match_offsets.add(i+off-msize+1)\n            if score > k:\n                k = score\n                match_offsets = set([i+off-msize+1])\n\n    if len(match_offsets):\n        logging.debug(\n            'Found MATCH in positions {} '\n            'with weight {} ({}%)'.format(\n                match_offsets, k,\n                k * 100.0 / len(pattern.keys)\n            )\n        )\n        return [match_offsets, k, float(k) / len(pattern.keys)]\n    else:\n        # logging.debug('No match found')\n        return None\n\n\ndef makedirs(path: str) -> bool:\n    \"\"\"Make directories if they do not exist.\"\"\"\n    try:\n        os.makedirs(path)\n    except OSError:\n        _, value, _ = sys.exc_info()\n        # The directory already exists = no problem\n        if value.errno != 17:\n            logging.error(value)\n            return False\n    return True\n\n\ndef recursive_restore(node: 'File', part: 'Partition', outputdir: str, make_dirs: bool = True) -> None:\n    \"\"\"Restore a directory structure starting from a file node.\"\"\"\n    parent_path = str(\n        part[node.parent].full_path(part) if node.parent is not None\n        else ''\n    )\n\n    file_path = os.path.join(parent_path, node.name)\n    restore_parent_path = os.path.join(outputdir, parent_path)\n    restore_path = os.path.join(outputdir, file_path)\n\n    try:\n        content = node.get_content(part)\n    except NotImplementedError:\n        logging.error(u'Restore of #%s %s is not supported', node.index,\n                      file_path)\n        content = None\n\n    if make_dirs:\n        if not makedirs(restore_parent_path):\n            return\n\n    is_directory = node.is_directory or len(node.children) > 0\n\n    if is_directory:\n        logging.info(u'Restoring #%s %s', node.index, file_path)\n        if not makedirs(restore_path):\n            return\n\n    if is_directory and content is not None:\n        logging.warning(u'Directory %s has data content!', file_path)\n        restore_path += '_recuperabit_content'\n\n    try:\n        if content is not None:\n            logging.info(u'Restoring #%s %s', node.index, file_path)\n            with codecs.open(restore_path, 'wb') as outfile:\n                if isinstance(content, types.GeneratorType):\n                    for piece in content:\n                        outfile.write(piece)\n                else:\n                    outfile.write(content)\n        else:\n            if not is_directory:\n                # Empty file\n                open(restore_path, 'wb').close()\n    except IOError:\n        logging.error(u'IOError when trying to create %s', restore_path)\n\n    try:\n        # Restore Modification + Access time\n        mtime, atime, _ = node.get_mac()\n        if mtime is not None:\n            atime = time.mktime(atime.astimezone().timetuple())\n            mtime = time.mktime(mtime.astimezone().timetuple())\n            os.utime(restore_path, (atime, mtime))\n    except IOError:\n        logging.error(u'IOError while setting atime and mtime of %s', restore_path)\n\n    if is_directory:\n        for child in node.children:\n            if not child.ignore():\n                recursive_restore(child, part, outputdir, make_dirs=False)\n            else:\n                logging.info(u'Skipping ignored file {}'.format(child))\n"
  },
  {
    "path": "recuperabit/utils.py",
    "content": "\"\"\"Collection of utility functions.\"\"\"\n\n# RecuperaBit\n# Copyright 2014-2021 Andrea Lazzarotto\n#\n# This file is part of RecuperaBit.\n#\n# RecuperaBit 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# RecuperaBit 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 RecuperaBit. If not, see <http://www.gnu.org/licenses/>.\n\n\nfrom datetime import datetime\nimport logging\nimport pprint\nimport string\nimport sys\nimport time\nfrom typing import TYPE_CHECKING, Any, Iterable, Optional, List, Dict, Tuple, Union, Callable\nimport unicodedata\nimport io\n\nfrom .fs.constants import sector_size\n\nprinter: pprint.PrettyPrinter = pprint.PrettyPrinter(indent=4)\nall_chars = (chr(i) for i in range(sys.maxunicode))\nunicode_printable: set[str] = set(\n    c for c in all_chars\n    if not unicodedata.category(c)[0].startswith('C')\n)\nascii_printable: set[str] = set(string.printable[:-5])\n\nif TYPE_CHECKING:\n    from .fs.core_types import File, Partition\n\n\ndef sectors(image: io.BufferedReader, offset: int, size: int, bsize: int = sector_size, fill: bool = True) -> Optional[bytearray]:\n    \"\"\"Read from a file descriptor.\"\"\"\n    read = True\n    try:\n        image.seek(offset * bsize)\n    except (IOError, OverflowError, ValueError):\n        read = False\n    if read:\n        try:\n            dump = image.read(size * bsize)\n        except (IOError, MemoryError):\n            logging.warning(\n                \"Cannot read sector(s). Filling with 0x00. Offset: {} Size: \"\n                \"{} Bsize: {}\".format(offset, size, bsize)\n            )\n            read = False\n    if not read:\n        if fill:\n            dump = size * bsize * b'\\x00'\n        else:\n            return None\n    return bytearray(dump)\n\ndef unixtime(dtime: Optional[datetime]) -> float:\n    \"\"\"Convert datetime to UNIX epoch.\"\"\"\n    if dtime is None:\n        return 0.0\n    try:\n        return time.mktime(dtime.timetuple())\n    except ValueError:\n        return 0.0\n\n\n# format:\n# [(label, (formatter, lower, higher)), ...]\ndef unpack(data: bytes, fmt: List[Tuple[str, Tuple[Union[str, Callable[[bytes], Any]], Union[int, Callable[[Dict[str, Any]], Optional[int]]], Union[int, Callable[[Dict[str, Any]], Optional[int]]]]]]) -> Dict[str, Any]:\n    \"\"\"Extract formatted information from a string of bytes.\"\"\"\n    result: Dict[str, Any] = {}\n    for label, description in fmt:\n        formatter, lower, higher = description\n        # If lower is a function, then apply it\n        low = lower(result) if callable(lower) else lower\n        high = higher(result) if callable(higher) else higher\n\n        if low is None or high is None:\n            result[label] = None\n            continue\n\n        if callable(formatter):\n            result[label] = formatter(data[low:high+1])\n        else:\n            if formatter == 's':\n                result[label] = str(data[low:high+1])\n            if formatter.startswith('utf'):\n                result[label] = data[low:high+1].decode(formatter)\n            if formatter.endswith('i') and len(formatter) < 4:\n                # Use little-endian by default. Big-endian with >i.\n                # Force sign-extension of first bit with >+i / +i.\n                chunk = data[low:high+1]\n\n                signed = False\n                if '+' in formatter:\n                    signed = True\n\n                byteorder = 'little'\n                if formatter.startswith('>'):\n                    byteorder = 'big'\n\n                if len(chunk):\n                    result[label] = int.from_bytes(chunk, byteorder=byteorder, signed=signed)\n                else:\n                    result[label] = None\n    return result\n\n\ndef feed_all(image: io.BufferedReader, scanners: List[Any], indexes: Iterable[int]) -> List[int]:\n    # Scan the disk image and feed the scanners\n    interesting: List[int] = []\n    for index in indexes:\n        sector = sectors(image, index, 1, fill=False)\n        if not sector:\n            break\n\n        for instance in scanners:\n            res = instance.feed(index, sector)\n            if res is not None:\n                logging.info('Found {} at sector {}'.format(res, index))\n                interesting.append(index)\n    return interesting\n\n\ndef printable(text: str, default: str = '.', alphabet: Optional[set[str]] = None) -> str:\n    \"\"\"Replace unprintable characters in a text with a default one.\"\"\"\n    if alphabet is None:\n        alphabet = unicode_printable\n    return ''.join((i if i in alphabet else default) for i in text)\n\n\n\n\n\n\n\ndef readable_bytes(amount: Optional[int]) -> str:\n    \"\"\"Return a human readable string representing a size in bytes.\"\"\"\n    if amount is None:\n        return '??? B'\n    if amount < 1:\n        return '%.2f B' % amount\n    powers = {\n        0: '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'\n    }\n    biggest = max(i for i in powers if amount / 1024.**i >= 1)\n    scaled = amount / 1024.**biggest\n    return '%.2f %sB' % (scaled, powers[biggest])\n\n\ndef _file_tree_repr(node: 'File') -> str:\n    \"\"\"Give a nice representation for the tree.\"\"\"\n    desc = (\n        ' [GHOST]' if node.is_ghost else\n        ' [DELETED]' if node.is_deleted else ''\n    )\n    tail = '/' if node.is_directory else ''\n    data = [\n        ('Id', node.index),\n        ('Offset', node.offset),\n        (\n            'Offset bytes',\n            node.offset * sector_size\n            if node.offset is not None else None\n        )\n        # ('MAC', node.mac)\n    ]\n    if not node.is_directory:\n        data += [('Size', readable_bytes(node.size))]\n    return u'%s%s (%s) %s' % (\n        node.name, tail, ', '.join(a + ': ' + str(b) for a, b in data), desc\n    )\n\n\ndef tree_folder(directory: 'File', padding: int = 0) -> str:\n    \"\"\"Return a tree-like textual representation of a directory.\"\"\"\n    lines: List[str] = []\n    pad = ' ' * padding\n    lines.append(\n        pad + _file_tree_repr(directory)\n    )\n    padding = padding + 2\n    pad = ' ' * padding\n    for entry in directory.children:\n        if len(entry.children) or entry.is_directory:\n            lines.append(tree_folder(entry, padding))\n        else:\n            lines.append(\n                pad + _file_tree_repr(entry)\n            )\n    return '\\n'.join(lines)\n\n\ndef _bodyfile_repr(node: 'File', path: str) -> str:\n    \"\"\"Return a body file line for node.\"\"\"\n    end = '/' if node.is_directory or len(node.children) else ''\n    return '|'.join(str(el) for el in [\n        '0',                        # MD5\n        path + node.name + end,     # name\n        node.index,                 # inode\n        '0', '0', '0',              # mode, UID, GID\n        node.size if node.size is not None else 0,\n        unixtime(node.mac['access']),\n        unixtime(node.mac['modification']),\n        unixtime(node.mac['creation']),\n        '0'\n    ])\n\n\ndef bodyfile_folder(directory: 'File', path: str = '') -> List[str]:\n    \"\"\"Create a body file compatible with TSK 3.x.\n\n    Format:\n    '#MD5|name|inode|mode_as_string|UID|GID|size|atime|mtime|ctime|crtime'\n    See also: http://wiki.sleuthkit.org/index.php?title=Body_file\"\"\"\n    lines: List[str] = [_bodyfile_repr(directory, path)]\n    path += directory.name + '/'\n    for entry in directory.children:\n        if len(entry.children) or entry.is_directory:\n            lines += bodyfile_folder(entry, path)\n        else:\n            lines.append(_bodyfile_repr(entry, path))\n    return lines\n\n\ndef _ltx_clean(label: Any) -> str:\n    \"\"\"Small filter to prepare strings to be included in LaTeX code.\"\"\"\n    clean = str(label).replace('$', r'\\$').replace('_', r'\\_')\n    if clean[0] == '-':\n        clean = r'\\textminus{}' + clean[1:]\n    return clean\n\n\ndef _tikz_repr(node: 'File') -> str:\n    \"\"\"Represent the node for a Tikz diagram.\"\"\"\n    return r'node %s{%s\\enskip{}%s}' % (\n        '[ghost]' if node.is_ghost else '[deleted]' if node.is_deleted else '',\n        _ltx_clean(node.index), _ltx_clean(node.name)\n    )\n\n\ndef tikz_child(directory: 'File', padding: int = 0) -> Tuple[str, int]:\n    \"\"\"Write a child row for Tikz representation.\"\"\"\n    pad = ' ' * padding\n    lines: List[str] = [r'%schild {%s' % (pad, _tikz_repr(directory))]\n    count: int = len(directory.children)\n    for entry in directory.children:\n        content, number = tikz_child(entry, padding+4)\n        lines.append(content)\n        count += number\n    lines.append('}')\n    for entry in range(count):\n        lines.append('child [missing] {}')\n    return '\\n'.join(lines).replace('\\n}', '}'), count\n\n\ndef tikz_part(part: 'Partition') -> str:\n    \"\"\"Create LaTeX code to represent the directory structure as a nice Tikz\n    diagram.\n\n    See also: http://www.texample.net/tikz/examples/filesystem-tree/\"\"\"\n\n    preamble = (r\"\"\"%\\usepackage{tikz}\n    %\\usetikzlibrary{trees}\"\"\")\n\n    begin_tree = r\"\"\"\\begin{tikzpicture}[%\n    grow via three points={one child at (1.75em,-1.75em) and\n    two children at (1.75em,-1.75em) and (1.75em,-3.5em)},\n    edge from parent path={(\\tikzparentnode.south) |- (\\tikzchildnode.west)}]\n    \\scriptsize\n    \"\"\"\n    end_tree = r\"\"\"\\end{tikzpicture}\"\"\"\n\n    lines = [r'\\node [root] {File System Structure}']\n    lines += [tikz_child(entry, 4)[0] for entry in (part.root, part.lost)]\n    lines.append(';')\n\n    return '%s\\n\\n%s\\n%s\\n%s' % (\n        preamble, begin_tree, '\\n'.join(lines), end_tree\n    )\n\n\ndef csv_part(part: 'Partition') -> list[str]:\n    \"\"\"Provide a CSV representation for a partition.\"\"\"\n    contents = [\n        ','.join(('Id', 'Parent', 'Name', 'Full Path', 'Modification Time',\n                  'Access Time', 'Creation Time', 'Size (bytes)',\n                  'Size (human)', 'Offset (bytes)', 'Offset (sectors)',\n                  'Directory', 'Deleted', 'Ghost'))\n    ]\n    for index in part.files:\n        obj = part.files[index]\n        contents.append(\n                u'%s,%s,\"%s\",\"%s\",%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (\n                    obj.index, obj.parent, obj.name,\n                    obj.full_path(part),\n                    obj.mac['modification'], obj.mac['access'],\n                    obj.mac['creation'], obj.size,\n                    readable_bytes(obj.size),\n                    (obj.offset * sector_size\n                     if obj.offset is not None else None),\n                    obj.offset,\n                    '1' if obj.is_directory else '',\n                    '1' if obj.is_deleted else '',\n                    '1' if obj.is_ghost else ''\n                )\n        )\n    return contents\n\n\ndef _sub_locate(text: str, directory: 'File', part: 'Partition') -> List[Tuple['File', str]]:\n    \"\"\"Helper for locate.\"\"\"\n    lines: List[Tuple['File', str]] = []\n    for entry in sorted(directory.children, key=lambda node: node.name):\n        path = entry.full_path(part)\n        if text in path.lower():\n            lines.append((entry, path))\n        if len(entry.children) or entry.is_directory:\n            lines += _sub_locate(text, entry, part)\n    return lines\n\n\ndef locate(part: 'Partition', text: str) -> List[Tuple['File', str]]:\n    \"\"\"Return paths of files matching the text.\"\"\"\n    lines: List[Tuple['File', str]] = []\n    text = text.lower()\n    lines += _sub_locate(text, part.lost, part)\n    lines += _sub_locate(text, part.root, part)\n    return lines\n\n\ndef merge(part: 'Partition', piece: 'Partition') -> None:\n    \"\"\"Merge piece into part (both are partitions).\"\"\"\n    for index in piece.files:\n        if (\n            index not in part.files or\n            part.files[index].is_ghost\n        ):\n            part.add_file(piece.files[index])\n"
  }
]