pax_global_header00006660000000000000000000000064134516043450014517gustar00rootroot0000000000000052 comment=1016998b0a6991e049d379330f9550b9d61dda88 librecaptcha-0.6.2/000077500000000000000000000000001345160434500141455ustar00rootroot00000000000000librecaptcha-0.6.2/.gitignore000066400000000000000000000020641345160434500161370ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv .venv/ venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject # Vim swap files *.swp librecaptcha-0.6.2/LICENSE000066400000000000000000001045131345160434500151560ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . librecaptcha-0.6.2/MANIFEST.in000066400000000000000000000014351345160434500157060ustar00rootroot00000000000000# Copyright (C) 2016, 2018 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . include LICENSE global-exclude *.pyc global-exclude /.* librecaptcha-0.6.2/README.rst000066400000000000000000000131461345160434500156410ustar00rootroot00000000000000librecaptcha ============ Version 0.6.2 librecaptcha is a free/libre program and library that allows you to solve `reCAPTCHA`_ challenges. *librecaptcha does not automatically solve challenges and is not designed to make it easier to do so—it provides an interface through which a human can solve the challenges without proprietary software.* .. _reCAPTCHA: https://en.wikipedia.org/wiki/ReCAPTCHA Installation ------------ From PyPI ~~~~~~~~~ Install with `pip`_:: sudo pip3 install librecaptcha[gtk] To install locally, run without ``sudo`` and add the ``--user`` option. You can omit ``[gtk]`` if you don’t want to install the GTK 3 GUI. From the Git repository ~~~~~~~~~~~~~~~~~~~~~~~ Clone the repository with the following commands (you’ll need to have `Git`_ installed):: git clone https://github.com/nickolas360/librecaptcha cd librecaptcha Then install with `pip`_:: sudo pip3 install .[gtk] To install locally, run without ``sudo`` and add the ``--user`` option. You can omit ``[gtk]`` if you don’t want to install the GTK 3 GUI. Run without installing ~~~~~~~~~~~~~~~~~~~~~~ Run the first set of commands in the previous section to clone the repository. Then, install the required dependencies by running:: sudo pip3 install -r requirements.txt To install the dependencies locally, run without ``sudo`` and add ``--user``. .. _pip: https://pip.pypa.io .. _Git: https://git-scm.com Usage ----- If you installed librecaptcha, you can simply run ``librecaptcha``. Otherwise, run ``./librecaptcha.py``. Pass the ``--help`` option to show usage information. If you’d like to use the GUI, be sure to pass the ``--gui`` option. To use librecaptcha programmatically, import it:: import librecaptcha and then call ``librecaptcha.get_token()``. Its signature is:: get_token( api_key: str, site_url: str, user_agent: str, *, gui=False, debug=False, ) -> str Parameters: * ``api_key``: The reCAPTCHA API key to use. This is usually the value of the ``data-sitekey`` HTML attribute. * ``site_url``: The base URL of the site that contains the reCAPTCHA challenge. This should start with ``http://`` or ``https://`` and include the hostname. Everything after the hostname is optional. For example: ``https://example.com`` * ``user_agent``: The user-agent string to use. This should match the user-agent used when sending the request that requires a reCAPTCHA token. You can generate a random user-agent string with ``librecaptcha.random_user_agent()``. * ``gui``: Whether to use the GTK 3 GUI (as opposed to the CLI). The CLI writes to standard output and reads from standard input. * ``debug``: Whether to print debug information. Returns: A reCAPTCHA token. This should usually be submitted with the form as the value of the ``g-recaptcha-response`` field. These tokens usually expire after a couple of minutes. Notes ----- librecaptcha currently supports two types of challenges: *dynamic* and *multicaptcha*. *dynamic* challenges present you with a grid of different images and ask you to select the images that match the given description. Each time you click an image, a new one takes its place. Usually, three images from the initial set match the description, and at least one of the replacement images does as well. *multicaptcha* challenges present you with one large image split into a grid of tiles and ask you to select the tiles that contain a given object. Occasionally, the image will not contain the object, but rather something that looks similar. It is possible to select no tiles in this case, but reCAPTCHA may have been fooled by the similar-looking object and would reject a selection of no tiles. **Note:** Even when all challenges are completed and a token is obtained, the token may still be rejected when used. If this happens, simply try again. Waiting a while may also help. Unfortunately, you may have to try many times—perhaps even ten. What’s new ---------- Version 0.6.0: * Added ``librecaptcha.has_gui()``, which returns whether the GUI can be used. * Improved cross-platform support for the CLI. Version 0.5.0: * Added a GTK 3 GUI (thanks, cyclopsian!). * ``get_token()`` now has an optional ``gui`` parameter. * ``get_token()`` now requires a user-agent string. * ``librecaptcha.py`` now has a ``--gui`` option. * ``librecaptcha.py`` now accepts an optional ```` argument. If not provided, a random user-agent string is chosen and shown. Version 0.4.0: * Image windows are now automatically closed when questions are answered. Version 0.3.x: * Fixed possible encoding issue in ``setup.py``. * librecaptcha can now be installed from PyPI, or from the Git repository with pip or ``setup.py``. Version 0.2.x: * Updated user-agent list. * The current reCAPTCHA version is now fetched during initialization and no longer needs to be manually updated. Dependencies ------------ * `Python`_ ≥ 3.5 * The following Python packages (the installation instructions above handle installing these): - `Pillow`_ ≥ 4.1.1 - `requests`_ ≥ 2.18.1 - `slimit`_ ≥ 0.8.1 - `PyGObject`_ ≥ 3.30.0 (only for GUI) .. _Python: https://www.python.org/ .. _Pillow: https://pypi.org/project/Pillow/ .. _requests: https://pypi.org/project/requests/ .. _slimit: https://pypi.org/project/slimit/ .. _PyGObject: https://pypi.org/project/PyGObject/ License ------- librecaptcha is licensed under the GNU General Public License, version 3 or any later version. See `LICENSE`_. This README file has been released to the public domain using `CC0`_. .. _LICENSE: LICENSE .. _CC0: https://creativecommons.org/publicdomain/zero/1.0/ librecaptcha-0.6.2/librecaptcha.py000077500000000000000000000015111345160434500171410ustar00rootroot00000000000000#!/usr/bin/env python3 # Copyright (C) 2017-2018 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from librecaptcha.__main__ import main if __name__ == "__main__": main() librecaptcha-0.6.2/librecaptcha/000077500000000000000000000000001345160434500165665ustar00rootroot00000000000000librecaptcha-0.6.2/librecaptcha/__init__.py000066400000000000000000000017321345160434500207020ustar00rootroot00000000000000# Copyright (C) 2017-2018 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . # flake8: noqa from . import librecaptcha, extract_strings, user_agents from .recaptcha import ReCaptcha from .librecaptcha import __version__, get_token, has_gui from .user_agents import USER_AGENTS, random_user_agent from .__main__ import main librecaptcha-0.6.2/librecaptcha/__main__.py000066400000000000000000000160051345160434500206620ustar00rootroot00000000000000# Copyright (C) 2017, 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from .errors import UserError, UserExit from .librecaptcha import get_token, __version__ from .user_agents import random_user_agent import os import re import sys def get_cmd(): if not sys.argv: return "librecaptcha" if sys.argv[0].startswith("./"): return sys.argv[0] return os.path.basename(sys.argv[0]) CMD = get_cmd() USAGE = """\ Usage: {0} [options] [--] [] {0} -h | --help | --version Arguments: The reCAPTCHA API key to use. This is usually the value of the "data-sitekey" HTML attribute. The URL of the site that contains the reCAPTCHA challenge. Should start with http:// or https://. Everything after the hostname is optional. For example: https://example.com A user-agent string. The client that will use the obtained reCAPTCHA token should have this user-agent string. If not provided, a random user-agent string will be chosen and shown. Options: -g --gui Use the GTK 3 GUI (as opposed to the CLI). --debug Show debugging information while running. -h --help Show this help message. --version Show the program version. """.format(CMD) def usage(file=sys.stdout): print(USAGE, end="", file=file) def usage_error(exit=True): usage(sys.stderr) if exit: sys.exit(1) class ParsedArgs: def __init__(self): self.parse_error = None self.api_key = None self.site_url = None self.user_agent = None self.gui = False self.debug = False self.help = False self.version = False class ArgParser: def __init__(self, args): self.args = args self.index = 0 self.positional_index = 0 self.parsed = ParsedArgs() self.options_done = False self.end_early = False @property def arg(self): try: return self.args[self.index] except IndexError: return None @property def done(self): return self.end_early or self.index >= len(self.args) def advance(self): self.index += 1 def error(self, message): self.parsed.parse_error = message self.end_early = True def parse_long_option(self, arg): body = arg[len("--"):] if body == "debug": self.parsed.debug = True return if body == "help": self.parsed.help = True self.end_early = True return if body == "version": self.parsed.version = True self.end_early = True return if body == "gui": self.parsed.gui = True return self.error("Unrecognized option: {}".format(arg)) def parse_short_option_char(self, char): if char == "h": self.parsed.help = True self.end_early = True return if char == "g": self.parsed.gui = True return self.error("Unrecognized option: -{}".format(char)) def parse_short_option(self, arg): body = arg[len("-"):] for char in body: self.parse_short_option_char(char) def try_parse_option(self): arg = self.arg if arg == "--": self.options_done = True return True if re.match(r"--[^-]", arg): self.parse_long_option(arg) return True if re.match(r"-[^-]", arg): self.parse_short_option(arg) return True return False def parse_positional(self): arg = self.arg if self.positional_index == 0: self.parsed.api_key = arg return if self.positional_index == 1: self.parsed.site_url = arg return if self.positional_index == 2: self.parsed.user_agent = arg return self.error("Unexpected positional argument: {}".format(arg)) def parse_single(self): if not self.options_done and self.try_parse_option(): return self.parse_positional() self.positional_index += 1 def handle_end(self): if self.end_early: return if self.positional_index < 1: self.error("Missing positional argument: ") return if self.positional_index < 2: self.error("Missing positional argument: ") return def parse(self): while not self.done: self.parse_single() self.advance() self.handle_end() return self.parsed GOT_TOKEN_MSG = """\ Received token. This token should usually be submitted with the form as the value of the "g-recaptcha-response" field. """ def run(args: ParsedArgs): random_ua = False user_agent = args.user_agent if args.user_agent is None: random_ua = True user_agent = random_user_agent() if args.debug: print("User-agent string: {}".format(user_agent), file=sys.stderr) uvtoken = get_token( args.api_key, args.site_url, user_agent, gui=args.gui, debug=args.debug, ) print(GOT_TOKEN_MSG) if random_ua: print("Note: The following user-agent string was used:") print(user_agent) print() print("Token:") print(uvtoken) UNEXPECTED_ERR_MSG = """\ An unexpected error occurred. The exception traceback is shown below: """ def run_or_exit(args: ParsedArgs): if args.debug: return run(args) try: return run(args) except UserExit: sys.exit(2) except UserError as e: print(e.message, file=sys.stderr) sys.exit(1) except KeyboardInterrupt: print(file=sys.stderr) sys.exit(2) except Exception: print(UNEXPECTED_ERR_MSG, file=sys.stderr) raise def main(): args = sys.argv[1:] parsed = ArgParser(args).parse() error = parsed.parse_error if error is not None: print(error, file=sys.stderr) print("For usage information, run: {} --help".format(CMD), file=sys.stderr) sys.exit(1) if parsed.help: usage() return if parsed.version: print(__version__) return run_or_exit(parsed) if __name__ == "__main__": main() librecaptcha-0.6.2/librecaptcha/cli.py000066400000000000000000000230341345160434500177110ustar00rootroot00000000000000# Copyright (C) 2017, 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from .errors import UserError from .frontend import Frontend from PIL import ImageDraw, ImageFont from threading import Thread, RLock from queue import Queue import io import json import os import subprocess import sys import time def get_font(size): typefaces = [ "FreeSans", "LiberationSans-Regular", "DejaVuSans", "Arial", "arial", ] for typeface in typefaces: try: return ImageFont.truetype(typeface, size=size) except OSError: pass return ImageFont.load_default() FONT_SIZE = 16 FONT = get_font(FONT_SIZE) def read_indices(prompt, max_index): while True: print(prompt, end="", flush=True) line = input() try: indices = [int(i) - 1 for i in line.split()] except ValueError: print("Invalid input.") continue if all(0 <= i < max_index for i in indices): return indices print("Numbers out of bounds.") def draw_lines(image, rows, columns): draw = ImageDraw.Draw(image) def line(p1, p2): draw.line([p1, p2], fill=(255, 255, 255), width=2) for i in range(1, rows): y = image.height * i // rows - 1 line((0, y), (image.width, y)) for i in range(1, columns): x = image.width * i // columns - 1 line((x, 0), (x, image.height)) def draw_indices(image, rows, columns): draw = ImageDraw.Draw(image, "RGBA") for i in range(rows * columns): row = i // columns column = i % columns corner = ( image.width * column // columns, image.height * (row + 1) // rows, ) text_loc = ( corner[0] + round(FONT_SIZE / 2), corner[1] - round(FONT_SIZE * 1.5), ) text = str(i + 1) text_size = FONT.getsize(text) draw.rectangle([ (text_loc[0] - round(FONT_SIZE / 10), text_loc[1]), ( text_loc[0] + text_size[0] + round(FONT_SIZE / 10), text_loc[1] + text_size[1] + round(FONT_SIZE / 10), ), ], fill=(0, 0, 0, 128)) draw.text(text_loc, str(i + 1), fill=(255, 255, 255), font=FONT) def print_temporary(string, file=sys.stdout): end = "" if file.isatty() else "\n" print(string, file=file, end=end, flush=True) def clear_temporary(file=sys.stdout): if not file.isatty(): return print("\r\x1b[K", file=file, end="", flush=True) class CliSolver: def __init__(self, solver): self.solver = solver self.__image_procs = [] self.__has_display = (os.name == "posix") def __run_display(self, img_bytes): return subprocess.Popen( ["display", "-"], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) def __try_display(self, image): if not self.__has_display: return False img_buffer = io.BytesIO() image.save(img_buffer, "png") img_bytes = img_buffer.getvalue() try: proc = self.__run_display(img_bytes) except FileNotFoundError: self.__has_display = False return False proc.stdin.write(img_bytes) proc.stdin.close() self.__image_procs.append(proc) return True def show_image(self, image): if not self.__try_display(image): image.show() def hide_images(self): for proc in self.__image_procs: proc.terminate() self.__image_procs.clear() def run(self): self.solver.run() class CliDynamicSolver(CliSolver): def __init__(self, solver): super().__init__(solver) solver.on_initial_image = self.handle_initial_image solver.on_tile_image = self.handle_tile_image self.image_open = False self.image_queue = Queue() self.num_pending = 0 self.lock = RLock() def handle_initial_image(self, image, **kwargs): solver = self.solver num_rows, num_columns = solver.dimensions draw_indices(image, num_rows, num_columns) self.show_image(image) print("Take a look at the grid of tiles that just appeared. ", end="") print("({} rows, {} columns)".format(num_rows, num_columns)) print("Which tiles should be selected?") print("(Top-left is 1; bottom-right is {}.)".format(solver.num_tiles)) indices = read_indices( "Enter numbers separated by spaces: ", solver.num_tiles, ) print() self.hide_images() self.select_initial(indices) self.new_tile_loop() solver.finish() def new_tile_loop(self): while self.num_pending > 0: print_temporary("Waiting for next image...") index, image = self.image_queue.get() clear_temporary() self.num_pending -= 1 self.show_image(image) print("Take a look at the image that just appeared.") accept = input( "Should this image be selected? [y/N] ", )[:1].lower() == "y" print() self.hide_images() if accept: self.select_tile(index) # Called from a non-main thread. def handle_tile_image(self, index, image, **kwargs): self.image_queue.put((index, image)) def select_initial(self, indices): for i, index in enumerate(indices): # Avoid sending initial requests simultaneously. self.select_tile(index, 0.25 * i) def select_tile_sync(self, index): self.num_pending += 1 self.solver.select_tile(index) def select_tile(self, index, delay=0): def target(): delay and time.sleep(delay) with self.lock: self.select_tile_sync(index) Thread(target=target, daemon=True).start() class CliMultiCaptchaSolver(CliSolver): def __init__(self, solver): super().__init__(solver) solver.on_image = self.handle_image def handle_image(self, image, **kwargs): solver = self.solver num_rows, num_columns = solver.dimensions draw_lines(image, num_rows, num_columns) draw_indices(image, num_rows, num_columns) self.show_image(image) print("Take a look at the grid of tiles that just appeared. ", end="") print("({} rows, {} columns)".format(num_rows, num_columns)) print("Which tiles should be selected?") print("(Top-left is 1; bottom-right is {}.)".format(solver.num_tiles)) indices = read_indices( "Enter numbers separated by spaces: ", solver.num_tiles, ) print() self.hide_images() solver.select_indices(indices) BLOCKED_MSG = """\ ERROR: Received challenge type "{}". This is usually an indication that reCAPTCHA requests from this network are being blocked. Try installing Tor (the full installation, not just the browser bundle) and running this program over Tor with the "torsocks" command. Alternatively, try waiting a while before requesting another challenge over this network. """ class Cli(Frontend): def __init__(self, recaptcha): super().__init__(recaptcha) rc = recaptcha rc.on_goal = self.handle_goal rc.on_challenge = self.handle_challenge rc.on_challenge_dynamic = self.challenge_dynamic rc.on_challenge_multicaptcha = self.challenge_multicaptcha rc.on_challenge_blocked = self.challenge_blocked rc.on_challenge_unknown = self.challenge_unknown self._first = True def handle_goal(self, goal, meta, **kwargs): if goal: print("CHALLENGE OBJECTIVE: {}".format(goal)) return print("WARNING: Could not determine challenge objective.") print("Challenge information: {}".format(json.dumps(meta))) def handle_challenge(self, ctype, **kwargs): if not self._first: print("You must solve another challenge.") print() self._first = False def challenge_dynamic(self, solver, **kwargs): CliDynamicSolver(solver).run() def challenge_multicaptcha(self, solver, **kwargs): CliMultiCaptchaSolver(solver).run() def challenge_blocked(self, ctype, **kwargs): self.raise_challenge_blocked(ctype) def challenge_unknown(self, ctype, **kwargs): self.raise_challenge_unknown(ctype) @classmethod def raise_challenge_blocked(cls, ctype): print(BLOCKED_MSG.format(ctype), end="") raise UserError( "Error: Unsupported challenge type: {}.\n".format(ctype) + "Requests are most likely being blocked; see the message above.", ) @classmethod def raise_challenge_unknown(cls, ctype): raise UserError( "Error: Got unsupported challenge type: {}\n".format(ctype) + "Please file an issue if this problem persists.", ) librecaptcha-0.6.2/librecaptcha/errors.py000066400000000000000000000026551345160434500204640ustar00rootroot00000000000000# Copyright (C) 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . class UserError(Exception): """A user-facing exception for an expected error condition (e.g., bad user-supplied data). When librecaptcha is run as a program, exceptions of this type are shown without a traceback unless --debug is passed. """ def __init__(self, message): super().__init__(message) @property def message(self): return self.args[0] class UserExit(UserError): """When librecaptcha is run as a program, throwing this exception causes the program to terminate. The exception message is not shown by default. """ def __init__(self, message="Program terminated."): super().__init__(message) class GtkImportError(ImportError): pass librecaptcha-0.6.2/librecaptcha/extract_strings.py000066400000000000000000000051421345160434500223650ustar00rootroot00000000000000# Copyright (C) 2017, 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from slimit.parser import Parser from slimit import ast import requests import json import os import os.path import sys SHOW_WARNINGS = False def make_parser_raw(): return Parser() def make_parser_silent(): # File descriptor hackiness to silence warnings null_fd = os.open(os.devnull, os.O_RDWR) old_fd = os.dup(2) try: os.dup2(null_fd, 2) return make_parser_raw() finally: os.dup2(old_fd, 2) os.close(null_fd) os.close(old_fd) make_parser = make_parser_silent if SHOW_WARNINGS: make_parser = make_parser_raw def load_javascript(url, user_agent): print("Downloading <{}>...".format(url), file=sys.stderr) r = requests.get(url, headers={ "User-Agent": user_agent, }) return r.text def extract_strings(javascript): print("Extracting strings...", file=sys.stderr) parsed = make_parser().parse(javascript) strings = [] def add_strings(tree, strings): if tree is None: return if not isinstance(tree, (ast.Node, list, tuple)): raise TypeError("Unexpected item: {!r}".format(tree)) if isinstance(tree, ast.String): strings.append(tree.value[1:-1]) children = tree if isinstance(tree, ast.Node): children = tree.children() for child in children: add_strings(child, strings) add_strings(parsed, strings) return strings def extract_and_save(url, path, version, rc_version, user_agent): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w") as f: print("{}/{}".format(version, rc_version), file=f) js = load_javascript(url, user_agent) strings = extract_strings(js) strings_json = json.dumps(strings) print('Saving strings to "{}"...'.format(path), file=sys.stderr) f.write(strings_json) return strings librecaptcha-0.6.2/librecaptcha/frontend.py000066400000000000000000000022571345160434500207650ustar00rootroot00000000000000# Copyright (C) 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . class Frontend: def __init__(self, recaptcha): self.rc = rc = recaptcha rc.on_token = self.__handle_token def __handle_token(self, token, **kwargs): self.on_token(token) def on_token(self, token: str, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def run(self, callback=None): if callback: self.on_token = callback self.rc.run() librecaptcha-0.6.2/librecaptcha/gui.py000066400000000000000000000337201345160434500177310ustar00rootroot00000000000000# Copyright (C) 2019 cyclopsian (https://github.com/cyclopsian) # Copyright (C) 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from .cli import Cli from .errors import UserExit, GtkImportError from .frontend import Frontend from threading import Thread, RLock import html import json import math import re try: import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk, Gdk, GdkPixbuf, GLib except ImportError as e: raise GtkImportError from e # Disable GTK warnings GLib.log_set_writer_func(lambda *args: GLib.LogWriterOutput.HANDLED) def image_to_gdk_pixbuf(image): width, height = image.size image_bytes = GLib.Bytes.new(image.tobytes()) has_alpha = image.mode == "RGBA" bpp = 4 if has_alpha else 3 return GdkPixbuf.Pixbuf.new_from_bytes( image_bytes, GdkPixbuf.Colorspace.RGB, has_alpha, 8, width, height, width * bpp, ) class ChallengeDialogWidget(Gtk.Dialog): css_provider = None def __init__(self): super().__init__() self.columns = 0 self.grid = Gtk.Grid.new() self.set_title("CAPTCHA Challenge") self.set_icon_name("view-refresh-symbolic") self.verify = self.add_button("", Gtk.ResponseType.OK) context = self.verify.get_style_context() context.add_class("suggested-action") self.set_resizable(False) self.content = content = self.get_content_area() content.set_spacing(6) for dir in ["top", "right", "bottom", "left"]: getattr(content, "set_margin_" + dir)(6) self.header = Gtk.Label.new("") self.header.set_xalign(0) context = self.header.get_style_context() context.add_class("challenge-header") content.pack_start(self.header, False, False, 0) self.load_css() def get_goal(self, **kwargs) -> str: """Callback; set this attribute in this parent class.""" raise NotImplementedError def get_note(self, **kwargs) -> str: """Callback; set this attribute in this parent class.""" raise NotImplementedError def get_verify_label(self, **kwargs) -> str: """Callback; set this attribute in this parent class.""" raise NotImplementedError def make_grid_item(self, index, pixbuf, **kwargs) -> object: """Callback; set this attribute in this parent class.""" raise NotImplementedError @property def formatted_goal(self): raw = str(self.get_goal()) match = re.fullmatch(r"(.*)(.*)(.*)", raw) if not match: return html.escape(raw) groups = match.groups() return '{}{}{}'.format( *map(html.escape, [ groups[0] and groups[0] + "\n", groups[1], groups[2], ]), ) @classmethod def load_css(cls): if cls.css_provider is not None: return cls.css_provider = Gtk.CssProvider.new() cls.css_provider.load_from_data(""" .challenge-button { border-radius: 0; border-width: 1px; padding: 0; } .challenge-check, .challenge-header { color: @theme_selected_fg_color; background-image: linear-gradient( @theme_selected_bg_color, @theme_selected_bg_color); } .challenge-header { padding: 12px; } .challenge-check { border-radius: 50%; } """.encode("utf8")) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), cls.css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, ) def load_initial(self, image, *, rows, columns): self.columns = columns pixbuf = image_to_gdk_pixbuf(image) stride_x = image.width // columns stride_y = image.height // rows for i in range(rows * columns): column = i % columns row = i // columns cell_pixbuf = GdkPixbuf.Pixbuf.new( GdkPixbuf.Colorspace.RGB, pixbuf.get_has_alpha(), 8, stride_x, stride_y, ) src_x = stride_x * column src_y = stride_y * row pixbuf.copy_area( src_x, src_y, stride_x, stride_y, cell_pixbuf, 0, 0, ) widget = self.make_grid_item(i, cell_pixbuf) context = widget.get_style_context() context.add_class("challenge-button") self.grid.attach(widget, column, row, 1, 1) self.content.pack_start(self.grid, True, True, 0) def get_grid_item(self, i): column = i % self.columns row = i // self.columns return self.grid.get_child_at(column, row) def replace_grid_item(self, i, new): column = i % self.columns row = i // self.columns old = self.grid.get_child_at(column, row) self.grid.remove(old) self.grid.attach(new, column, row, 1, 1) new.show_all() def update(self): goal = self.formatted_goal note = str(self.get_note()) verify_label = str(self.get_verify_label()) markup = goal + "\n" self.header.set_markup(markup + note) self.verify.set_label(verify_label) def run(self): self.show_all() response = super().run() self.destroy() while Gtk.events_pending(): Gtk.main_iteration() if response != Gtk.ResponseType.OK: raise UserExit class ChallengeToggleButton(Gtk.ToggleButton): def __init__(self, pixbuf): super().__init__() self.pixbuf = pixbuf width = pixbuf.get_width() height = pixbuf.get_height() self.small_pixbuf = pixbuf.scale_simple( width * 0.9, height * 0.9, GdkPixbuf.InterpType.BILINEAR, ) self.set_relief(Gtk.ReliefStyle.NONE) fixed = Gtk.Fixed.new() self.image = Gtk.Image.new_from_pixbuf(pixbuf) self.image.set_size_request(width, height) self.check = Gtk.Image.new_from_icon_name( "object-select-symbolic", Gtk.IconSize.DND, ) self.check.set_pixel_size(24) self.check.set_no_show_all(True) context = self.check.get_style_context() context.add_class("challenge-check") fixed.put(self.image, 0, 0) fixed.put(self.check, 0, 0) self.add(fixed) self.connect("toggled", lambda obj: self.toggle_check()) def toggle_check(self): if self.get_active(): self.check.show() self.image.set_from_pixbuf(self.small_pixbuf) return self.check.hide() self.image.set_from_pixbuf(self.pixbuf) class BaseCaptchaDialog: def __init__(self): self.dialog = dialog = ChallengeDialogWidget() dialog.get_goal = self.__get_goal def __get_goal(self, **kwargs): return self.get_goal(**kwargs) def get_goal(self, **kwargs) -> str: """Callback; set this attribute in this parent class.""" raise NotImplementedError def load_initial(self, image, *, rows, columns): self.dialog.load_initial(image, rows=rows, columns=columns) self.update() def update(self): self.dialog.update() def run(self): self.dialog.run() class DynamicDialog(BaseCaptchaDialog): def __init__(self): super().__init__() dialog = self.dialog dialog.get_note = self.get_note dialog.get_verify_label = self.get_verify_label dialog.make_grid_item = self.make_grid_item def on_clicked(self, index, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def get_note(self, **kwargs): return "Click verify once there are none left" def get_verify_label(self, **kwargs): return "Ver_ify" def make_grid_item(self, index, pixbuf, **kwargs): button = Gtk.Button.new() image = Gtk.Image.new_from_pixbuf(pixbuf) button.add(image) button.connect("clicked", lambda obj: self.handle_clicked(obj, index)) context = button.get_style_context() context.add_class("challenge-button") return button def handle_clicked(self, button, index, **kwargs): spinner = Gtk.Spinner.new() spinner.set_size_request(32, 32) left = (button.get_allocated_width() - 32) / 2 top = (button.get_allocated_height() - 32) / 2 spinner.set_margin_top(math.floor(top)) spinner.set_margin_left(math.floor(left)) spinner.set_margin_bottom(math.ceil(top)) spinner.set_margin_right(math.ceil(left)) self.dialog.replace_grid_item(index, spinner) spinner.start() self.on_clicked(index) def replace_tile_image(self, index, image): pixbuf = image_to_gdk_pixbuf(image) spinner = self.dialog.get_grid_item(index) if pixbuf is None: spinner.stop() return button = self.make_grid_item(index, pixbuf) self.dialog.replace_grid_item(index, button) class MultiCaptchaDialog(BaseCaptchaDialog): def __init__(self): super().__init__() self.selected = set() dialog = self.dialog dialog.get_note = self.get_note dialog.get_verify_label = self.get_verify_label dialog.make_grid_item = self.make_grid_item def get_note(self, **kwargs): note = "If there are none, click skip" if self.selected: note = '{}'.format(note) return note def get_verify_label(self, **kwargs): if self.selected: return "Ver_ify" return "Sk_ip" def make_grid_item(self, index, pixbuf, **kwargs): button = ChallengeToggleButton(pixbuf) button.connect( "toggled", lambda obj: self.handle_toggled(obj, index), ) return button def handle_toggled(self, button, index, **kwargs): if button.get_active(): self.selected.add(index) else: self.selected.remove(index) self.update() def run(self): super().run() return list(self.selected) class GuiSolver: def __init__(self, solver, gui: "Gui"): self.solver = solver self.gui: "Gui" = gui self.dialog = None def get_goal(self, **kwargs): return self.gui.goal def prepare_dialog(self, dialog): dialog.get_goal = self.get_goal return dialog def run(self): self.solver.run() class GuiDynamicSolver(GuiSolver): def __init__(self, solver, gui): super().__init__(solver, gui) solver.on_initial_image = self.handle_initial_image solver.on_tile_image = self.handle_tile_image self.lock = RLock() def handle_initial_image(self, image, **kwargs): solver = self.solver rows, columns = solver.dimensions self.dialog = self.prepare_dialog(DynamicDialog()) self.dialog.on_clicked = self.handle_gui_tile_clicked self.dialog.load_initial(image, rows=rows, columns=columns) self.dialog.run() print("Submitting solution...") solver.finish() # Called from a non-UI thread. def handle_tile_image(self, index, image, **kwargs): def callback(): self.dialog.replace_tile_image(index, image) GLib.timeout_add(0, callback) def handle_gui_tile_clicked(self, index): def target(): with self.lock: self.solver.select_tile(index) Thread(target=target, daemon=True).start() class GuiMultiCaptchaSolver(GuiSolver): def __init__(self, solver, gui): super().__init__(solver, gui) solver.on_image = self.handle_image def handle_image(self, image, **kwargs): solver = self.solver rows, columns = solver.dimensions self.dialog = self.prepare_dialog(MultiCaptchaDialog()) self.dialog.load_initial(image, rows=rows, columns=columns) indices = self.dialog.run() print("Submitting solution...") solver.select_indices(indices) class Gui(Frontend): def __init__(self, recaptcha): super().__init__(recaptcha) self.goal = None self._first = True rc = self.rc rc.on_goal = self.handle_goal rc.on_challenge = self.handle_challenge rc.on_challenge_dynamic = self.challenge_dynamic rc.on_challenge_multicaptcha = self.challenge_multicaptcha rc.on_challenge_blocked = self.challenge_blocked rc.on_challenge_unknown = self.challenge_unknown def handle_goal(self, goal, meta, raw, **kwargs): if not raw: print("WARNING: Could not determine challenge objective.") raw = json.dumps(meta) self.goal = raw def handle_challenge(self, ctype, **kwargs): if not self._first: print("You must solve another challenge.") print() self._first = False def challenge_dynamic(self, solver, **kwargs): GuiDynamicSolver(solver, self).run() def challenge_multicaptcha(self, solver, **kwargs): GuiMultiCaptchaSolver(solver, self).run() def challenge_blocked(self, ctype, **kwargs): Cli.raise_challenge_blocked(ctype) def challenge_unknown(self, ctype, **kwargs): Cli.raise_challenge_unknown(ctype) librecaptcha-0.6.2/librecaptcha/librecaptcha.py000066400000000000000000000031561345160434500215660ustar00rootroot00000000000000# Copyright (C) 2017, 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from . import cli from .errors import GtkImportError, UserError from .recaptcha import ReCaptcha __version__ = "0.6.2" def _get_gui(): try: from . import gui except GtkImportError as e: raise UserError( "Error: Could not load the GUI. Is PyGObject installed?\n" "Try (re)installing librecaptcha[gtk] with pip.\n" "For more details, add the --debug option.", ) from e return gui def has_gui(): try: from . import gui # noqa: F401 except GtkImportError: return False return True def get_token(api_key, site_url, user_agent, *, gui=False, debug=False): rc = ReCaptcha(api_key, site_url, user_agent, debug=debug) ui = (_get_gui().Gui if gui else cli.Cli)(rc) uvtoken = None def callback(token): nonlocal uvtoken uvtoken = token ui.run(callback) return uvtoken librecaptcha-0.6.2/librecaptcha/recaptcha.py000066400000000000000000000376731345160434500211120ustar00rootroot00000000000000# Copyright (C) 2017, 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from .errors import UserError from .extract_strings import extract_and_save from PIL import Image import requests from html.parser import HTMLParser from threading import Thread from urllib.parse import urlparse import base64 import io import json import os import os.path import re import sys import time BASE_URL = "https://www.google.com/recaptcha/api2/" API_JS_URL = "https://www.google.com/recaptcha/api.js" JS_URL_TEMPLATE = "https://www.gstatic.com/recaptcha/api2/{}/recaptcha__en.js" STRINGS_VERSION = "0.1.0" STRINGS_PATH = os.path.join( os.path.expanduser("~"), ".cache", "librecaptcha", "cached-strings", ) DYNAMIC_SELECT_DELAY = 4.5 # seconds FIND_GOAL_SEARCH_DISTANCE = 10 def get_full_url(url): return BASE_URL.rstrip("/") + "/" + url.lstrip("/") def get_rc_site_url(url): parsed = urlparse(url) if not parsed.hostname: raise UserError("Error: Site URL has no hostname.") if not parsed.scheme: raise UserError("Error: Site URL has no scheme.") if parsed.scheme not in ["http", "https"]: raise UserError( "Error: Site URL has invalid scheme: {}".format(parsed.scheme), ) port = parsed.port if port is None: port = {"http": 80, "https": 443}[parsed.scheme] return "{}://{}:{}".format(parsed.scheme, parsed.hostname, port) def rc_base64(string): data = string if isinstance(string, str): data = string.encode() return base64.b64encode(data, b"-_").decode().replace("=", ".") def load_rc_json(text): return json.loads(text.split("\n", 1)[1]) def get_meta(pmeta, probable_index): if not isinstance(pmeta, list): raise TypeError("pmeta is not a list: {!r}".format(pmeta)) def matches(meta): return meta and isinstance(meta, list) if probable_index < len(pmeta): meta = pmeta[probable_index] if matches(meta): return meta for child in pmeta: if matches(child): return child raise RuntimeError("Could not find meta; pmeta: {!r}".format(pmeta)) def get_rresp(uvresp): if not isinstance(uvresp, list): raise TypeError("uvresp is not a list: {!r}".format(uvresp)) for child in uvresp: if child and isinstance(child, list) and child[0] == "rresp": return child return None def get_js_strings(user_agent, rc_version): def get_json(): with open(STRINGS_PATH) as f: version, text = f.read().split("\n", 1) if version != "{}/{}".format(STRINGS_VERSION, rc_version): raise OSError("Incorrect version: {}".format(version)) return json.loads(text) try: return get_json() except (OSError, ValueError, json.JSONDecodeError): pass result = extract_and_save( JS_URL_TEMPLATE.format(rc_version), STRINGS_PATH, STRINGS_VERSION, rc_version, user_agent, ) print(file=sys.stderr) return result def get_rc_version(user_agent): match = re.search(r"/recaptcha/api2/(.+?)/", requests.get( API_JS_URL, headers={ "User-Agent": user_agent, }, ).text) if match is None: raise RuntimeError("Could not extract version from api.js.") return match.group(1) def get_image(data): return Image.open(io.BytesIO(data)) class Solver: def __init__(self, recaptcha): self.rc = recaptcha def on_solved(response, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError class HasGrid: @property def num_rows(self): return self.dimensions[0] @property def num_columns(self): return self.dimensions[1] @property def num_tiles(self): return self.num_rows * self.num_columns class DynamicSolver(Solver, HasGrid): def __init__(self, recaptcha, pmeta): super().__init__(recaptcha) self.selections = [] meta = get_meta(pmeta, 1) self.meta = meta self.dimensions = (meta[3], meta[4]) self.tile_index_map = list(range(self.num_tiles)) self.last_request_map = [0] * self.num_tiles self.latest_index = self.num_tiles - 1 def on_initial_image(self, image, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def on_tile_image(self, index, image, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def run(self): self.rc.show_challenge_goal(self.meta) self.first_payload() def finish(self, block=True): if block: time.sleep(self.final_timeout) self.on_solved(self.selections) @property def final_timeout(self): return max(self.get_timeout(i) for i in range(self.num_tiles)) def get_timeout(self, index): elapsed = time.monotonic() - self.last_request_map[index] duration = max(DYNAMIC_SELECT_DELAY - elapsed, 0) return duration def first_payload(self): image = get_image(self.rc.get("payload", api=False, params={ "c": self.rc.current_token, "k": self.rc.api_key, }).content) self.on_initial_image(image) def select_tile(self, index): def target(): time.sleep(self.get_timeout(index)) self.on_tile_image(index, image) image = self.replace_tile(index) Thread(target=target, daemon=True).start() def replace_tile(self, index): real_index = self.tile_index_map[index] self.selections.append(real_index) r = self.rc.post("replaceimage", data={ "c": self.rc.current_token, "ds": "[{}]".format(real_index), }) self.last_request_map[index] = time.monotonic() data = load_rc_json(r.text) self.latest_index += 1 self.tile_index_map[index] = self.latest_index self.rc.current_token = data[1] replacement_id = data[2][0] image = get_image(self.rc.get("payload", api=False, params={ "c": self.rc.current_token, "k": self.rc.api_key, "id": replacement_id, }).content) return image class MultiCaptchaSolver(Solver, HasGrid): def __init__(self, recaptcha, pmeta): super().__init__(recaptcha) self.selection_groups = [] self.dimensions = None self.challenge_type = None self.previous_token = None self.previous_id = None self.id = "2" self.metas = list(get_meta(pmeta, 5)[0]) self.next_challenge() def on_image(self, image, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def run(self): self.first_payload() def next_challenge(self): meta = self.metas.pop(0) self.dimensions = (meta[3], meta[4]) self.rc.show_challenge_goal(meta) def select_indices(self, indices): self.selection_groups.append(list(sorted(indices))) if self.metas: self.replace_image() return self.on_solved(self.selection_groups) def first_payload(self): image = get_image(self.rc.get("payload", api=False, params={ "c": self.rc.current_token, "k": self.rc.api_key, }).content) self.on_image(image) def replace_image(self): selections = self.selection_groups[-1] r = self.rc.post("replaceimage", data={ "c": self.rc.current_token, "ds": json.dumps([selections], separators=",:"), }) data = load_rc_json(r.text) self.previous_token = self.rc.current_token self.rc.current_token = data[1] replacement_id = (data[2] or [None])[0] self.previous_id = self.id self.id = replacement_id self.next_challenge() image = get_image(self.rc.get("payload", api=False, params={ "c": self.previous_token, "k": self.rc.api_key, "id": self.previous_id, }).content) self.on_image(image) class ReCaptcha: def __init__(self, api_key, site_url, user_agent, debug=False, make_requests=True): self.api_key = api_key self.site_url = get_rc_site_url(site_url) self._debug = debug self.co = rc_base64(self.site_url) self.first_token = None self.current_token = None self.user_agent = user_agent self.js_strings = None self.rc_version = None if make_requests: self.rc_version = get_rc_version(self.user_agent) self.js_strings = get_js_strings(self.user_agent, self.rc_version) def on_goal(goal: str, meta, *, raw: str): """Callback; set this attribute in the parent class.""" raise NotImplementedError def on_token(token: str, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def on_challenge(type: str, **kwargs): """Callback (optional); set this attribute in the parent class.""" pass def on_challenge_dynamic(solver: DynamicSolver, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def on_challenge_multicaptcha(solver: MultiCaptchaSolver, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def on_challenge_blocked(type: str, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def on_challenge_unknown(type: str, **kwargs): """Callback; set this attribute in the parent class.""" raise NotImplementedError def debug(self, *args, **kwargs): if self._debug: print(*args, file=sys.stderr, **kwargs) def find_challenge_goal(self, id, raw=False): start = 0 matching_strings = [] def try_find(): nonlocal start index = self.js_strings.index(id, start) for i in range(FIND_GOAL_SEARCH_DISTANCE): next_str = self.js_strings[index + i + 1] if re.search(r"\bselect all\b", next_str, re.I): matching_strings.append((i, index, next_str)) start = index + FIND_GOAL_SEARCH_DISTANCE + 1 try: while True: try_find() except (ValueError, IndexError): pass try: goal = min(matching_strings)[2] except ValueError: return None, None raw = goal plain = raw.replace("", "").replace("", "") return raw, plain def show_challenge_goal(self, meta): raw, goal = self.find_challenge_goal(meta[0]) self.on_goal(goal, meta, raw=raw) def get_headers(self, headers): headers = headers or {} if "User-Agent" not in headers: headers["User-Agent"] = self.user_agent return headers def get(self, url, *, params=None, api=True, headers=None, allow_errors=None, **kwargs): params = params or {} if api: params["k"] = self.api_key params["v"] = self.rc_version headers = self.get_headers(headers) r = requests.get( get_full_url(url), params=params, headers=headers, **kwargs, ) self.debug("[http] [get] {}".format(r.url)) if not (allow_errors is True or r.status_code in (allow_errors or {})): r.raise_for_status() return r def post(self, url, *, params=None, data=None, api=True, headers=None, allow_errors=None, no_debug_response=False, **kwargs): params = params or {} data = data or {} if api: params["k"] = self.api_key data["v"] = self.rc_version headers = self.get_headers(headers) r = requests.post( get_full_url(url), params=params, data=data, headers=headers, **kwargs, ) self.debug("[http] [post] {}".format(r.url)) self.debug("[http] [post] [data] {!r}".format(data)) if not no_debug_response: self.debug("[http] [post] [response] {}".format(r.text)) if not (allow_errors is True or r.status_code in (allow_errors or {})): r.raise_for_status() return r def request_first_token(self): class Parser(HTMLParser): def __init__(p_self): p_self.token = None super().__init__() def handle_starttag(p_self, tag, attrs): attrs = dict(attrs) if attrs.get("id") == "recaptcha-token": p_self.token = attrs.get("value") text = self.get("anchor", params={"co": self.co}).text parser = Parser() parser.feed(text) if not parser.token: raise RuntimeError( "Could not get first token. Response:\n{}".format(text), ) self.first_token = parser.token self.current_token = self.first_token def verify(self, response): response_text = json.dumps({"response": response}, separators=",:") response_b64 = rc_base64(response_text) self.debug("Sending verify request...") r = self.post("userverify", data={ "c": self.current_token, "response": response_b64, }) uvresp = load_rc_json(r.text) self.debug("Got verify response: {!r}".format(uvresp)) rresp = get_rresp(uvresp) uvresp_token = uvresp[1] return (uvresp_token, rresp) def get_first_rresp(self): self.debug("Getting first rresp...") r = self.post("reload", data={"reason": "fi", "c": self.first_token}) rresp = load_rc_json(r.text) self.debug("Got first rresp: {!r}".format(rresp)) return rresp def handle_solved(self, response, **kwargs): uvtoken, rresp = self.verify(response) if rresp is not None: self.solve_challenge(rresp) return if not uvtoken: raise RuntimeError("Got neither uvtoken nor new rresp.") self.on_token(uvtoken) def solve_challenge(self, rresp): challenge_type = rresp[5] self.debug("Challenge type: {}".format(challenge_type)) pmeta = rresp[4] self.debug("pmeta: {}".format(pmeta)) self.current_token = rresp[1] self.debug("Current token: {}".format(self.current_token)) solver_class = { "dynamic": DynamicSolver, "multicaptcha": MultiCaptchaSolver, }.get(challenge_type) handler = { "dynamic": self.on_challenge_dynamic, "multicaptcha": self.on_challenge_multicaptcha, "default": self.on_challenge_blocked, "doscaptcha": self.on_challenge_blocked, }.get(challenge_type) self.on_challenge(challenge_type) if handler is None: self.on_challenge_unknown(challenge_type) return if solver_class is None: handler(challenge_type) return solver = solver_class(self, pmeta) solver.on_solved = self.handle_solved handler(solver) def run(self): self.request_first_token() rresp = self.get_first_rresp() self.solve_challenge(rresp) librecaptcha-0.6.2/librecaptcha/user_agent_data.py000066400000000000000000000066631345160434500223000ustar00rootroot00000000000000# This file was automatically generated by update_user_agents.py using data # from . # flake8: noqa USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0", "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36" ] librecaptcha-0.6.2/librecaptcha/user_agents.py000066400000000000000000000015341345160434500214620ustar00rootroot00000000000000# Copyright (C) 2017-2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from .user_agent_data import USER_AGENTS import random def random_user_agent(): return random.choice(USER_AGENTS) librecaptcha-0.6.2/requirements.txt000066400000000000000000000000771345160434500174350ustar00rootroot00000000000000Pillow>=4.1.1 requests>=2.18.1 slimit>=0.8.1 PyGObject>=3.30.0 librecaptcha-0.6.2/scripts/000077500000000000000000000000001345160434500156345ustar00rootroot00000000000000librecaptcha-0.6.2/scripts/update_user_agents.py000077500000000000000000000045671345160434500221060ustar00rootroot00000000000000#!/usr/bin/env python3 # Copyright (C) 2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . import requests from html.parser import HTMLParser import json import os.path import re URL = "https://techblog.willshouse.com/2012/01/03/most-common-user-agents/" SCRIPT_DIR = os.path.dirname(__file__) OUT_PATH = os.path.join(SCRIPT_DIR, "..", "librecaptcha", "user_agent_data.py") NUM_ENTRIES = 30 HEADER = """\ # This file was automatically generated by update_user_agents.py using data # from . # flake8: noqa USER_AGENTS = \ """ FOOTER = "\n" class Parser(HTMLParser): def __init__(self): self.desc_seen = False self.result = None super().__init__() def handle_data(self, data): if self.result is not None: return if data is None: return if not self.desc_seen: self.desc_seen = bool(re.search(r"\bplain-text\b", data)) return if re.match(r"\s*Mozilla/", data): self.result = data def get_agents(data): agents = [] for agent in data.strip().splitlines()[:NUM_ENTRIES]: if len(agents) >= NUM_ENTRIES: break if re.match(r"\b(iPhone|iPad|Android)\b", agent): continue agents.append(agent) return agents def write_agents(agents, file): print(HEADER, file=file, end="") json.dump(agents, file, indent=4) print(FOOTER, file=file, end="") def main(): r = requests.get(URL) parser = Parser() parser.feed(r.text) with open(OUT_PATH, "w", encoding="utf8") as f: agents = get_agents(parser.result) write_agents(agents, f) if __name__ == "__main__": main() librecaptcha-0.6.2/setup.py000077500000000000000000000046561345160434500156750ustar00rootroot00000000000000#!/usr/bin/env python3 # Copyright (C) 2016-2019 nickolas360 # # This file is part of librecaptcha. # # librecaptcha is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # librecaptcha is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with librecaptcha. If not, see . from setuptools import setup import os SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) REPO_URL = "https://github.com/nickolas360/librecaptcha" DESC_REPLACEMENTS = { ".. _LICENSE: LICENSE": ".. _LICENSE: {}/blob/master/LICENSE".format(REPO_URL), } def long_description(): with open(os.path.join(SCRIPT_DIR, "README.rst"), encoding='utf-8') as f: lines = f.read().splitlines() result = [] for line in lines: result.append(DESC_REPLACEMENTS.get(line, line) + "\n") return "".join(result) LICENSE = """\ License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\ """ setup( name="librecaptcha", version="0.6.2", description="A free/libre interface for solving reCAPTCHA challenges.", long_description=long_description(), url="https://github.com/nickolas360/librecaptcha", author="nickolas360", author_email="contact@nickolas360.com", license="GNU General Public License v3 or later (GPLv3+)", classifiers=[ "Development Status :: 4 - Beta", "Topic :: Internet", LICENSE, "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], keywords="captcha recaptcha", packages=["librecaptcha"], entry_points={ "console_scripts": [ "librecaptcha=librecaptcha:main", ], }, install_requires=[ "Pillow>=4.1.1", "requests>=2.18.1", "slimit>=0.8.1", ], extras_require={ "gtk": [ "PyGObject>=3.30.0", ] }, )