commit a1176afa153c171118a01315102b5430c140bed5 Author: 502647092 Date: Mon Oct 12 15:26:15 2015 +0800 init project... Signed-off-by: 502647092 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a0348ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,125 @@ +# Created by https://www.gitignore.io + +### Java ### +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +#*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + + +### Eclipse ### +*.pydevproject +.metadata +.gradle +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath + +# Eclipse Core +.project + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# PDT-specific +.buildpath + +# sbteclipse plugin +.target + +# TeXlipse plugin +.texlipse + + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties + + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +nbactions.xml +nb-configuration.xml +.nb-gradle/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..f6b0f14 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,19 @@ +sudo: false + +language: java +jdk: oraclejdk7 + +cache: + directories: + - '$HOME/.m2/repository' + +script: + - mvn clean install -B && mvn clean -B + +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/952357dbd9d3cea70fd5 + on_success: change # options: [always|never|change] default: always + on_failure: always # options: [always|never|change] default: always + on_start: false # default: false diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + 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. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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: + + {project} Copyright (C) {year} {fullname} + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..056700d --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +

+

The most used authentication plugin for CraftBukkit/Spigot!

+
+#####Development tools: + +- DEVELOPMENT TEAM REPO (please send PRs here!): Github Development Page + +- Developers ChatRoom: [![Join the chat at https://gitter.im/Xephi/AuthMeReloaded](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Xephi/AuthMeReloaded?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +- Build status: [![Build Status](https://travis-ci.org/Xephi/AuthMeReloaded.svg?branch=master)](https://travis-ci.org/Xephi/AuthMeReloaded) [![Dependency Status](https://www.versioneye.com/user/projects/55bab9e8653762002000190a/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55bab9e8653762002000190a) + +- Build status (CircleCI): [![Circle CI](https://circleci.com/gh/Xephi/AuthMeReloaded.svg?style=svg)](https://circleci.com/gh/Xephi/AuthMeReloaded) + +- Issue Tracking : [![Stories in Ready](https://badge.waffle.io/Xephi/AuthMeReloaded.png?label=ready&title=Ready)](https://waffle.io/Xephi/AuthMeReloaded) [![Stories in Bugs](https://badge.waffle.io/Xephi/AuthMeReloaded.png?label=bugs&title=Bugs)](https://waffle.io/Xephi/AuthMeReloaded) [![Stories in In%20Progress](https://badge.waffle.io/Xephi/AuthMeReloaded.png?label=in%20progress&title=In%20Progress)](https://waffle.io/Xephi/AuthMeReloaded) + +- Build Server (DEVELOPMENT BUILDS): Xephi's Jenkins + +- JavaDocs: AuthMe Javadoc + +- Maven Repo: AuthMe Repo + +#####Statistics: + +McStats: http://mcstats.org/plugin/AuthMe + + + + + + + +
+ +#####Compiling Requirements: +>- JDK 1.7 +>- Maven +>- Git/Github (Optional) + +#####How to compile the project: +>- Clone the project with Git/Github +>- Execute command "mvn clean install" + +#####Running Requirements: +>- Java 1.7 (should work also with Java 1.8) +>- Spigot or CraftBukkit (1.7.10 or 1.8.X) +>- Vault +>- Protocollib + +
+###Plugin Description: + +#####"The best authentication plugin for the Bukkit/Spigot API!" + +

Prevent username stealing on your server! Full compatible with UUIDs and Craftbukkit/Spigot 1.8.X!
+Use it to secure your Offline mode server or to incrase your Online mode server's protection!

+ +

AuthMeReloaded disallows players who aren't authenticated to do actions like placing blocks, moving,
+typing commands or use the inventory. It can also kick players with uncommon long or short player names or kick players from banned countries.

+

With the Session Login feature you don't have to execute the authentication command everytime you connect to the server! Each command and every feature can be enabled or disabled from our well structured configuration file.

+

You can also create your own translation file and, if you want, you can share it with us! :)

+ +####Features: +
    +
  • E-Mail Recovery System !!!
  • +
  • Username spoofing protection.
  • +
  • Countries Whitelist/Blacklist! (countries codes)
  • +
  • Built-in AntiBot System!
  • +
  • ForceLogin Feature: Admins can login with all account via console command!
  • +
  • Avoid the "Logged in from another location" message!
  • +
  • Session Login!
  • +
  • Editable translations and messages!
  • +
  • MySQL and SQLite Backend support!
  • +
  • Supported password encryption algorithms: MD5, SHA1, SHA256, xAuth, Whirlpool
  • +
  • Supported alternative registration methods:
    +
      +
    • PHPBB, VBullettin: MD5VB - PHPBB
    • +
    • MyBB: MYBB
    • +
    • IPB3: IPB3
    • +
    • PhpFusion: PHPFUSION
    • +
    • Xenforo SHA1: XFSHA1 (Deprecated)
    • +
    • Xenforo SHA256: XFSHA256 (Deprecated)
    • +
    • Joomla: JOOMLA
    • +
    • WBB3: WBB3*
    • +
    • SHA512: SHA512
    • +
    • DoubleSaltedMD5: SALTED2MD5
    • +
    • WordPress: WORDPRESS
    • +
  • +
  • Custom MySQL tables/columns names (useful with forums databases)
  • +
  • Cached database queries!
  • +
  • Full compatible with Citizens2, CombatTag, CombatTagPlus and ChestShop!
  • +
  • Compatible with Minecraft mods like BuildCraft or RedstoneCraft
  • +
  • Restricted users (associate a Username with an IP)
  • +
  • Protect player's inventory until a correct Authentication
  • +
  • Saves the quit location of the player
  • +
  • Automatic database Backup
  • +
  • Avariable languages: en, de, br, cz, pl, fr, uk, ru, hu, sk, es, fi, zhtw, zhhk, zhcn, lt, it, ko, pt, nl, gl, bg, eu, tr (feel free to send new translations)
  • +
  • Built-in Deprecated FlatFile (auths.db) to SQL (authme.sql) converter!
  • +
  • Import your old database from other plugins like Rakamak, xAuth, CrazyLogin, RoyalAuth and vAuth!
  • +
+ +####Configuration +How to Configure Authme +####Email Recovery Dependency +How to configure email recovery system? +####Commands +Command list and usage +####Permissions +
  • authme.player.* - for all user command +
  • authme.admin.* - for all admin command +
  • authme.* - for all user and admin command +
  • List of all single permissions +
+####How To + +
+ +#####GeoIP +

This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com

+
+ +#####Donate +

Do you like my work? Do you want to buy me a coffee? :)
+EUR: +USD:

+ +#####Sponsor +GameHosting.it is leader in Italy as Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware. +[![GameHosting](http://www.gamehosting.it/images/bn3.png)](http://www.gamehosting.it) + +#####Credits +

Team members: look at the team.txt file +

Credit for old version of the plugin to: d4rkwarriors, fabe1337 , Whoami2 and pomo4ka

+

Thanks also to: AS1LV3RN1NJA, Hoeze and eprimex

diff --git a/circle.yml b/circle.yml new file mode 100644 index 0000000..6da929d --- /dev/null +++ b/circle.yml @@ -0,0 +1,9 @@ +machine: + java: + version: oraclejdk7 +general: + artifacts: + - "target/AuthMe-*.jar" +test: + override: + - mvn clean install -B diff --git a/lib/Essentials.jar b/lib/Essentials.jar new file mode 100644 index 0000000..f056eec Binary files /dev/null and b/lib/Essentials.jar differ diff --git a/lib/ProtocolLib-3.6.5-SNAPSHOT.jar b/lib/ProtocolLib-3.6.5-SNAPSHOT.jar new file mode 100644 index 0000000..ec73d32 Binary files /dev/null and b/lib/ProtocolLib-3.6.5-SNAPSHOT.jar differ diff --git a/lib/Vault.jar b/lib/Vault.jar new file mode 100644 index 0000000..f9aa324 Binary files /dev/null and b/lib/Vault.jar differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..6090c3d --- /dev/null +++ b/pom.xml @@ -0,0 +1,309 @@ + + + 4.0.0 + + fr.xephi + authme + 5.1-SNAPSHOT + jar + + AuthMeReloaded + Authentication plugin for CraftBukkit/Spigot! + 2013 + http://dev.bukkit.org/bukkit-plugins/authme-reloaded/ + + + + AuthMe-Team + https://github.com/AuthMe-Team + + + + scm:git:https://github.com/Xephi/AuthMeReloaded.git + scm:git:git@github.com:Xephi/AuthMeReloaded.git + http://github.com/Xephi/AuthMeReloaded + + + + + jenkins + http://ci.xephi.fr/job/AuthMeReloaded/ + + + + GitHub + https://github.com/Xephi/AuthMeReloaded/issues + + + + + The GNU General Public Licence version 3 (GPLv3) + http://www.gnu.org/licenses/gpl-3.0.html + + + + + UTF-8 + + 1.7 + + 1.8.8-R0.1-SNAPSHOT + + + + AuthMe-${project.version} + + + . + true + src/main/resources/ + + *.yml + + + + ./messages/ + false + src/main/resources/messages/ + + *.yml + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.7 + ${javaVersion} + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + false + true + + + com.zaxxer:HikariCP + org.slf4j:slf4j-jdk14 + org.slf4j:slf4j-api + com.maxmind.geoip:geoip-api + com.google.code.gson:gson + + + + + + package + + shade + + + + + + + + + + + + spigot-repo + http://hub.spigotmc.org/nexus/content/groups/public + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.spigotmc + spigot-api + jar + 1.8.8-R0.1-SNAPSHOT + + + cn.citycraft + PluginHelper + jar + 1.0 + + + net.milkbowl.vault + VaultAPI + 1.5 + system + ${project.basedir}/lib/Vault.jar + + + com.earth2me + essentials + 2.9.6 + system + ${project.basedir}/lib/Essentials.jar + + + com.zaxxer + HikariCP + 2.4.1 + compile + true + + + com.maxmind.geoip + geoip-api + 1.2.15 + compile + true + + + + org.apache.logging.log4j + log4j-core + 2.0-beta9 + provided + true + + + com.comphenix.protocol + ProtocolLib + 3.6.5-SNAPSHOT + system + ${project.basedir}/lib/ProtocolLib-3.6.5-SNAPSHOT.jar + + + + + + + + diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java new file mode 100644 index 0000000..d58390c --- /dev/null +++ b/src/main/java/fr/xephi/authme/AuthMe.java @@ -0,0 +1,738 @@ +package fr.xephi.authme; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; + +import org.apache.logging.log4j.LogManager; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; + +import com.earth2me.essentials.Essentials; + +import fr.xephi.authme.api.API; +import fr.xephi.authme.api.NewAPI; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.backup.JsonCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.commands.AdminCommand; +import fr.xephi.authme.commands.CaptchaCommand; +import fr.xephi.authme.commands.ChangePasswordCommand; +import fr.xephi.authme.commands.ConverterCommand; +import fr.xephi.authme.commands.LoginCommand; +import fr.xephi.authme.commands.LogoutCommand; +import fr.xephi.authme.commands.RegisterCommand; +import fr.xephi.authme.commands.UnregisterCommand; +import fr.xephi.authme.converter.Converter; +import fr.xephi.authme.converter.ForceFlatToSqlite; +import fr.xephi.authme.datasource.CacheDataSource; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.datasource.DatabaseCalls; +import fr.xephi.authme.datasource.FlatFile; +import fr.xephi.authme.datasource.MySQL; +import fr.xephi.authme.datasource.SQLite; +import fr.xephi.authme.datasource.SQLite_HIKARI; +import fr.xephi.authme.listener.AuthMeBlockListener; +import fr.xephi.authme.listener.AuthMeEntityListener; +import fr.xephi.authme.listener.AuthMeInventoryPacketAdapter; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.listener.AuthMePlayerListener16; +import fr.xephi.authme.listener.AuthMePlayerListener18; +import fr.xephi.authme.listener.AuthMeServerListener; +import fr.xephi.authme.modules.ModuleManager; +import fr.xephi.authme.plugin.manager.BungeeCordMessage; +import fr.xephi.authme.plugin.manager.EssSpawn; +import fr.xephi.authme.process.Management; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.OtherAccounts; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.Spawn; +import net.milkbowl.vault.permission.Permission; + +public class AuthMe extends JavaPlugin { + + private static AuthMe authme; + private static Server server; + public boolean antibotMod = false; + + public NewAPI api; + public ConcurrentHashMap cap = new ConcurrentHashMap<>(); + public ConcurrentHashMap captcha = new ConcurrentHashMap<>(); + public DataSource database; + public DataManager dataManager; + public boolean delayedAntiBot = true; + public Essentials ess; + public Location essentialsSpawn; + public AuthMeInventoryPacketAdapter inventoryProtector; + public Management management; + public OtherAccounts otherAccounts; + + // Hooks TODO: move into modules + public Permission permission; + public ConcurrentHashMap realIp = new ConcurrentHashMap<>(); + // TODO: Create Manager for fields below + public ConcurrentHashMap sessions = new ConcurrentHashMap<>(); + + private Logger authmeLogger; + + private Messages m; + // Module manager + private ModuleManager moduleManager; + private JsonCache playerBackup; + private Settings settings; + + public static AuthMe getInstance() { + return authme; + } + + public boolean authmePermissible(final CommandSender sender, final String perm) { + if (sender.hasPermission(perm)) { + return true; + } else if (permission != null) { + return permission.has(sender, perm); + } + return false; + } + + // Check if a player/command sender have a permission + public boolean authmePermissible(final Player player, final String perm) { + if (player.hasPermission(perm)) { + return true; + } else if (permission != null) { + return permission.playerHas(player, perm); + } + return false; + } + + // Get the Essentials plugin + public void checkEssentials() { + if (server.getPluginManager().isPluginEnabled("Essentials")) { + try { + ess = (Essentials) server.getPluginManager().getPlugin("Essentials"); + ConsoleLogger.info("发现 Essentials 启用相关功能..."); + } catch (Exception | NoClassDefFoundError ingnored) { + ess = null; + } + } else { + ess = null; + } + if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) { + try { + essentialsSpawn = new EssSpawn().getLocation(); + ConsoleLogger.info("发现 EssentialsSpawn 读取重生点..."); + } catch (final Exception e) { + essentialsSpawn = null; + ConsoleLogger.showError("无法读取文件 /plugins/Essentials/spawn.yml !"); + } + } else { + essentialsSpawn = null; + } + } + + // Check the presence of the ProtocolLib plugin + public void checkProtocolLib() { + if (Settings.protectInventoryBeforeLogInEnabled) { + if (server.getPluginManager().isPluginEnabled("ProtocolLib")) { + inventoryProtector = new AuthMeInventoryPacketAdapter(this); + inventoryProtector.register(); + } else { + ConsoleLogger.showError("警告!!! 保护背包功能必须启用 ProtocolLib 插件 但是未找到! 关闭该功能..."); + Settings.protectInventoryBeforeLogInEnabled = false; + } + } + } + + // Check the presence of the Vault plugin and a permissions provider + public void checkVault() { + if (server.getPluginManager().isPluginEnabled("Vault")) { + final RegisteredServiceProvider permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); + if (permissionProvider != null) { + permission = permissionProvider.getProvider(); + ConsoleLogger.info("发现 Vault 使用经济系统: " + permission.getName()); + } else { + ConsoleLogger.showError("发现 Vault, 但是 Vault 未找到权限系统..."); + } + } else { + permission = null; + } + } + + // Select the player to kick when a vip player join the server when full + public Player generateKickPlayer(final Collection collection) { + Player player = null; + for (final Player p : collection) { + if (!(authmePermissible(p, "authme.vip"))) { + player = p; + break; + } + } + return player; + } + + @Deprecated + public String getCountryCode(final String ip) { + return Utils.getCountryCode(ip); + } + + @Deprecated + public String getCountryName(final String ip) { + return Utils.getCountryName(ip); + } + + public String getIP(final Player player) { + final String name = player.getName().toLowerCase(); + String ip = player.getAddress().getAddress().getHostAddress(); + if (Settings.bungee) { + if (realIp.containsKey(name)) { + ip = realIp.get(name); + } + } + if (Settings.checkVeryGames) { + if (getVeryGamesIP(player) != null) { + ip = getVeryGamesIP(player); + } + } + return ip; + } + + public Messages getMessages() { + return m; + } + + public ModuleManager getModuleManager() { + return moduleManager; + } + + public Settings getSettings() { + return settings; + } + + // Return the spawn location of a player + public Location getSpawnLocation(final Player player) { + final World world = player.getWorld(); + final String[] spawnPriority = Settings.spawnPriority.split(","); + Location spawnLoc = world.getSpawnLocation(); + for (int i = spawnPriority.length - 1; i >= 0; i--) { + final String s = spawnPriority[i]; + if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null) { + spawnLoc = getDefaultSpawn(world); + } + if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null) { + spawnLoc = getEssentialsSpawn(); + } + if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null) { + spawnLoc = getAuthMeSpawn(player); + } + } + if (spawnLoc == null) { + spawnLoc = world.getSpawnLocation(); + } + return spawnLoc; + } + + /** + * Get Player real IP through VeryGames method + * + * @param player + * player + */ + @Deprecated + public String getVeryGamesIP(final Player player) { + String realIP = player.getAddress().getAddress().getHostAddress(); + String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%"; + sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort()); + try { + final URL url = new URL(sUrl); + final URLConnection urlc = url.openConnection(); + final BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); + final String inputLine = in.readLine(); + if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) { + realIP = inputLine; + } + } catch (final Exception ignored) { + } + return realIP; + } + + public boolean hasJoinedIp(final String name, final String ip) { + int count = 0; + for (final Player player : Utils.getOnlinePlayers()) { + if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name)) { + count++; + } + } + return count >= Settings.getMaxJoinPerIp; + } + + public boolean isLoggedIp(final String name, final String ip) { + int count = 0; + for (final Player player : Utils.getOnlinePlayers()) { + if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name)) { + count++; + } + } + return count >= Settings.getMaxLoginPerIp; + } + + @Override + public void onDisable() { + // Save player data + final Collection players = Utils.getOnlinePlayers(); + if (players != null) { + for (final Player player : players) { + this.savePlayer(player); + } + } + + // Close the database + if (database != null) { + database.close(); + } + + // Do backup on stop if enabled + if (Settings.isBackupActivated && Settings.isBackupOnStop) { + final boolean Backup = new PerformBackup(this).doBackup(); + if (Backup) { + ConsoleLogger.info("Backup performed correctly."); + } else { + ConsoleLogger.showError("Error while performing the backup!"); + } + } + + // Unload modules + moduleManager.unloadModules(); + + // Disabled correctly + ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!"); + } + + @SuppressWarnings("deprecation") + @Override + public void onEnable() { + // Set the Instance + server = getServer(); + authmeLogger = Logger.getLogger("AuthMe"); + authme = this; + + // TODO: split the plugin in more modules + moduleManager = new ModuleManager(this); + @SuppressWarnings("unused") + final int loaded = moduleManager.loadModules(); + + // TODO: remove vault as hard dependency + final PluginManager pm = server.getPluginManager(); + + // Setup the Logger + if (authmeLogger == null) { + authmeLogger = this.getLogger(); + } else { + authmeLogger.setParent(this.getLogger()); + } + + // Load settings and custom configurations + // TODO: new configuration style (more files) + try { + settings = new Settings(this); + Settings.reload(); + } catch (final Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!"); + server.shutdown(); + return; + } + + // Setup otherAccounts file + otherAccounts = OtherAccounts.getInstance(); + + // Setup messages + m = Messages.getInstance(); + + // Set Console Filter + if (Settings.removePassword) { + final ConsoleFilter filter = new ConsoleFilter(); + this.getLogger().setFilter(filter); + Bukkit.getLogger().setFilter(filter); + Logger.getLogger("Minecraft").setFilter(filter); + authmeLogger.setFilter(filter); + // Set Log4J Filter + try { + Class.forName("org.apache.logging.log4j.core.Filter"); + setLog4JFilter(); + } catch (ClassNotFoundException | NoClassDefFoundError e) { + ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled"); + } + } + + // AntiBot delay + if (Settings.enableAntiBot) { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + @Override + public void run() { + delayedAntiBot = false; + } + }, 2400); + } + + // Download GeoIp.dat file + Utils.checkGeoIP(); + + // Find Permissions + checkVault(); + + // Check Essentials + checkEssentials(); + + // Check if the protocollib is available. If so we could listen for + // inventory protection + checkProtocolLib(); + + // Do backup on start if enabled + if (Settings.isBackupActivated && Settings.isBackupOnStart) { + // Do backup and check return value! + if (new PerformBackup(this).doBackup()) { + ConsoleLogger.info("Backup performed correctly"); + } else { + ConsoleLogger.showError("Error while performing the backup!"); + } + } + + // Connect to the database and setup tables + try { + setupDatabase(); + } catch (final Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError(e.getMessage()); + ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!"); + stopOrUnload(); + return; + } + + // Setup the inventory backup + playerBackup = new JsonCache(); + + // Set the DataManager + dataManager = new DataManager(this); + + // Setup the new API + api = new NewAPI(this); + // Setup the old deprecated API + new API(this); + + // Setup Management + management = new Management(this); + + // Bungeecord hook + if (Settings.bungee) { + Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this)); + } + + // Reload support hook + if (Settings.reloadSupport) { + if (database != null) { + final int playersOnline = Utils.getOnlinePlayers().size(); + if (playersOnline < 1) { + database.purgeLogged(); + } else { + for (final PlayerAuth auth : database.getLoggedPlayers()) { + if (auth == null) { + continue; + } + auth.setLastLogin(new Date().getTime()); + database.updateSession(auth); + PlayerCache.getInstance().addPlayer(auth); + } + } + } + } + + // Register events + pm.registerEvents(new AuthMePlayerListener(this), this); + // Try to register 1.6 player listeners + try { + Class.forName("org.bukkit.event.player.PlayerEditBookEvent"); + pm.registerEvents(new AuthMePlayerListener16(this), this); + } catch (final ClassNotFoundException ignore) { + } + // Try to register 1.8 player listeners + try { + Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent"); + pm.registerEvents(new AuthMePlayerListener18(this), this); + } catch (final ClassNotFoundException ignore) { + } + pm.registerEvents(new AuthMeBlockListener(this), this); + pm.registerEvents(new AuthMeEntityListener(this), this); + pm.registerEvents(new AuthMeServerListener(this), this); + + // Register commands + getCommand("authme").setExecutor(new AdminCommand(this)); + getCommand("register").setExecutor(new RegisterCommand(this)); + getCommand("login").setExecutor(new LoginCommand(this)); + getCommand("changepassword").setExecutor(new ChangePasswordCommand(this)); + getCommand("logout").setExecutor(new LogoutCommand(this)); + getCommand("unregister").setExecutor(new UnregisterCommand(this)); + getCommand("captcha").setExecutor(new CaptchaCommand(this)); + getCommand("converter").setExecutor(new ConverterCommand(this)); + + // Purge on start if enabled + autoPurge(); + + // Start Email recall task if needed + recallEmail(); + + // Configuration Security Warnings + if (!Settings.isForceSingleSessionEnabled) { + ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!"); + } + if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) { + ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!"); + } + + // Sponsor messages + ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!"); + ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt."); + ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!"); + + // Successful message + ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!"); + } + + public String replaceAllInfos(String message, final Player player) { + final int playersOnline = Utils.getOnlinePlayers().size(); + message = message.replace("&", "§"); + message = message.replace("{PLAYER}", player.getName()); + message = message.replace("{ONLINE}", "" + playersOnline); + message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers()); + message = message.replace("{IP}", getIP(player)); + message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged()); + message = message.replace("{WORLD}", player.getWorld().getName()); + message = message.replace("{SERVER}", server.getServerName()); + message = message.replace("{VERSION}", server.getBukkitVersion()); + message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player))); + return message; + } + + // Save Player Data + public void savePlayer(final Player player) { + if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) { + return; + } + final String name = player.getName().toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) { + final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), + player.getName()); + database.updateQuitLoc(auth); + } + if (LimboCache.getInstance().hasLimboPlayer(name)) { + final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (!Settings.noTeleport) { + player.teleport(limbo.getLoc()); + } + + Utils.addNormal(player, limbo.getGroup()); + player.setOp(limbo.getOperator()); + limbo.getTimeoutTaskId().cancel(); + LimboCache.getInstance().deleteLimboPlayer(name); + if (this.playerBackup.doesCacheExist(player)) { + this.playerBackup.removeCache(player); + } + } + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + player.saveData(); + } + + public void setMessages(final Messages m) { + this.m = m; + } + + // Initialize and setup the database + public void setupDatabase() throws Exception { + if (database != null) { + database.close(); + } + // Backend MYSQL - FILE - SQLITE - SQLITEHIKARI + boolean isSQLite = false; + switch (Settings.getDataSource) { + case FILE: + database = new FlatFile(); + break; + case MYSQL: + database = new MySQL(); + break; + case SQLITE: + database = new SQLite(); + isSQLite = true; + break; + case SQLITEHIKARI: + database = new SQLite_HIKARI(); + isSQLite = true; + break; + } + + if (isSQLite) { + server.getScheduler().runTaskAsynchronously(this, new Runnable() { + + @Override + public void run() { + final int accounts = database.getAccountsRegistered(); + if (accounts >= 4000) { + ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!"); + } + } + }); + } + + if (Settings.isCachingEnabled) { + database = new CacheDataSource(this, database); + } else { + database = new DatabaseCalls(database); + } + + if (Settings.getDataSource == DataSource.DataSourceType.FILE) { + final Converter converter = new ForceFlatToSqlite(database, this); + server.getScheduler().runTaskAsynchronously(this, converter); + ConsoleLogger.showError( + "FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !"); + ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart"); + } + } + + // Stop/unload the server/plugin as defined in the configuration + public void stopOrUnload() { + if (Settings.isStopEnabled) { + ConsoleLogger.showError("THE SERVER IS GOING TO SHUTDOWN AS DEFINED IN THE CONFIGURATION!"); + server.shutdown(); + } else { + server.getPluginManager().disablePlugin(AuthMe.getInstance()); + } + } + + // Show the exception message and stop/unload the server/plugin as defined + // in the configuration + public void stopOrUnload(final Exception e) { + ConsoleLogger.showError(e.getMessage()); + stopOrUnload(); + } + + public void switchAntiBotMod(final boolean mode) { + this.antibotMod = mode; + Settings.switchAntiBotMod(mode); + } + + // Purge inactive players from the database, as defined in the configuration + private void autoPurge() { + if (!Settings.usePurge) { + return; + } + final Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DATE, -(Settings.purgeDelay)); + final long until = calendar.getTimeInMillis(); + final List cleared = database.autoPurgeDatabase(until); + if (cleared == null) { + return; + } + if (cleared.isEmpty()) { + return; + } + ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!"); + if (Settings.purgeEssentialsFile && this.ess != null) { + dataManager.purgeEssentials(cleared); // name to UUID convertion + } + // needed with latest versions + if (Settings.purgePlayerDat) { + dataManager.purgeDat(cleared); // name to UUID convertion needed + } + // with latest versions of MC + if (Settings.purgeLimitedCreative) { + dataManager.purgeLimitedCreative(cleared); + } + if (Settings.purgeAntiXray) { + dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or + } + // names... (Actually it purges + // only names!) + if (Settings.purgePermissions) { + dataManager.purgePermissions(cleared, permission); + } + } + + // Return the authme soawnpoint + private Location getAuthMeSpawn(final Player player) { + if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) { + return Spawn.getInstance().getFirstSpawn(); + } + if (Spawn.getInstance().getSpawn() != null) { + return Spawn.getInstance().getSpawn(); + } + return player.getWorld().getSpawnLocation(); + } + + // Return the default spawnpoint of a world + private Location getDefaultSpawn(final World world) { + return world.getSpawnLocation(); + } + + // Return the essentials spawnpoint + private Location getEssentialsSpawn() { + if (essentialsSpawn != null) { + return essentialsSpawn; + } + return null; + } + + private void recallEmail() { + if (!Settings.recallEmail) { + return; + } + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { + + @Override + public void run() { + for (final Player player : Utils.getOnlinePlayers()) { + if (player.isOnline()) { + final String name = player.getName().toLowerCase(); + if (database.isAuthAvailable(name)) { + if (PlayerCache.getInstance().isAuthenticated(name)) { + final String email = database.getAuth(name).getEmail(); + if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) { + m.send(player, "add_email"); + } + } + } + } + } + } + }, 1, 1200 * Settings.delayRecall); + } + + // Set the console filter to remove the passwords + private void setLog4JFilter() { + Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + @Override + public void run() { + final org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); + coreLogger.addFilter(new Log4JFilter()); + } + }); + } +} diff --git a/src/main/java/fr/xephi/authme/ConsoleFilter.java b/src/main/java/fr/xephi/authme/ConsoleFilter.java new file mode 100644 index 0000000..eaa63a9 --- /dev/null +++ b/src/main/java/fr/xephi/authme/ConsoleFilter.java @@ -0,0 +1,35 @@ +package fr.xephi.authme; + +import java.util.logging.Filter; +import java.util.logging.LogRecord; + +/** + * + * @author Xephi59 + */ +public class ConsoleFilter implements Filter { + + public ConsoleFilter() { + } + + @Override + public boolean isLoggable(LogRecord record) { + try { + if (record == null || record.getMessage() == null) + return true; + String logM = record.getMessage().toLowerCase(); + if (!logM.contains("issued server command:")) + return true; + if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") + && !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") + && !logM.contains("/register ")) + return true; + String playername = record.getMessage().split(" ")[0]; + record.setMessage(playername + " issued an AuthMe command!"); + return true; + } catch (NullPointerException npe) { + return true; + } + } + +} diff --git a/src/main/java/fr/xephi/authme/ConsoleLogger.java b/src/main/java/fr/xephi/authme/ConsoleLogger.java new file mode 100644 index 0000000..dfe20e7 --- /dev/null +++ b/src/main/java/fr/xephi/authme/ConsoleLogger.java @@ -0,0 +1,61 @@ +package fr.xephi.authme; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.logging.Logger; + +import com.google.common.base.Throwables; + +import fr.xephi.authme.api.NewAPI; +import fr.xephi.authme.settings.Settings; + +public class ConsoleLogger { + + private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]"); + private static final Logger log = AuthMe.getInstance().getLogger(); + + public static void info(final String message) { + if (AuthMe.getInstance().isEnabled()) { + log.info(message); + if (Settings.useLogging) { + String dateTime; + synchronized (df) { + dateTime = df.format(new Date()); + } + writeLog(dateTime + " " + message); + } + } + } + + public static void showError(final String message) { + if (AuthMe.getInstance().isEnabled()) { + log.warning(message); + if (Settings.useLogging) { + String dateTime; + synchronized (df) { + dateTime = df.format(new Date()); + } + writeLog(dateTime + " ERROR: " + message); + } + } + } + + public static void writeLog(final String message) { + try { + Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE); + } catch (final IOException ignored) { + } + } + + public static void writeStackTrace(final Exception ex) { + String dateTime; + synchronized (df) { + dateTime = df.format(new Date()); + } + writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex)); + } +} diff --git a/src/main/java/fr/xephi/authme/DataManager.java b/src/main/java/fr/xephi/authme/DataManager.java new file mode 100644 index 0000000..b7dc9cb --- /dev/null +++ b/src/main/java/fr/xephi/authme/DataManager.java @@ -0,0 +1,201 @@ +package fr.xephi.authme; + +import java.io.File; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import fr.xephi.authme.settings.Settings; +import net.milkbowl.vault.permission.Permission; + +public class DataManager { + + public AuthMe plugin; + + public DataManager(final AuthMe plugin) { + this.plugin = plugin; + } + + public synchronized OfflinePlayer getOfflinePlayer(final String name) { + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final Future result = executor.submit(new Callable() { + + @Override + public synchronized OfflinePlayer call() throws Exception { + OfflinePlayer result = null; + try { + for (final OfflinePlayer op : Bukkit.getOfflinePlayers()) { + if (op.getName().equalsIgnoreCase(name)) { + result = op; + break; + } + } + } catch (final Exception e) { + } + return result; + } + }); + try { + return result.get(); + } catch (final Exception e) { + return (null); + } finally { + executor.shutdown(); + } + } + + public boolean isOnline(final Player player, final String name) { + if (player.isOnline()) { + return true; + } + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final Future result = executor.submit(new Callable() { + @Override + public synchronized Boolean call() throws Exception { + for (final OfflinePlayer op : Utils.getOnlinePlayers()) { + if (op.getName().equalsIgnoreCase(name)) { + return true; + } + } + return false; + } + }); + try { + return result.get(); + } catch (final Exception e) { + return false; + } finally { + executor.shutdown(); + } + } + + public synchronized void purgeAntiXray(final List cleared) { + int i = 0; + for (final String name : cleared) { + try { + final org.bukkit.OfflinePlayer player = getOfflinePlayer(name); + if (player == null) { + continue; + } + final String playerName = player.getName(); + final File playerFile = new File("." + File.separator + "plugins" + File.separator + "AntiXRayData" + File.separator + "PlayerData" + File.separator + playerName); + if (playerFile.exists()) { + playerFile.delete(); + i++; + } + } catch (final Exception e) { + } + } + ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " AntiXRayData Files"); + } + + public synchronized void purgeDat(final List cleared) { + int i = 0; + for (final String name : cleared) { + try { + final org.bukkit.OfflinePlayer player = getOfflinePlayer(name); + File playerFile = null; + if (player == null) { + continue; + } + try { + playerFile = new File( + plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getUniqueId() + ".dat"); + } catch (final Exception ignore) { + } + if (playerFile != null && playerFile.exists()) { + playerFile.delete(); + i++; + } else { + playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getName() + ".dat"); + if (playerFile.exists()) { + playerFile.delete(); + i++; + } + } + } catch (final Exception ignore) { + } + } + ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " .dat Files"); + } + + @SuppressWarnings("deprecation") + public void purgeEssentials(final List cleared) { + int i = 0; + for (final String name : cleared) { + try { + File playerFile = null; + try { + playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + plugin.getServer().getOfflinePlayer(name).getUniqueId() + ".yml"); + } catch (final Exception ignore) { + } + if (playerFile != null && playerFile.exists()) { + playerFile.delete(); + i++; + } else { + playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml"); + if (playerFile.exists()) { + playerFile.delete(); + i++; + } + } + } catch (final Exception e) { + } + } + ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " EssentialsFiles"); + } + + public synchronized void purgeLimitedCreative(final List cleared) { + int i = 0; + for (final String name : cleared) { + try { + final org.bukkit.OfflinePlayer player = getOfflinePlayer(name); + if (player == null) { + continue; + } + final String playerName = player.getName(); + File playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + ".yml"); + if (playerFile.exists()) { + playerFile.delete(); + i++; + } + playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_creative.yml"); + if (playerFile.exists()) { + playerFile.delete(); + i++; + } + playerFile = new File("." + File.separator + "plugins" + File.separator + "LimitedCreative" + File.separator + "inventories" + File.separator + playerName + "_adventure.yml"); + if (playerFile.exists()) { + playerFile.delete(); + i++; + } + } catch (final Exception e) { + } + } + ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " LimitedCreative Survival, Creative and Adventure files"); + } + + public synchronized void purgePermissions(final List cleared, final Permission permission) { + int i = 0; + for (final String name : cleared) { + try { + final OfflinePlayer p = this.getOfflinePlayer(name); + for (final String group : permission.getPlayerGroups((Player) p)) { + permission.playerRemoveGroup(null, p, group); + } + i++; + } catch (final Exception e) { + } + } + ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " Permissions"); + } + + public void run() { + } +} diff --git a/src/main/java/fr/xephi/authme/ImageGenerator.java b/src/main/java/fr/xephi/authme/ImageGenerator.java new file mode 100644 index 0000000..cf9af99 --- /dev/null +++ b/src/main/java/fr/xephi/authme/ImageGenerator.java @@ -0,0 +1,31 @@ +package fr.xephi.authme; + +import java.awt.Color; +import java.awt.Font; +import java.awt.GradientPaint; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +public class ImageGenerator { + + private String pass; + + public ImageGenerator(String pass) { + this.pass = pass; + } + + public BufferedImage generateImage() { + BufferedImage image = new BufferedImage(200, 60, BufferedImage.TYPE_BYTE_INDEXED); + Graphics2D graphics = image.createGraphics(); + graphics.setColor(Color.BLACK); + graphics.fillRect(0, 0, 200, 40); + GradientPaint gradientPaint = new GradientPaint(10, 5, Color.WHITE, 20, 10, Color.WHITE, true); + graphics.setPaint(gradientPaint); + Font font = new Font("Comic Sans MS", Font.BOLD, 30); + graphics.setFont(font); + graphics.drawString(pass, 5, 30); + graphics.dispose(); + image.flush(); + return image; + } +} diff --git a/src/main/java/fr/xephi/authme/Log4JFilter.java b/src/main/java/fr/xephi/authme/Log4JFilter.java new file mode 100644 index 0000000..cd55a0e --- /dev/null +++ b/src/main/java/fr/xephi/authme/Log4JFilter.java @@ -0,0 +1,100 @@ +package fr.xephi.authme; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.message.Message; + +/** + * + * @author Xephi59 + */ +public class Log4JFilter implements org.apache.logging.log4j.core.Filter { + + public Log4JFilter() { + } + + @Override + public Result filter(LogEvent record) { + try { + if (record == null || record.getMessage() == null) + return Result.NEUTRAL; + String logM = record.getMessage().getFormattedMessage().toLowerCase(); + if (!logM.contains("issued server command:")) + return Result.NEUTRAL; + if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") + && !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") + && !logM.contains("/register ")) + return Result.NEUTRAL; + return Result.DENY; + } catch (NullPointerException npe) { + return Result.NEUTRAL; + } + } + + @Override + public Result filter(Logger arg0, Level arg1, Marker arg2, Message message, Throwable arg4) { + try { + if (message == null) + return Result.NEUTRAL; + String logM = message.getFormattedMessage().toLowerCase(); + if (!logM.contains("issued server command:")) + return Result.NEUTRAL; + if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") + && !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") + && !logM.contains("/register ")) + return Result.NEUTRAL; + return Result.DENY; + } catch (NullPointerException npe) { + return Result.NEUTRAL; + } + } + + @Override + public Result filter(Logger arg0, Level arg1, Marker arg2, Object message, Throwable arg4) { + try { + if (message == null) + return Result.NEUTRAL; + String logM = message.toString().toLowerCase(); + if (!logM.contains("issued server command:")) + return Result.NEUTRAL; + if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") + && !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") + && !logM.contains("/register ")) + return Result.NEUTRAL; + return Result.DENY; + } catch (NullPointerException npe) { + return Result.NEUTRAL; + } + } + + @Override + public Result filter(Logger arg0, Level arg1, Marker arg2, String message, Object... arg4) { + try { + if (message == null) + return Result.NEUTRAL; + String logM = message.toLowerCase(); + if (!logM.contains("issued server command:")) + return Result.NEUTRAL; + if (!logM.contains("/login ") && !logM.contains("/l ") && !logM.contains("/reg ") && !logM.contains("/changepassword ") && !logM.contains("/unregister ") + && !logM.contains("/authme register ") && !logM.contains("/authme changepassword ") && !logM.contains("/authme reg ") && !logM.contains("/authme cp ") + && !logM.contains("/register ")) + return Result.NEUTRAL; + return Result.DENY; + } catch (NullPointerException npe) { + return Result.NEUTRAL; + } + } + + @Override + public Result getOnMatch() { + return Result.NEUTRAL; + } + + @Override + public Result getOnMismatch() { + return Result.NEUTRAL; + } + +} diff --git a/src/main/java/fr/xephi/authme/PerformBackup.java b/src/main/java/fr/xephi/authme/PerformBackup.java new file mode 100644 index 0000000..8d7af9c --- /dev/null +++ b/src/main/java/fr/xephi/authme/PerformBackup.java @@ -0,0 +1,148 @@ +package fr.xephi.authme; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; + +import fr.xephi.authme.settings.Settings; + +/** + * + * @author stefano + */ +public class PerformBackup { + + private final SimpleDateFormat aformat = new SimpleDateFormat("yyyy-MM-dd_HH-mm"); + private final String dateString = aformat.format(new Date()); + private final String dbName = Settings.getMySQLDatabase; + private final String dbPassword = Settings.getMySQLPassword; + private final String dbUserName = Settings.getMySQLUsername; + private AuthMe instance; + private final String path = AuthMe.getInstance().getDataFolder() + File.separator + "backups" + File.separator + "backup" + dateString; + private final String tblname = Settings.getMySQLTablename; + + public PerformBackup(final AuthMe instance) { + this.setInstance(instance); + } + + public boolean doBackup() { + + switch (Settings.getDataSource) { + case FILE: + return FileBackup("auths.db"); + case MYSQL: + return MySqlBackup(); + case SQLITEHIKARI: + case SQLITE: + return FileBackup(Settings.getMySQLDatabase + ".db"); + } + + return false; + } + + public AuthMe getInstance() { + return instance; + } + + public void setInstance(final AuthMe instance) { + this.instance = instance; + } + + /* + * Check if we are under Windows and correct location of mysqldump.exe + * otherwise return error. + */ + private boolean checkWindows(final String windowsPath) { + final String isWin = System.getProperty("os.name").toLowerCase(); + if (isWin.indexOf("win") >= 0) { + if (new File(windowsPath + "\\bin\\mysqldump.exe").exists()) { + return true; + } else { + ConsoleLogger.showError("Mysql Windows Path is incorrect please check it"); + return true; + } + } else { + return false; + } + } + + private boolean FileBackup(final String backend) { + final File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups"); + + if (!dirBackup.exists()) { + dirBackup.mkdir(); + } + + try { + copy(new File("plugins" + File.separator + "AuthMe" + File.separator + backend), new File(path + ".db")); + return true; + + } catch (final Exception ex) { + ex.printStackTrace(); + } + return false; + } + + private boolean MySqlBackup() { + final File dirBackup = new File(AuthMe.getInstance().getDataFolder() + "/backups"); + + if (!dirBackup.exists()) { + dirBackup.mkdir(); + } + if (checkWindows(Settings.backupWindowsPath)) { + final String executeCmd = Settings.backupWindowsPath + "\\bin\\mysqldump.exe -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql"; + Process runtimeProcess; + try { + runtimeProcess = Runtime.getRuntime().exec(executeCmd); + final int processComplete = runtimeProcess.waitFor(); + if (processComplete == 0) { + ConsoleLogger.info("Backup created successfully."); + return true; + } else { + ConsoleLogger.showError("Could not create the backup!"); + } + } catch (final Exception ex) { + ex.printStackTrace(); + } + } else { + final String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " " + dbName + " --tables " + tblname + " -r " + path + ".sql"; + Process runtimeProcess; + try { + runtimeProcess = Runtime.getRuntime().exec(executeCmd); + final int processComplete = runtimeProcess.waitFor(); + if (processComplete == 0) { + ConsoleLogger.info("Backup created successfully."); + return true; + } else { + ConsoleLogger.showError("Could not create the backup!"); + } + } catch (final Exception ex) { + ex.printStackTrace(); + } + } + return false; + } + + /* + * Copyr src bytefile into dst file + */ + void copy(final File src, final File dst) throws IOException { + final InputStream in = new FileInputStream(src); + final OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + final byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); + } + +} diff --git a/src/main/java/fr/xephi/authme/Utils.java b/src/main/java/fr/xephi/authme/Utils.java new file mode 100644 index 0000000..4c270c6 --- /dev/null +++ b/src/main/java/fr/xephi/authme/Utils.java @@ -0,0 +1,295 @@ +package fr.xephi.authme; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.zip.GZIPInputStream; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import com.maxmind.geoip.LookupService; + +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.events.AuthMeTeleportEvent; +import fr.xephi.authme.settings.Settings; + +public class Utils { + + public static AuthMe plugin; + + private static Method getOnlinePlayers; + private static boolean getOnlinePlayersIsCollection; + private static LookupService lookupService; + + static { + plugin = AuthMe.getInstance(); + checkGeoIP(); + try { + final Method m = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); + getOnlinePlayersIsCollection = m.getReturnType() == Collection.class; + } catch (final Exception ignored) { + } + } + + public static boolean addNormal(final Player player, final String group) { + if (!useGroupSystem()) { + return false; + } + if (plugin.permission == null) { + return false; + } + try { + if (plugin.permission.playerRemoveGroup(player, Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(player, group)) { + return true; + } + } catch (final UnsupportedOperationException e) { + ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!"); + plugin.permission = null; + return false; + } + return false; + } + + // TODO: Move to a Manager + public static boolean checkAuth(final Player player) { + if (player == null || Utils.isUnrestricted(player)) { + return true; + } + + final String name = player.getName().toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(name)) { + return true; + } + + if (!Settings.isForcedRegistrationEnabled) { + if (!plugin.database.isAuthAvailable(name)) { + return true; + } + } + + return false; + } + + // Check and Download GeoIP data if not exist + public static boolean checkGeoIP() { + if (lookupService != null) { + return true; + } + ConsoleLogger.info("[LICENSE] IP数据来自 CityCraft 的 Yum 源 原始数据来自 http://www.maxmind.com"); + final File file = new File(Settings.APLUGIN_FOLDER, "GeoIP.dat"); + try { + if (file.exists()) { + if (lookupService == null) { + lookupService = new LookupService(file); + return true; + } + } + final String url = "http://citycraft.cn/downloads/authme/GeoIP.dat.gz"; + final URL downloadUrl = new URL(url); + final URLConnection conn = downloadUrl.openConnection(); + conn.setConnectTimeout(10000); + conn.connect(); + InputStream input = conn.getInputStream(); + if (conn.getURL().toString().endsWith(".gz")) { + input = new GZIPInputStream(input); + } + final OutputStream output = new FileOutputStream(file); + final byte[] buffer = new byte[2048]; + int length = input.read(buffer); + while (length >= 0) { + output.write(buffer, 0, length); + length = input.read(buffer); + } + output.close(); + input.close(); + } catch (final Exception e) { + ConsoleLogger.writeStackTrace(e); + return false; + } + return checkGeoIP(); + } + + /* + * Used for force player GameMode + */ + public static void forceGM(final Player player) { + if (!plugin.authmePermissible(player, "authme.bypassforcesurvival")) { + player.setGameMode(GameMode.SURVIVAL); + } + } + + public static String getCountryCode(final String ip) { + if (checkGeoIP()) { + return lookupService.getCountry(ip).getCode(); + } + return "--"; + } + + public static String getCountryName(final String ip) { + if (checkGeoIP()) { + return lookupService.getCountry(ip).getName(); + } + return "N/A"; + } + + @SuppressWarnings("unchecked") + public static Collection getOnlinePlayers() { + if (getOnlinePlayersIsCollection) { + return Bukkit.getOnlinePlayers(); + } + try { + if (getOnlinePlayers == null) { + getOnlinePlayers = Bukkit.class.getMethod("getOnlinePlayers"); + } + final Object obj = getOnlinePlayers.invoke(null); + if (obj instanceof Collection) { + return (Collection) obj; + } + return Arrays.asList((Player[]) obj); + } catch (final Exception ignored) { + } + return Collections.emptyList(); + } + + // TODO: remove if not needed + public static void hasPermOnJoin(final Player player) { + if (plugin.permission == null) { + return; + } + for (final String permission : Settings.getJoinPermissions) { + if (plugin.permission.playerHas(player, permission)) { + plugin.permission.playerAddTransient(player, permission); + } + } + } + + public static boolean isNPC(final Entity player) { + return player.hasMetadata("NPC"); + } + + public static boolean isUnrestricted(final Player player) { + return Settings.isAllowRestrictedIp && !Settings.getUnrestrictedName.isEmpty() && (Settings.getUnrestrictedName.contains(player.getName())); + } + + public static void packCoords(final double x, final double y, final double z, final String w, final Player pl) { + World theWorld; + if (w.equals("unavailableworld")) { + theWorld = pl.getWorld(); + } else { + theWorld = Bukkit.getWorld(w); + } + if (theWorld == null) { + theWorld = pl.getWorld(); + } + final World world = theWorld; + final Location locat = new Location(world, x, y, z); + + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + final AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getChunk().isLoaded()) { + tpEvent.getTo().getChunk().load(); + } + pl.teleport(tpEvent.getTo()); + } + } + }); + } + + public static void purgeDirectory(final File file) { + if (!file.isDirectory()) { + return; + } + final File[] files = file.listFiles(); + if (files == null) { + return; + } + for (final File target : files) { + if (target.isDirectory()) { + purgeDirectory(target); + target.delete(); + } else { + target.delete(); + } + } + } + + public static void setGroup(final Player player, final GroupType group) { + if (!Settings.isPermissionCheckEnabled) { + return; + } + if (plugin.permission == null) { + return; + } + String currentGroup; + try { + currentGroup = plugin.permission.getPrimaryGroup(player); + } catch (final UnsupportedOperationException e) { + ConsoleLogger.showError("Your permission plugin (" + plugin.permission.getName() + ") doesn't support the Group system... unhook!"); + plugin.permission = null; + return; + } + switch (group) { + case UNREGISTERED: { + plugin.permission.playerRemoveGroup(player, currentGroup); + plugin.permission.playerAddGroup(player, Settings.unRegisteredGroup); + break; + } + case REGISTERED: { + plugin.permission.playerRemoveGroup(player, currentGroup); + plugin.permission.playerAddGroup(player, Settings.getRegisteredGroup); + break; + } + case NOTLOGGEDIN: { + if (!useGroupSystem()) { + break; + } + plugin.permission.playerRemoveGroup(player, currentGroup); + plugin.permission.playerAddGroup(player, Settings.getUnloggedinGroup); + break; + } + case LOGGEDIN: { + if (!useGroupSystem()) { + break; + } + final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); + if (limbo == null) { + break; + } + final String realGroup = limbo.getGroup(); + plugin.permission.playerRemoveGroup(player, currentGroup); + plugin.permission.playerAddGroup(player, realGroup); + break; + } + } + } + + private static boolean useGroupSystem() { + return Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty(); + } + + public enum GroupType { + LOGGEDIN, + NOTLOGGEDIN, + REGISTERED, + UNREGISTERED + } +} diff --git a/src/main/java/fr/xephi/authme/api/API.java b/src/main/java/fr/xephi/authme/api/API.java new file mode 100644 index 0000000..694dd73 --- /dev/null +++ b/src/main/java/fr/xephi/authme/api/API.java @@ -0,0 +1,183 @@ +package fr.xephi.authme.api; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Settings; + +public class API { + + public static AuthMe instance; + public static final String newline = System.getProperty("line.separator"); + + @Deprecated + public API(final AuthMe instance) { + API.instance = instance; + } + + /** + * @param String + * playerName, String passwordToCheck + * @return true if the password is correct , false else + */ + @Deprecated + public static boolean checkPassword(final String playerName, final String passwordToCheck) { + if (!isRegistered(playerName)) { + return false; + } + final String player = playerName.toLowerCase(); + final PlayerAuth auth = instance.database.getAuth(player); + try { + return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); + } catch (final NoSuchAlgorithmException e) { + return false; + } + } + + /** + * Force a player to login + * + * @param Player + * player + */ + @Deprecated + public static void forceLogin(final Player player) { + instance.management.performLogin(player, "dontneed", true); + } + + @Deprecated + public static Location getLastLocation(final Player player) { + try { + final PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); + + if (auth != null) { + final Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); + return loc; + } else { + return null; + } + + } catch (final NullPointerException ex) { + return null; + } + } + + /** + * Hook into AuthMe + * + * @return AuthMe instance + */ + @Deprecated + public static AuthMe hookAuthMe() { + if (instance != null) { + return instance; + } + final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); + if (plugin == null || !(plugin instanceof AuthMe)) { + return null; + } + instance = (AuthMe) plugin; + return instance; + } + + /** + * + * @param player + * @return true if player is authenticate + */ + @Deprecated + public static boolean isAuthenticated(final Player player) { + return PlayerCache.getInstance().isAuthenticated(player.getName()); + } + + /** + * + * @param playerName + * @return true if player is registered + */ + @Deprecated + public static boolean isRegistered(final String playerName) { + final String player = playerName.toLowerCase(); + return instance.database.isAuthAvailable(player); + } + + /** + * + * @param player + * @return true if the player is unrestricted + */ + @Deprecated + public static boolean isUnrestricted(final Player player) { + return Utils.isUnrestricted(player); + } + + /** + * Register a player + * + * @param String + * playerName, String password + * @return true if the player is register correctly + */ + @Deprecated + public static boolean registerPlayer(final String playerName, final String password) { + try { + final String name = playerName.toLowerCase(); + final String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); + if (isRegistered(name)) { + return false; + } + final PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", playerName); + if (!instance.database.saveAuth(auth)) { + return false; + } + return true; + } catch (final NoSuchAlgorithmException ex) { + return false; + } + } + + @Deprecated + public static void setPlayerInventory(final Player player, final ItemStack[] content, final ItemStack[] armor) { + try { + player.getInventory().setContents(content); + player.getInventory().setArmorContents(armor); + } catch (final NullPointerException npe) { + } + } + + @Deprecated + public AuthMe getPlugin() { + return instance; + } + + /** + * + * @param player + * @return true if player is a npc + */ + @Deprecated + public boolean isaNPC(final Player player) { + return Utils.isNPC(player); + } + + /** + * + * @param player + * @return true if player is a npc + */ + @Deprecated + public boolean isNPC(final Player player) { + return Utils.isNPC(player); + } + +} diff --git a/src/main/java/fr/xephi/authme/api/NewAPI.java b/src/main/java/fr/xephi/authme/api/NewAPI.java new file mode 100644 index 0000000..cfa405e --- /dev/null +++ b/src/main/java/fr/xephi/authme/api/NewAPI.java @@ -0,0 +1,155 @@ +package fr.xephi.authme.api; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Settings; + +public class NewAPI { + + public static final String newline = System.getProperty("line.separator"); + public static NewAPI singleton; + public AuthMe plugin; + + public NewAPI(final AuthMe plugin) { + this.plugin = plugin; + } + + public NewAPI(final Server serv) { + this.plugin = (AuthMe) serv.getPluginManager().getPlugin("AuthMe"); + } + + /** + * Hook into AuthMe + * + * @return AuthMe plugin + */ + public static NewAPI getInstance() { + if (singleton != null) { + return singleton; + } + final Plugin p = Bukkit.getServer().getPluginManager().getPlugin("AuthMe"); + if (p == null || !(p instanceof AuthMe)) { + return null; + } + final AuthMe authme = (AuthMe) p; + singleton = (new NewAPI(authme)); + return singleton; + } + + /** + * @param String + * playerName, String passwordToCheck + * @return true if the password is correct , false else + */ + public boolean checkPassword(final String playerName, final String passwordToCheck) { + if (!isRegistered(playerName)) { + return false; + } + final String player = playerName.toLowerCase(); + final PlayerAuth auth = plugin.database.getAuth(player); + try { + return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName); + } catch (final NoSuchAlgorithmException e) { + return false; + } + } + + /** + * Force a player to login + * + * @param Player + * player + */ + public void forceLogin(final Player player) { + plugin.management.performLogin(player, "dontneed", true); + } + + public Location getLastLocation(final Player player) { + try { + final PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase()); + + if (auth != null) { + return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ()); + } else { + return null; + } + + } catch (final NullPointerException ex) { + return null; + } + } + + public AuthMe getPlugin() { + return plugin; + } + + /** + * + * @param player + * @return true if player is authenticate + */ + public boolean isAuthenticated(final Player player) { + return PlayerCache.getInstance().isAuthenticated(player.getName()); + } + + /** + * + * @param player + * @return true if player is a npc + */ + public boolean isNPC(final Player player) { + return Utils.isNPC(player); + } + + /** + * + * @param playerName + * @return true if player is registered + */ + public boolean isRegistered(final String playerName) { + final String player = playerName.toLowerCase(); + return plugin.database.isAuthAvailable(player); + } + + /** + * + * @param player + * @return true if the player is unrestricted + */ + public boolean isUnrestricted(final Player player) { + return Utils.isUnrestricted(player); + } + + /** + * Register a player + * + * @param String + * playerName, String password + * @return true if the player is register correctly + */ + public boolean registerPlayer(final String playerName, final String password) { + try { + final String name = playerName.toLowerCase(); + final String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); + if (isRegistered(name)) { + return false; + } + final PlayerAuth auth = new PlayerAuth(name, hash, "127.0.0.1", 0, "mc@mc.com", playerName); + return plugin.database.saveAuth(auth); + } catch (final NoSuchAlgorithmException ex) { + return false; + } + } + +} diff --git a/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java b/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java new file mode 100644 index 0000000..18a4e9a --- /dev/null +++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerAuth.java @@ -0,0 +1,263 @@ +package fr.xephi.authme.cache.auth; + +import fr.xephi.authme.security.HashAlgorithm; +import fr.xephi.authme.settings.Settings; + +public class PlayerAuth { + + private String email = "your@email.com"; + private int groupId = -1; + private String hash = ""; + private String ip = "192.168.0.1"; + private long lastLogin = 0; + private String nickname = ""; + private String realName; + private String salt = ""; + private String vBhash = null; + private String world = "world"; + private double x = 0; + private double y = 0; + private double z = 0; + + public PlayerAuth(String nickname, double x, double y, double z, String world, String realName) { + this.nickname = nickname; + this.x = x; + this.y = y; + this.z = z; + this.world = world; + this.realName = realName; + this.lastLogin = System.currentTimeMillis(); + + } + + public PlayerAuth(String nickname, String ip, long lastLogin, String realName) { + this.nickname = nickname; + this.ip = ip; + this.lastLogin = lastLogin; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.world = world; + this.salt = salt; + this.groupId = groupId; + this.email = email; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String salt, int groupId, String ip, long lastLogin, String realName) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.salt = salt; + this.groupId = groupId; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.world = world; + this.email = email; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String realName) { + this.nickname = nickname; + this.ip = ip; + this.lastLogin = lastLogin; + this.hash = hash; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String ip, long lastLogin, String email, String realName) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.email = email; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, double x, double y, double z, String world, String email, String realName) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.x = x; + this.y = y; + this.z = z; + this.world = world; + this.salt = salt; + this.email = email; + this.realName = realName; + } + + public PlayerAuth(String nickname, String hash, String salt, String ip, long lastLogin, String realName) { + this.nickname = nickname; + this.hash = hash; + this.ip = ip; + this.lastLogin = lastLogin; + this.salt = salt; + this.realName = realName; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof PlayerAuth)) { + return false; + } + PlayerAuth other = (PlayerAuth) obj; + return other.getIp().equals(this.ip) && other.getNickname().equals(this.nickname); + } + + public String getEmail() { + return email; + } + + public int getGroupId() { + return groupId; + } + + public String getHash() { + if (Settings.getPasswordHash == HashAlgorithm.MD5VB) { + if (salt != null && !salt.isEmpty() && Settings.getPasswordHash == HashAlgorithm.MD5VB) { + vBhash = "$MD5vb$" + salt + "$" + hash; + return vBhash; + } + } + return hash; + } + + public String getIp() { + if (ip == null || ip.isEmpty()) + ip = "127.0.0.1"; + return ip; + } + + public long getLastLogin() { + try { + if (Long.valueOf(lastLogin) == null) + lastLogin = 0L; + } catch (NullPointerException e) { + lastLogin = 0L; + } + return lastLogin; + } + + public String getNickname() { + return nickname; + } + + public double getQuitLocX() { + return x; + } + + public double getQuitLocY() { + return y; + } + + public double getQuitLocZ() { + return z; + } + + public String getRealName() { + return realName; + } + + public String getSalt() { + return this.salt; + } + + public String getWorld() { + return world; + } + + @Override + public int hashCode() { + int hashCode = 7; + hashCode = 71 * hashCode + (this.nickname != null ? this.nickname.hashCode() : 0); + hashCode = 71 * hashCode + (this.ip != null ? this.ip.hashCode() : 0); + return hashCode; + } + + public void set(PlayerAuth auth) { + this.setEmail(auth.getEmail()); + this.setHash(auth.getHash()); + this.setIp(auth.getIp()); + this.setLastLogin(auth.getLastLogin()); + this.setName(auth.getNickname()); + this.setQuitLocX(auth.getQuitLocX()); + this.setQuitLocY(auth.getQuitLocY()); + this.setQuitLocZ(auth.getQuitLocZ()); + this.setSalt(auth.getSalt()); + this.setWorld(auth.getWorld()); + this.setRealName(auth.getRealName()); + } + + public void setEmail(String email) { + this.email = email; + } + + public void setHash(String hash) { + this.hash = hash; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public void setLastLogin(long lastLogin) { + this.lastLogin = lastLogin; + } + + public void setName(String nickname) { + this.nickname = nickname; + } + + public void setQuitLocX(double d) { + this.x = d; + } + + public void setQuitLocY(double d) { + this.y = d; + } + + public void setQuitLocZ(double d) { + this.z = d; + } + + public void setRealName(String realName) { + this.realName = realName; + } + + public void setSalt(String salt) { + this.salt = salt; + } + + public void setWorld(String world) { + this.world = world; + } + + @Override + public String toString() { + String s = "Player : " + nickname + " | " + realName + " ! IP : " + ip + " ! LastLogin : " + lastLogin + " ! LastPosition : " + x + "," + y + "," + z + "," + world + " ! Email : " + email + + " ! Hash : " + hash + " ! Salt : " + salt; + return s; + + } + +} diff --git a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java new file mode 100644 index 0000000..af3c01c --- /dev/null +++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java @@ -0,0 +1,50 @@ +package fr.xephi.authme.cache.auth; + +import java.util.concurrent.ConcurrentHashMap; + +public class PlayerCache { + + private volatile static PlayerCache singleton = null; + private ConcurrentHashMap cache; + + private PlayerCache() { + cache = new ConcurrentHashMap<>(); + } + + public static PlayerCache getInstance() { + if (singleton == null) { + singleton = new PlayerCache(); + } + return singleton; + } + + public void addPlayer(PlayerAuth auth) { + cache.put(auth.getNickname().toLowerCase(), auth); + } + + public PlayerAuth getAuth(String user) { + return cache.get(user.toLowerCase()); + } + + public ConcurrentHashMap getCache() { + return this.cache; + } + + public int getLogged() { + return cache.size(); + } + + public boolean isAuthenticated(String user) { + return cache.containsKey(user.toLowerCase()); + } + + public void removePlayer(String user) { + cache.remove(user.toLowerCase()); + } + + public void updatePlayer(PlayerAuth auth) { + cache.remove(auth.getNickname().toLowerCase()); + cache.put(auth.getNickname().toLowerCase(), auth); + } + +} diff --git a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java new file mode 100644 index 0000000..ba11a3a --- /dev/null +++ b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java @@ -0,0 +1,26 @@ +package fr.xephi.authme.cache.backup; + +public class DataFileCache { + + private boolean flying; + private String group; + private boolean operator; + + public DataFileCache(String group, boolean operator, boolean flying) { + this.group = group; + this.operator = operator; + this.flying = flying; + } + + public String getGroup() { + return group; + } + + public boolean getOperator() { + return operator; + } + + public boolean isFlying() { + return flying; + } +} diff --git a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java new file mode 100644 index 0000000..be49155 --- /dev/null +++ b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java @@ -0,0 +1,158 @@ +package fr.xephi.authme.cache.backup; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Type; + +import org.bukkit.entity.Player; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.settings.Settings; + +public class JsonCache { + + private final File cacheDir; + private final Gson gson; + + public JsonCache() { + cacheDir = Settings.CACHE_FOLDER; + if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) { + ConsoleLogger.showError("Failed to create cache directory."); + } + gson = new GsonBuilder() + .registerTypeAdapter(DataFileCache.class, new PlayerDataSerializer()) + .registerTypeAdapter(DataFileCache.class, new PlayerDataDeserializer()) + .setPrettyPrinting() + .create(); + } + + public void createCache(Player player, DataFileCache playerData) { + if (player == null) { + return; + } + + String path; + try { + path = player.getUniqueId().toString(); + } catch (Exception | Error e) { + path = player.getName().toLowerCase(); + } + + File file = new File(cacheDir, path + File.separator + "cache.json"); + if (file.exists()) { + return; + } + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { + return; + } + + try { + String data = gson.toJson(playerData); + Files.touch(file); + Files.write(data, file, Charsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public boolean doesCacheExist(Player player) { + String path; + try { + path = player.getUniqueId().toString(); + } catch (Exception | Error e) { + path = player.getName().toLowerCase(); + } + File file = new File(cacheDir, path + File.separator + "cache.json"); + return file.exists(); + } + + public DataFileCache readCache(Player player) { + String path; + try { + path = player.getUniqueId().toString(); + } catch (Exception | Error e) { + path = player.getName().toLowerCase(); + } + + File file = new File(cacheDir, path + File.separator + "cache.json"); + if (!file.exists()) { + return null; + } + + try { + String str = Files.toString(file, Charsets.UTF_8); + return gson.fromJson(str, DataFileCache.class); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public void removeCache(Player player) { + String path; + try { + path = player.getUniqueId().toString(); + } catch (Exception | Error e) { + path = player.getName().toLowerCase(); + } + File file = new File(cacheDir, path); + if (file.exists()) { + Utils.purgeDirectory(file); + if (!file.delete()) { + ConsoleLogger.showError("Failed to remove" + player.getName() + "cache."); + } + } + } + + private static class PlayerDataDeserializer implements JsonDeserializer { + @Override + public DataFileCache deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject == null) { + return null; + } + JsonElement e; + String group = null; + boolean operator = false; + boolean flying = false; + + if ((e = jsonObject.get("group")) != null) { + group = e.getAsString(); + } + if ((e = jsonObject.get("operator")) != null) { + operator = e.getAsBoolean(); + } + if ((e = jsonObject.get("flying")) != null) { + flying = e.getAsBoolean(); + } + + return new DataFileCache(group, operator, flying); + } + } + + private class PlayerDataSerializer implements JsonSerializer { + @Override + public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("group", dataFileCache.getGroup()); + jsonObject.addProperty("operator", dataFileCache.getOperator()); + jsonObject.addProperty("flying", dataFileCache.isFlying()); + + return jsonObject; + } + } + +} diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java new file mode 100644 index 0000000..642daa5 --- /dev/null +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java @@ -0,0 +1,123 @@ +package fr.xephi.authme.cache.limbo; + +import java.util.concurrent.ConcurrentHashMap; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.backup.DataFileCache; +import fr.xephi.authme.cache.backup.JsonCache; +import fr.xephi.authme.events.ResetInventoryEvent; +import fr.xephi.authme.events.StoreInventoryEvent; +import fr.xephi.authme.settings.Settings; + +public class LimboCache { + + private volatile static LimboCache singleton; + public ConcurrentHashMap cache; + public AuthMe plugin; + private JsonCache playerData; + + private LimboCache(AuthMe plugin) { + this.plugin = plugin; + this.cache = new ConcurrentHashMap<>(); + this.playerData = new JsonCache(); + } + + public static LimboCache getInstance() { + if (singleton == null) { + singleton = new LimboCache(AuthMe.getInstance()); + } + return singleton; + } + + public void addLimboPlayer(Player player) { + String name = player.getName().toLowerCase(); + Location loc = player.getLocation(); + GameMode gameMode = player.getGameMode(); + boolean operator = false; + String playerGroup = ""; + boolean flying = false; + + if (playerData.doesCacheExist(player)) { + final StoreInventoryEvent event = new StoreInventoryEvent(player, playerData); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) { + player.getInventory().setContents(event.getInventory()); + player.getInventory().setArmorContents(event.getArmor()); + } + + DataFileCache cache = playerData.readCache(player); + if (cache != null) { + playerGroup = cache.getGroup(); + operator = cache.getOperator(); + flying = cache.isFlying(); + } + } else { + StoreInventoryEvent event = new StoreInventoryEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) { + player.getInventory().setContents(event.getInventory()); + player.getInventory().setArmorContents(event.getArmor()); + } + + operator = player.isOp(); + flying = player.isFlying(); + if (plugin.permission != null) { + try { + playerGroup = plugin.permission.getPrimaryGroup(player); + } catch (UnsupportedOperationException e) { + ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!"); + plugin.permission = null; + } + } + } + + if (Settings.isForceSurvivalModeEnabled) { + if (Settings.isResetInventoryIfCreative && gameMode == GameMode.CREATIVE) { + ResetInventoryEvent event = new ResetInventoryEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + player.getInventory().clear(); + player.sendMessage("Your inventory has been cleaned!"); + } + } + if (gameMode == GameMode.CREATIVE) { + flying = false; + } + gameMode = GameMode.SURVIVAL; + } + if (player.isDead()) { + loc = plugin.getSpawnLocation(player); + } + cache.put(name, new LimboPlayer(name, loc, gameMode, operator, playerGroup, flying)); + } + + public void addLimboPlayer(Player player, String group) { + cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group)); + } + + public void deleteLimboPlayer(String name) { + cache.remove(name); + } + + public LimboPlayer getLimboPlayer(String name) { + return cache.get(name); + } + + public boolean hasLimboPlayer(String name) { + return cache.containsKey(name); + } + + public void updateLimboPlayer(Player player) { + if (this.hasLimboPlayer(player.getName().toLowerCase())) { + this.deleteLimboPlayer(player.getName().toLowerCase()); + } + addLimboPlayer(player); + } + +} diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java new file mode 100644 index 0000000..86c7ab3 --- /dev/null +++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java @@ -0,0 +1,75 @@ +package fr.xephi.authme.cache.limbo; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.scheduler.BukkitTask; + +public class LimboPlayer { + + private boolean flying = false; + private GameMode gameMode = GameMode.SURVIVAL; + private String group = ""; + private Location loc = null; + private BukkitTask messageTaskId = null; + private String name; + private boolean operator = false; + private BukkitTask timeoutTaskId = null; + + public LimboPlayer(String name, Location loc, GameMode gameMode, boolean operator, String group, boolean flying) { + this.name = name; + this.loc = loc; + this.gameMode = gameMode; + this.operator = operator; + this.group = group; + this.flying = flying; + } + + public LimboPlayer(String name, String group) { + this.name = name; + this.group = group; + } + + public GameMode getGameMode() { + return gameMode; + } + + public String getGroup() { + return group; + } + + public Location getLoc() { + return loc; + } + + public BukkitTask getMessageTaskId() { + return messageTaskId; + } + + public String getName() { + return name; + } + + public boolean getOperator() { + return operator; + } + + public BukkitTask getTimeoutTaskId() { + return timeoutTaskId; + } + + public boolean isFlying() { + return flying; + } + + public void setMessageTaskId(BukkitTask messageTaskId) { + if (this.messageTaskId != null) + this.messageTaskId.cancel(); + this.messageTaskId = messageTaskId; + } + + public void setTimeoutTaskId(BukkitTask i) { + if (this.timeoutTaskId != null) + this.timeoutTaskId.cancel(); + this.timeoutTaskId = i; + } +} diff --git a/src/main/java/fr/xephi/authme/commands/AdminCommand.java b/src/main/java/fr/xephi/authme/commands/AdminCommand.java new file mode 100644 index 0000000..33ae770 --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/AdminCommand.java @@ -0,0 +1,613 @@ +package fr.xephi.authme.commands; + +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.events.SpawnTeleportEvent; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.Spawn; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; + +public class AdminCommand implements CommandExecutor { + + public AuthMe plugin; + private final Messages m = Messages.getInstance(); + + public AdminCommand(final AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(final CommandSender sender, final Command cmnd, final String label, final String[] args) { + if (args.length == 0) { + sender.sendMessage("Usage:"); + sender.sendMessage("/authme reload - Reload the config"); + sender.sendMessage("/authme version - Get AuthMe version info"); + sender.sendMessage("/authme register - Register a player"); + sender.sendMessage("/authme unregister - Unregister a player"); + sender.sendMessage("/authme changepassword - Change a player's password"); + sender.sendMessage("/authme chgemail - Change a player's email"); + sender.sendMessage("/authme getemail - Get a player's email"); + sender.sendMessage("/authme getip - Display a player's IP if he's online"); + sender.sendMessage("/authme lastlogin - Display the date of a player's last login"); + sender.sendMessage("/authme accounts - Display all player's accounts"); + sender.sendMessage("/authme purge - Purge database"); + sender.sendMessage("/authme purgebannedplayers - Purge database from banned players"); + sender.sendMessage("/authme purgelastpos - Purge last position infos for a player"); + sender.sendMessage("/authme setspawn - Set player's spawn to your current position"); + sender.sendMessage("/authme setfirstspawn - Set player's first spawn to your current position"); + sender.sendMessage("/authme spawn - Teleport yourself to the spawn point"); + sender.sendMessage("/authme firstspawn - Teleport yourself to the first spawn point"); + sender.sendMessage("/authme switchantibot on/off - Enable/Disable AntiBot feature"); + sender.sendMessage("/authme forcelogin - Enforce the login of a connected player"); + return true; + } + + if (!plugin.authmePermissible(sender, "authme.admin." + args[0].toLowerCase())) { + m.send(sender, "no_perm"); + return true; + } + + if (args[0].equalsIgnoreCase("version")) { + sender.sendMessage("AuthMe Version: " + AuthMe.getInstance().getDescription().getVersion()); + return true; + } + + if (args[0].equalsIgnoreCase("purge")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme purge "); + return true; + } + if (Integer.parseInt(args[1]) < 30) { + sender.sendMessage("You can only purge data older than 30 days"); + return true; + } + try { + final Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DATE, -(Integer.parseInt(args[1]))); + final long until = calendar.getTimeInMillis(); + final List purged = plugin.database.autoPurgeDatabase(until); + sender.sendMessage("Deleted " + purged.size() + " user accounts"); + if (Settings.purgeEssentialsFile && plugin.ess != null) { + plugin.dataManager.purgeEssentials(purged); + } + if (Settings.purgePlayerDat) { + plugin.dataManager.purgeDat(purged); + } + if (Settings.purgeLimitedCreative) { + plugin.dataManager.purgeLimitedCreative(purged); + } + if (Settings.purgeAntiXray) { + plugin.dataManager.purgeAntiXray(purged); + } + sender.sendMessage("[AuthMe] Database has been purged correctly"); + return true; + } catch (final NumberFormatException e) { + sender.sendMessage("Usage: /authme purge "); + return true; + } + } else if (args[0].equalsIgnoreCase("reload")) { + try { + Settings.reload(); + plugin.getModuleManager().reloadModules(); + m.reloadMessages(); + plugin.setupDatabase(); + } catch (final Exception e) { + ConsoleLogger.showError("Fatal error occurred! Authme instance ABORTED!"); + ConsoleLogger.writeStackTrace(e); + plugin.stopOrUnload(); + return false; + } + m.send(sender, "reload"); + } else if (args[0].equalsIgnoreCase("lastlogin")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme lastlogin "); + return true; + } + PlayerAuth auth; + try { + auth = plugin.database.getAuth(args[1].toLowerCase()); + } catch (final NullPointerException e) { + m.send(sender, "unknown_user"); + return true; + } + if (auth == null) { + m.send(sender, "user_unknown"); + return true; + } + final long lastLogin = auth.getLastLogin(); + final Date d = new Date(lastLogin); + final long diff = System.currentTimeMillis() - lastLogin; + final String msg = (int) (diff / 86400000) + " days " + (int) (diff / 3600000 % 24) + " hours " + (int) (diff / 60000 % 60) + " mins " + (int) (diff / 1000 % 60) + " secs."; + final String lastIP = auth.getIp(); + sender.sendMessage("[AuthMe] " + args[1] + " lastlogin : " + d.toString()); + sender.sendMessage("[AuthMe] The player " + auth.getNickname() + " is unlogged since " + msg); + sender.sendMessage("[AuthMe] Last Player's IP: " + lastIP); + } else if (args[0].equalsIgnoreCase("accounts")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme accounts "); + sender.sendMessage("Or: /authme accounts "); + return true; + } + if (!args[1].contains(".")) { + final String[] arguments = args; + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + PlayerAuth auth; + final StringBuilder message = new StringBuilder("[AuthMe] "); + try { + auth = plugin.database.getAuth(arguments[1].toLowerCase()); + } catch (final NullPointerException npe) { + m.send(sender, "unknown_user"); + return; + } + if (auth == null) { + m.send(sender, "unknown_user"); + return; + } + final List accountList = plugin.database.getAllAuthsByName(auth); + if (accountList == null || accountList.isEmpty()) { + m.send(sender, "user_unknown"); + return; + } + if (accountList.size() == 1) { + sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); + return; + } + int i = 0; + for (final String account : accountList) { + i++; + message.append(account); + if (i != accountList.size()) { + message.append(", "); + } else { + message.append("."); + } + } + sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); + sender.sendMessage(message.toString()); + } + }); + return true; + } else { + final String[] arguments = args; + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + @Override + public void run() { + final StringBuilder message = new StringBuilder("[AuthMe] "); + if (arguments[1] == null) { + sender.sendMessage("[AuthMe] Please put a valid IP"); + return; + } + final List accountList = plugin.database.getAllAuthsByIp(arguments[1]); + if (accountList == null || accountList.isEmpty()) { + sender.sendMessage("[AuthMe] This IP does not exist in the database"); + return; + } + if (accountList.size() == 1) { + sender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player"); + return; + } + int i = 0; + for (final String account : accountList) { + i++; + message.append(account); + if (i != accountList.size()) { + message.append(", "); + } else { + message.append("."); + } + } + sender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts"); + sender.sendMessage(message.toString()); + } + }); + return true; + } + } else if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) { + if (args.length != 3) { + sender.sendMessage("Usage: /authme register "); + return true; + } + final String name = args[1].toLowerCase(); + final String lowpass = args[2].toLowerCase(); + if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") + || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) { + m.send(sender, "password_error"); + return true; + } + if (lowpass.equalsIgnoreCase(args[1])) { + m.send(sender, "password_error_nick"); + return true; + } + if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) { + m.send(sender, "pass_len"); + return true; + } + if (!Settings.unsafePasswords.isEmpty()) { + if (Settings.unsafePasswords.contains(lowpass)) { + m.send(sender, "password_error_unsafe"); + return true; + } + } + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + try { + if (plugin.database.isAuthAvailable(name)) { + m.send(sender, "user_regged"); + return; + } + final String hash = PasswordSecurity.getHash(Settings.getPasswordHash, lowpass, name); + final PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com", name); + if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) { + auth.setSalt(PasswordSecurity.userSalt.get(name)); + } else { + auth.setSalt(""); + } + if (!plugin.database.saveAuth(auth)) { + m.send(sender, "error"); + return; + } + m.send(sender, "registered"); + ConsoleLogger.info(name + " registered"); + } catch (final NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + m.send(sender, "error"); + } + + } + }); + return true; + } else if (args[0].equalsIgnoreCase("getemail")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme getemail "); + return true; + } + final String playername = args[1].toLowerCase(); + final PlayerAuth auth = plugin.database.getAuth(playername); + if (auth == null) { + m.send(sender, "unknown_user"); + return true; + } + sender.sendMessage("[AuthMe] " + args[1] + "'s email: " + auth.getEmail()); + return true; + } else if (args[0].equalsIgnoreCase("chgemail")) { + if (args.length != 3) { + sender.sendMessage("Usage: /authme chgemail "); + return true; + } + if (!Settings.isEmailCorrect(args[2])) { + m.send(sender, "email_invalid"); + return true; + } + final String playername = args[1].toLowerCase(); + final PlayerAuth auth = plugin.database.getAuth(playername); + if (auth == null) { + m.send(sender, "unknown_user"); + return true; + } + auth.setEmail(args[2]); + if (!plugin.database.updateEmail(auth)) { + m.send(sender, "error"); + return true; + } + if (PlayerCache.getInstance().getAuth(playername) != null) { + PlayerCache.getInstance().updatePlayer(auth); + } + m.send(sender, "email_changed"); + return true; + } else if (args[0].equalsIgnoreCase("setspawn")) { + try { + if (sender instanceof Player) { + if (Spawn.getInstance().setSpawn(((Player) sender).getLocation())) { + sender.sendMessage("[AuthMe] Correctly defined new spawn point"); + } else { + sender.sendMessage("[AuthMe] SetSpawn has failed, please retry"); + } + } else { + sender.sendMessage("[AuthMe] Please use that command in game"); + } + } catch (final NullPointerException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + return true; + } else if (args[0].equalsIgnoreCase("setfirstspawn")) { + try { + if (sender instanceof Player) { + if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation())) { + sender.sendMessage("[AuthMe] Correctly defined new first spawn point"); + } else { + sender.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry"); + } + } else { + sender.sendMessage("[AuthMe] Please use that command in game"); + } + } catch (final NullPointerException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + return true; + } else if (args[0].equalsIgnoreCase("purgebannedplayers")) { + final List bannedPlayers = new ArrayList<>(); + for (final OfflinePlayer off : plugin.getServer().getBannedPlayers()) { + bannedPlayers.add(off.getName().toLowerCase()); + } + plugin.database.purgeBanned(bannedPlayers); + if (Settings.purgeEssentialsFile && plugin.ess != null) { + plugin.dataManager.purgeEssentials(bannedPlayers); + } + if (Settings.purgePlayerDat) { + plugin.dataManager.purgeDat(bannedPlayers); + } + if (Settings.purgeLimitedCreative) { + plugin.dataManager.purgeLimitedCreative(bannedPlayers); + } + if (Settings.purgeAntiXray) { + plugin.dataManager.purgeAntiXray(bannedPlayers); + } + sender.sendMessage("[AuthMe] Database has been purged correctly"); + return true; + } else if (args[0].equalsIgnoreCase("spawn")) { + try { + if (sender instanceof Player) { + if (Spawn.getInstance().getSpawn() != null) { + ((Player) sender).teleport(Spawn.getInstance().getSpawn()); + } else { + sender.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn"); + } + } else { + sender.sendMessage("[AuthMe] Please use that command in game"); + } + } catch (final NullPointerException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + return true; + } else if (args[0].equalsIgnoreCase("firstspawn")) { + try { + if (sender instanceof Player) { + if (Spawn.getInstance().getFirstSpawn() != null) { + ((Player) sender).teleport(Spawn.getInstance().getFirstSpawn()); + } else { + sender.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn"); + } + } else { + sender.sendMessage("[AuthMe] Please use that command in game"); + } + } catch (final NullPointerException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + return true; + } else if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) { + if (args.length != 3) { + sender.sendMessage("Usage: /authme changepassword "); + return true; + } + final String lowpass = args[2].toLowerCase(); + if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") + || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) { + m.send(sender, "password_error"); + return true; + } + if (lowpass.equalsIgnoreCase(args[1])) { + m.send(sender, "password_error_nick"); + return true; + } + if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) { + m.send(sender, "pass_len"); + return true; + } + if (!Settings.unsafePasswords.isEmpty()) { + if (Settings.unsafePasswords.contains(lowpass)) { + m.send(sender, "password_error_unsafe"); + return true; + } + } + final String name = args[1].toLowerCase(); + final String raw = args[2]; + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + String hash; + try { + hash = PasswordSecurity.getHash(Settings.getPasswordHash, raw, name); + } catch (final NoSuchAlgorithmException e) { + m.send(sender, "error"); + return; + } + PlayerAuth auth = null; + if (PlayerCache.getInstance().isAuthenticated(name)) { + auth = PlayerCache.getInstance().getAuth(name); + } else if (plugin.database.isAuthAvailable(name)) { + auth = plugin.database.getAuth(name); + } + if (auth == null) { + m.send(sender, "unknown_user"); + return; + } + auth.setHash(hash); + if (PasswordSecurity.userSalt.containsKey(name)) { + auth.setSalt(PasswordSecurity.userSalt.get(name)); + plugin.database.updateSalt(auth); + } + if (!plugin.database.updatePassword(auth)) { + m.send(sender, "error"); + return; + } + sender.sendMessage("pwd_changed"); + ConsoleLogger.info(name + "'s password changed"); + } + + }); + return true; + } else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme unregister "); + return true; + } + final String name = args[1].toLowerCase(); + if (!plugin.database.isAuthAvailable(name)) { + m.send(sender, "user_unknown"); + return true; + } + if (!plugin.database.removeAuth(name)) { + m.send(sender, "error"); + return true; + } + final Player target = Bukkit.getPlayer(name); + PlayerCache.getInstance().removePlayer(name); + Utils.setGroup(target, GroupType.UNREGISTERED); + if (target != null) { + if (target.isOnline()) { + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + final Location spawn = plugin.getSpawnLocation(target); + final SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + target.teleport(tpEvent.getTo()); + } + } + LimboCache.getInstance().addLimboPlayer(target); + final int delay = Settings.getRegistrationTimeout * 20; + final int interval = Settings.getWarnMessageInterval; + final BukkitScheduler sched = sender.getServer().getScheduler(); + if (delay != 0) { + final BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, target), delay); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + } + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval))); + if (Settings.applyBlindEffect) { + target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); + } + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + target.setWalkSpeed(0.0f); + target.setFlySpeed(0.0f); + } + m.send(target, "unregistered"); + } + } + m.send(sender, "unregistered"); + ConsoleLogger.info(args[1] + " unregistered"); + return true; + } else if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme purgelastpos "); + return true; + } + try { + final String name = args[1].toLowerCase(); + final PlayerAuth auth = plugin.database.getAuth(name); + if (auth == null) { + m.send(sender, "unknown_user"); + return true; + } + auth.setQuitLocX(0D); + auth.setQuitLocY(0D); + auth.setQuitLocZ(0D); + auth.setWorld("world"); + plugin.database.updateQuitLoc(auth); + sender.sendMessage(name + "'s last position location is now reset"); + } catch (final Exception e) { + ConsoleLogger.showError("An error occured while trying to reset location or player do not exist, please see below: "); + ConsoleLogger.showError(e.getMessage()); + if (sender instanceof Player) { + sender.sendMessage("An error occured while trying to reset location or player do not exist, please see logs"); + } + } + return true; + } else if (args[0].equalsIgnoreCase("switchantibot")) { + if (args.length != 2) { + sender.sendMessage("Usage: /authme switchantibot on/off"); + return true; + } + if (args[1].equalsIgnoreCase("on")) { + plugin.switchAntiBotMod(true); + sender.sendMessage("[AuthMe] AntiBotMod enabled"); + return true; + } + if (args[1].equalsIgnoreCase("off")) { + plugin.switchAntiBotMod(false); + sender.sendMessage("[AuthMe] AntiBotMod disabled"); + return true; + } + sender.sendMessage("Usage: /authme switchantibot on/off"); + return true; + } else if (args[0].equalsIgnoreCase("getip")) { + if (args.length < 2) { + sender.sendMessage("Usage: /authme getip "); + return true; + } + final Player player = Bukkit.getPlayer(args[1]); + if (player == null) { + sender.sendMessage("This player is not actually online"); + sender.sendMessage("Usage: /authme getip "); + return true; + } + sender.sendMessage(player.getName() + "'s actual IP is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort()); + sender.sendMessage(player.getName() + "'s real IP is : " + plugin.getIP(player)); + return true; + } else if (args[0].equalsIgnoreCase("forcelogin")) { + if (args.length < 2) { + sender.sendMessage("Usage: /authme forcelogin "); + return true; + } + try { + final Player player = Bukkit.getPlayer(args[1]); + if (player == null || !player.isOnline()) { + sender.sendMessage("Player needs to be online!"); + return true; + } + if (!plugin.authmePermissible(player, "authme.canbeforced")) { + sender.sendMessage("You cannot force login for this player!"); + return true; + } + plugin.management.performLogin(player, "dontneed", true); + sender.sendMessage("Force Login performed!"); + } catch (final Exception e) { + sender.sendMessage("An error occured while trying to get that player!"); + } + } else if (args[0].equalsIgnoreCase("resetname")) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + final List auths = plugin.database.getAllAuths(); + for (final PlayerAuth auth : auths) { + auth.setRealName("Player"); + plugin.database.updateSession(auth); + } + } + }); + } else { + sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername"); + } + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/commands/CaptchaCommand.java b/src/main/java/fr/xephi/authme/commands/CaptchaCommand.java new file mode 100644 index 0000000..422a6b2 --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/CaptchaCommand.java @@ -0,0 +1,77 @@ +package fr.xephi.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.security.RandomString; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class CaptchaCommand implements CommandExecutor { + + public static RandomString rdm = new RandomString(Settings.captchaLength); + public AuthMe plugin; + private Messages m = Messages.getInstance(); + + public CaptchaCommand(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + + if (!(sender instanceof Player)) { + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + + if (args.length == 0) { + m.send(player, "usage_captcha"); + return true; + } + + if (PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "logged_in"); + return true; + } + + if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) { + m.send(player, "no_perm"); + return true; + } + + if (!Settings.useCaptcha) { + m.send(player, "usage_log"); + return true; + } + + if (!plugin.cap.containsKey(name)) { + m.send(player, "usage_log"); + return true; + } + + if (Settings.useCaptcha && !args[0].equals(plugin.cap.get(name))) { + plugin.cap.remove(name); + plugin.cap.put(name, rdm.nextString()); + for (String s : m.send("wrong_captcha")) { + player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name))); + } + return true; + } + try { + plugin.captcha.remove(name); + plugin.cap.remove(name); + } catch (NullPointerException npe) { + } + m.send(player, "valid_captcha"); + m.send(player, "login_msg"); + return true; + } + +} diff --git a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java new file mode 100644 index 0000000..2db8485 --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java @@ -0,0 +1,69 @@ +package fr.xephi.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.task.ChangePasswordTask; + +public class ChangePasswordCommand implements CommandExecutor { + + public AuthMe plugin; + private Messages m = Messages.getInstance(); + + public ChangePasswordCommand(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) { + m.send(sender, "no_perm"); + return true; + } + + Player player = (Player) sender; + String name = player.getName().toLowerCase(); + if (!PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "not_logged_in"); + return true; + } + + if (args.length != 2) { + m.send(player, "usage_changepassword"); + return true; + } + + String lowpass = args[1].toLowerCase(); + if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") + || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) { + m.send(player, "password_error"); + return true; + } + if (lowpass.equalsIgnoreCase(name)) { + m.send(player, "password_error_nick"); + return true; + } + if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) { + m.send(player, "pass_len"); + return true; + } + if (!Settings.unsafePasswords.isEmpty()) { + if (Settings.unsafePasswords.contains(lowpass)) { + m.send(player, "password_error_unsafe"); + return true; + } + } + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, args[0], args[1])); + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/commands/ConverterCommand.java b/src/main/java/fr/xephi/authme/commands/ConverterCommand.java new file mode 100644 index 0000000..642da6c --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/ConverterCommand.java @@ -0,0 +1,110 @@ +package fr.xephi.authme.commands; + +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.converter.Converter; +import fr.xephi.authme.converter.CrazyLoginConverter; +import fr.xephi.authme.converter.FlatToSql; +import fr.xephi.authme.converter.FlatToSqlite; +import fr.xephi.authme.converter.RakamakConverter; +import fr.xephi.authme.converter.RoyalAuthConverter; +import fr.xephi.authme.converter.SqlToFlat; +import fr.xephi.authme.converter.vAuthConverter; +import fr.xephi.authme.settings.Messages; + +public class ConverterCommand implements CommandExecutor { + + private final Messages m = Messages.getInstance(); + private final AuthMe plugin; + + public ConverterCommand(final AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(final CommandSender sender, final Command cmnd, final String label, final String[] args) { + if (!plugin.authmePermissible(sender, "authme.admin.converter")) { + m.send(sender, "no_perm"); + return true; + } + + if (args.length == 0) { + sender.sendMessage("Usage : /converter flattosql | flattosqlite | xauth | crazylogin | rakamak | royalauth | vauth | sqltoflat"); + return true; + } + + final ConvertType type = ConvertType.fromName(args[0]); + if (type == null) { + m.send(sender, "error"); + return true; + } + Converter converter = null; + switch (type) { + case ftsql: + converter = new FlatToSql(); + break; + case ftsqlite: + converter = new FlatToSqlite(sender); + break; + case crazylogin: + converter = new CrazyLoginConverter(plugin, sender); + break; + case rakamak: + converter = new RakamakConverter(plugin, sender); + break; + case royalauth: + converter = new RoyalAuthConverter(plugin); + break; + case vauth: + converter = new vAuthConverter(plugin, sender); + break; + case sqltoflat: + converter = new SqlToFlat(plugin, sender); + break; + default: + break; + } + if (converter == null) { + m.send(sender, "error"); + return true; + } + Bukkit.getScheduler().runTaskAsynchronously(plugin, converter); + sender.sendMessage("[AuthMe] Successfully converted from " + args[0]); + return true; + } + + public enum ConvertType { + + crazylogin("crazylogin"), + ftsql("flattosql"), + ftsqlite("flattosqlite"), + rakamak("rakamak"), + royalauth("royalauth"), + sqltoflat("sqltoflat"), + vauth("vauth"), + xauth("xauth"); + + String name; + + ConvertType(final String name) { + this.name = name; + } + + public static ConvertType fromName(final String name) { + for (final ConvertType type : ConvertType.values()) { + if (type.getName().equalsIgnoreCase(name)) { + return type; + } + } + return null; + } + + String getName() { + return this.name; + } + } +} diff --git a/src/main/java/fr/xephi/authme/commands/LoginCommand.java b/src/main/java/fr/xephi/authme/commands/LoginCommand.java new file mode 100644 index 0000000..ff79e46 --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/LoginCommand.java @@ -0,0 +1,40 @@ +package fr.xephi.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.settings.Messages; + +public class LoginCommand implements CommandExecutor { + + private Messages m = Messages.getInstance(); + private AuthMe plugin; + + public LoginCommand(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, final String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + final Player player = (Player) sender; + + if (args.length == 0) { + m.send(player, "usage_log"); + return true; + } + + if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) { + m.send(player, "no_perm"); + return true; + } + plugin.management.performLogin(player, args[0], false); + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/commands/LogoutCommand.java b/src/main/java/fr/xephi/authme/commands/LogoutCommand.java new file mode 100644 index 0000000..5fc24ed --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/LogoutCommand.java @@ -0,0 +1,36 @@ +package fr.xephi.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.settings.Messages; + +public class LogoutCommand implements CommandExecutor { + + private Messages m = Messages.getInstance(); + private AuthMe plugin; + + public LogoutCommand(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) { + m.send(sender, "no_perm"); + return true; + } + + final Player player = (Player) sender; + plugin.management.performLogout(player); + return true; + } + +} diff --git a/src/main/java/fr/xephi/authme/commands/RegisterCommand.java b/src/main/java/fr/xephi/authme/commands/RegisterCommand.java new file mode 100644 index 0000000..62b2943 --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/RegisterCommand.java @@ -0,0 +1,64 @@ +package fr.xephi.authme.commands; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.security.RandomString; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class RegisterCommand implements CommandExecutor { + + public PlayerAuth auth; + public AuthMe plugin; + private Messages m = Messages.getInstance(); + + public RegisterCommand(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { + if (!(sender instanceof Player)) { + sender.sendMessage("Player Only! Use 'authme register ' instead"); + return true; + } + final Player player = (Player) sender; + if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) { + m.send(player, "usage_reg"); + return true; + } + if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) { + m.send(player, "no_perm"); + return true; + } + if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) { + if (Settings.doubleEmailCheck) { + if (args.length < 2 || !args[0].equals(args[1])) { + m.send(player, "usage_reg"); + return true; + } + } + final String email = args[0]; + if (!Settings.isEmailCorrect(email)) { + m.send(player, "email_invalid"); + return true; + } + RandomString rand = new RandomString(Settings.getRecoveryPassLength); + final String thePass = rand.nextString(); + plugin.management.performRegister(player, thePass, email); + return true; + } + if (args.length > 1 && Settings.getEnablePasswordVerifier) + if (!args[0].equals(args[1])) { + m.send(player, "password_error"); + return true; + } + plugin.management.performRegister(player, args[0], ""); + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java new file mode 100644 index 0000000..d0cb299 --- /dev/null +++ b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java @@ -0,0 +1,139 @@ +package fr.xephi.authme.commands; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.backup.JsonCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.events.SpawnTeleportEvent; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; + +public class UnregisterCommand implements CommandExecutor { + + public AuthMe plugin; + private Messages m = Messages.getInstance(); + private JsonCache playerCache; + + public UnregisterCommand(AuthMe plugin) { + this.plugin = plugin; + this.playerCache = new JsonCache(); + } + + @Override + public boolean onCommand(final CommandSender sender, Command cmnd, String label, final String[] args) { + if (!(sender instanceof Player)) { + return true; + } + + if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) { + m.send(sender, "no_perm"); + return true; + } + + final Player player = (Player) sender; + final String name = player.getName().toLowerCase(); + + if (!PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "not_logged_in"); + return true; + } + + if (args.length != 1) { + m.send(player, "usage_unreg"); + return true; + } + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + try { + if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) { + if (!plugin.database.removeAuth(name)) { + player.sendMessage("error"); + return; + } + if (Settings.isForcedRegistrationEnabled) { + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + Location spawn = plugin.getSpawnLocation(player); + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + player.teleport(tpEvent.getTo()); + } + } + + player.saveData(); + PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); + if (!Settings.getRegisteredGroup.isEmpty()) + Utils.setGroup(player, GroupType.UNREGISTERED); + LimboCache.getInstance().addLimboPlayer(player); + int delay = Settings.getRegistrationTimeout * 20; + int interval = Settings.getWarnMessageInterval; + BukkitScheduler sched = sender.getServer().getScheduler(); + if (delay != 0) { + BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + } + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval))); + m.send(player, "unregistered"); + ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); + return; + } + if (!Settings.unRegisteredGroup.isEmpty()) { + Utils.setGroup(player, Utils.GroupType.UNREGISTERED); + } + PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); + // check if Player cache File Exist and delete it, preventing + // duplication of items + if (playerCache.doesCacheExist(player)) { + playerCache.removeCache(player); + } + if (Settings.applyBlindEffect) + player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + player.setWalkSpeed(0.0f); + player.setFlySpeed(0.0f); + } + m.send(player, "unregistered"); + ConsoleLogger.info(player.getDisplayName() + " unregistered himself"); + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + Location spawn = plugin.getSpawnLocation(player); + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + return; + } else { + m.send(player, "wrong_pwd"); + } + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage("Internal Error please read the server log"); + } + } + }); + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/converter/Converter.java b/src/main/java/fr/xephi/authme/converter/Converter.java new file mode 100644 index 0000000..461567e --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/Converter.java @@ -0,0 +1,4 @@ +package fr.xephi.authme.converter; + +public interface Converter extends Runnable { +} diff --git a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java new file mode 100644 index 0000000..bd60315 --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java @@ -0,0 +1,69 @@ +package fr.xephi.authme.converter; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.settings.Settings; + +/** + * @author Xephi59 + */ +public class CrazyLoginConverter implements Converter { + + public DataSource database; + public AuthMe instance; + public CommandSender sender; + + public CrazyLoginConverter(AuthMe instance, CommandSender sender) { + this.instance = instance; + this.database = instance.database; + this.sender = sender; + } + + public CrazyLoginConverter getInstance() { + return this; + } + + @Override + public void run() { + String fileName = Settings.crazyloginFileName; + try { + File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName); + if (!source.exists()) { + sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!"); + return; + } + String line; + BufferedReader users = new BufferedReader(new FileReader(source)); + while ((line = users.readLine()) != null) { + if (line.contains("|")) { + String[] args = line.split("\\|"); + if (args.length < 2) + continue; + if (args[0].equalsIgnoreCase("name")) + continue; + String playerName = args[0].toLowerCase(); + String psw = args[1]; + if (psw != null) { + PlayerAuth auth = new PlayerAuth(playerName, psw, "127.0.0.1", System.currentTimeMillis(), playerName); + database.saveAuth(auth); + } + } + } + users.close(); + ConsoleLogger.info("CrazyLogin database has been imported correctly"); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + ConsoleLogger.showError("Can't open the crazylogin database file! Does it exist?"); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSql.java b/src/main/java/fr/xephi/authme/converter/FlatToSql.java new file mode 100644 index 0000000..fecaa4f --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/FlatToSql.java @@ -0,0 +1,96 @@ +package fr.xephi.authme.converter; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.Settings; + +/** + * @author Xephi59 + */ +public class FlatToSql implements Converter { + + private static String columnEmail; + private static String columnID; + private static String columnIp; + private static String columnLastLogin; + private static String columnLogged; + private static String columnName; + private static String columnPassword; + private static String lastlocWorld; + private static String lastlocX; + private static String lastlocY; + private static String lastlocZ; + private static String tableName; + + public FlatToSql() { + tableName = Settings.getMySQLTablename; + columnName = Settings.getMySQLColumnName; + columnPassword = Settings.getMySQLColumnPassword; + columnIp = Settings.getMySQLColumnIp; + columnLastLogin = Settings.getMySQLColumnLastLogin; + lastlocX = Settings.getMySQLlastlocX; + lastlocY = Settings.getMySQLlastlocY; + lastlocZ = Settings.getMySQLlastlocZ; + lastlocWorld = Settings.getMySQLlastlocWorld; + columnEmail = Settings.getMySQLColumnEmail; + columnLogged = Settings.getMySQLColumnLogged; + columnID = Settings.getMySQLColumnId; + } + + @Override + public void run() { + try { + File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db"); + source.createNewFile(); + File output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql"); + output.createNewFile(); + BufferedReader br = new BufferedReader(new FileReader(source)); + BufferedWriter sql = new BufferedWriter(new FileWriter(output)); + String createDB = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword + + " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL DEFAULT '127.0.0.1'," + columnLastLogin + " BIGINT NOT NULL DEFAULT '" + System.currentTimeMillis() + "'," + + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + + " VARCHAR(255) DEFAULT 'world'," + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com'," + columnLogged + " SMALLINT NOT NULL DEFAULT '0'," + + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"; + sql.write(createDB); + String line; + String newline; + while ((line = br.readLine()) != null) { + sql.newLine(); + String[] args = line.split(":"); + if (args.length == 4) + newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + + ", 0.0, 0.0, 0.0, 'world', 'your@email.com', 0);"; + else if (args.length == 7) + newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + + ", " + args[6] + ", 'world', 'your@email.com', 0);"; + else if (args.length == 8) + newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + + ", " + args[6] + ", '" + args[7] + "', 'your@email.com', 0);"; + else if (args.length == 9) + newline = "INSERT INTO " + tableName + "(" + columnName + "," + columnPassword + "," + columnIp + "," + columnLastLogin + "," + lastlocX + "," + lastlocY + "," + lastlocZ + "," + + lastlocWorld + "," + columnEmail + "," + columnLogged + ") VALUES ('" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + + ", " + args[6] + ", '" + args[7] + "', '" + args[8] + "', 0);"; + else + newline = ""; + if (!newline.equals("")) + sql.write(newline); + } + sql.close(); + br.close(); + ConsoleLogger.info("The FlatFile has been converted to authme.sql file"); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + ConsoleLogger.showError("Can't open the flat database file! Does it exist?"); + } + } +} diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java new file mode 100644 index 0000000..83a0609 --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java @@ -0,0 +1,177 @@ +package fr.xephi.authme.converter; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.Settings; + +public class FlatToSqlite implements Converter { + + public CommandSender sender; + private String columnEmail; + private String columnID; + private String columnIp; + private String columnLastLogin; + private String columnName; + private String columnPassword; + private Connection con; + private String database; + private String lastlocWorld; + private String lastlocX; + private String lastlocY; + private String lastlocZ; + private String tableName; + + public FlatToSqlite(CommandSender sender) { + this.sender = sender; + } + + private static void close(AutoCloseable o) { + if (o != null) { + try { + o.close(); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + } + } + } + + @Override + public void run() { + database = Settings.getMySQLDatabase; + tableName = Settings.getMySQLTablename; + columnName = Settings.getMySQLColumnName; + columnPassword = Settings.getMySQLColumnPassword; + columnIp = Settings.getMySQLColumnIp; + columnLastLogin = Settings.getMySQLColumnLastLogin; + lastlocX = Settings.getMySQLlastlocX; + lastlocY = Settings.getMySQLlastlocY; + lastlocZ = Settings.getMySQLlastlocZ; + lastlocWorld = Settings.getMySQLlastlocWorld; + columnEmail = Settings.getMySQLColumnEmail; + columnID = Settings.getMySQLColumnId; + + File source = new File(Settings.APLUGIN_FOLDER, "auths.db"); + if (!source.exists()) { + sender.sendMessage("Source file for FlatFile database not found... Aborting"); + return; + } + + try { + connect(); + setup(); + } catch (Exception e) { + sender.sendMessage("Some error appeared while trying to setup and connect to sqlite database... Aborting"); + return; + } + + try (BufferedReader reader = new BufferedReader(new FileReader(source))) { + String line; + int i = 1; + String newline; + while ((line = reader.readLine()) != null) { + String[] args = line.split(":"); + if (args.length == 4) + newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');"; + else if (args.length == 7) + newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + + ", 'world', 'your@email.com');"; + else if (args.length == 8) + newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + + ", '" + args[7] + "', 'your@email.com');"; + else if (args.length == 9) + newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", " + args[4] + ", " + args[5] + ", " + args[6] + + ", '" + args[7] + "', '" + args[8] + "');"; + else + newline = ""; + if (!newline.equals("")) + saveAuth(newline); + i = i + 1; + } + String resp = "The FlatFile has been converted to " + database + ".db file"; + ConsoleLogger.info(resp); + sender.sendMessage(resp); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage("Can't open the flat database file!"); + } finally { + close(con); + } + } + + private synchronized void connect() throws ClassNotFoundException, SQLException { + Class.forName("org.sqlite.JDBC"); + con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db"); + } + + private synchronized boolean saveAuth(String s) { + PreparedStatement pst = null; + try { + pst = con.prepareStatement(s); + pst.executeUpdate(); + } catch (SQLException e) { + ConsoleLogger.showError(e.getMessage()); + return false; + } finally { + close(pst); + } + return true; + } + + private synchronized void setup() throws SQLException { + Statement st = null; + ResultSet rs = null; + try { + st = con.createStatement(); + st.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + " (" + columnID + " INTEGER AUTO_INCREMENT," + columnName + " VARCHAR(255) NOT NULL UNIQUE," + columnPassword + + " VARCHAR(255) NOT NULL," + columnIp + " VARCHAR(40) NOT NULL," + columnLastLogin + " BIGINT," + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocY + + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0'," + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT '" + Settings.defaultWorld + "'," + columnEmail + + " VARCHAR(255) DEFAULT 'your@email.com'," + "CONSTRAINT table_const_prim PRIMARY KEY (" + columnID + "));"); + rs = con.getMetaData().getColumns(null, null, tableName, columnPassword); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnPassword + " VARCHAR(255) NOT NULL;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnIp); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnIp + " VARCHAR(40) NOT NULL;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnLastLogin); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnLastLogin + " BIGINT;"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, lastlocX); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocX + " DOUBLE NOT NULL DEFAULT '0.0';"); + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocY + " DOUBLE NOT NULL DEFAULT '0.0';"); + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocZ + " DOUBLE NOT NULL DEFAULT '0.0';"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, lastlocWorld); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + lastlocWorld + " VARCHAR(255) NOT NULL DEFAULT 'world';"); + } + rs.close(); + rs = con.getMetaData().getColumns(null, null, tableName, columnEmail); + if (!rs.next()) { + st.executeUpdate("ALTER TABLE " + tableName + " ADD COLUMN " + columnEmail + " VARCHAR(255) DEFAULT 'your@email.com';"); + } + } finally { + close(rs); + close(st); + } + } +} diff --git a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java new file mode 100644 index 0000000..ee10cad --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java @@ -0,0 +1,36 @@ +package fr.xephi.authme.converter; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.datasource.SQLite; +import fr.xephi.authme.settings.Settings; + +public class ForceFlatToSqlite implements Converter { + + private DataSource data; + + public ForceFlatToSqlite(DataSource data, AuthMe plugin) { + this.data = data; + } + + @Override + public void run() { + DataSource sqlite = null; + try { + sqlite = new SQLite(); + for (PlayerAuth auth : data.getAllAuths()) { + auth.setRealName("Player"); + sqlite.saveAuth(auth); + } + Settings.setValue("DataSource.backend", "sqlite"); + ConsoleLogger.info("Database successfully converted to sqlite !"); + } catch (Exception e) { + ConsoleLogger.showError("An error appeared while trying to convert flatfile to sqlite ..."); + } finally { + if (sqlite != null) + sqlite.close(); + } + } +} diff --git a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java new file mode 100644 index 0000000..6d89a77 --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java @@ -0,0 +1,98 @@ +package fr.xephi.authme.converter; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map.Entry; + +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.security.HashAlgorithm; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Settings; + +/** + * @author Xephi59 + */ +public class RakamakConverter implements Converter { + + public DataSource database; + public AuthMe instance; + public CommandSender sender; + + public RakamakConverter(AuthMe instance, CommandSender sender) { + this.instance = instance; + this.database = instance.database; + this.sender = sender; + } + + public RakamakConverter getInstance() { + return this; + } + + @Override + public void run() { + HashAlgorithm hash = Settings.getPasswordHash; + boolean useIP = Settings.rakamakUseIp; + String fileName = Settings.rakamakUsers; + String ipFileName = Settings.rakamakUsersIp; + File source = new File(Settings.APLUGIN_FOLDER, fileName); + File ipfiles = new File(Settings.APLUGIN_FOLDER, ipFileName); + HashMap playerIP = new HashMap<>(); + HashMap playerPSW = new HashMap<>(); + try { + BufferedReader users; + BufferedReader ipFile; + ipFile = new BufferedReader(new FileReader(ipfiles)); + String line; + if (useIP) { + String tempLine; + while ((tempLine = ipFile.readLine()) != null) { + if (tempLine.contains("=")) { + String[] args = tempLine.split("="); + playerIP.put(args[0], args[1]); + } + } + } + ipFile.close(); + users = new BufferedReader(new FileReader(source)); + while ((line = users.readLine()) != null) { + if (line.contains("=")) { + String[] arguments = line.split("="); + try { + playerPSW.put(arguments[0], PasswordSecurity.getHash(hash, arguments[1], arguments[0])); + } catch (NoSuchAlgorithmException e) { + ConsoleLogger.showError(e.getMessage()); + } + } + } + users.close(); + for (Entry m : playerPSW.entrySet()) { + String playerName = m.getKey(); + String psw = playerPSW.get(playerName); + String ip; + if (useIP) { + ip = playerIP.get(playerName); + } else { + ip = "127.0.0.1"; + } + PlayerAuth auth = new PlayerAuth(playerName, psw, ip, System.currentTimeMillis(), playerName); + if (PasswordSecurity.userSalt.containsKey(playerName)) + auth.setSalt(PasswordSecurity.userSalt.get(playerName)); + database.saveAuth(auth); + } + ConsoleLogger.info("Rakamak database has been imported correctly"); + sender.sendMessage("Rakamak database has been imported correctly"); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + sender.sendMessage("Can't open the rakamak database file! Does it exist?"); + } + } +} diff --git a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java new file mode 100644 index 0000000..e3c2b72 --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java @@ -0,0 +1,43 @@ +package fr.xephi.authme.converter; + +import java.io.File; + +import org.bukkit.OfflinePlayer; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; + +public class RoyalAuthConverter implements Converter { + + public AuthMe plugin; + private DataSource data; + + public RoyalAuthConverter(AuthMe plugin) { + this.plugin = plugin; + this.data = plugin.database; + } + + @Override + public void run() { + for (OfflinePlayer o : plugin.getServer().getOfflinePlayers()) { + try { + String name = o.getName().toLowerCase(); + String sp = File.separator; + File file = new File("." + sp + "plugins" + sp + "RoyalAuth" + sp + "userdata" + sp + name + ".yml"); + if (data.isAuthAvailable(name)) + continue; + if (!file.exists()) + continue; + RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file); + PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName()); + data.saveAuth(auth); + } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError("Error while trying to import " + o.getName() + " RoyalAuth datas"); + } + } + } + +} diff --git a/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java b/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java new file mode 100644 index 0000000..14c1dcc --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/RoyalAuthYamlReader.java @@ -0,0 +1,22 @@ +package fr.xephi.authme.converter; + +import java.io.File; + +import fr.xephi.authme.settings.CustomConfiguration; + +public class RoyalAuthYamlReader extends CustomConfiguration { + + public RoyalAuthYamlReader(File file) { + super(file); + load(); + save(); + } + + public String getHash() { + return getString("login.password"); + } + + public long getLastLogin() { + return getLong("timestamps.quit"); + } +} diff --git a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java new file mode 100644 index 0000000..2a6c154 --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java @@ -0,0 +1,47 @@ +package fr.xephi.authme.converter; + +import java.util.List; + +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.datasource.FlatFile; +import fr.xephi.authme.settings.Messages; + +public class SqlToFlat implements Converter { + + public DataSource database; + public AuthMe plugin; + public CommandSender sender; + + public SqlToFlat(AuthMe plugin, CommandSender sender) { + this.plugin = plugin; + this.database = plugin.database; + this.sender = sender; + } + + @Override + public void run() { + try { + FlatFile flat = new FlatFile(); + List auths = database.getAllAuths(); + int i = 0; + final int size = auths.size(); + for (PlayerAuth auth : auths) { + flat.saveAuth(auth); + i++; + if ((i % 100) == 0) { + sender.sendMessage("Conversion Status : " + i + " / " + size); + } + } + sender.sendMessage("Successfully convert from SQL table to file auths.db"); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + Messages.getInstance().send(sender, "error"); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/converter/vAuthConverter.java b/src/main/java/fr/xephi/authme/converter/vAuthConverter.java new file mode 100644 index 0000000..47236a4 --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/vAuthConverter.java @@ -0,0 +1,31 @@ +package fr.xephi.authme.converter; + +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.datasource.DataSource; + +public class vAuthConverter implements Converter { + + public DataSource database; + public AuthMe plugin; + public CommandSender sender; + + public vAuthConverter(AuthMe plugin, CommandSender sender) { + this.plugin = plugin; + this.database = plugin.database; + this.sender = sender; + } + + @Override + public void run() { + try { + new vAuthFileReader(plugin, sender).convert(); + } catch (Exception e) { + sender.sendMessage(e.getMessage()); + ConsoleLogger.showError(e.getMessage()); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java new file mode 100644 index 0000000..cd21bcb --- /dev/null +++ b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java @@ -0,0 +1,77 @@ +package fr.xephi.authme.converter; + +import java.io.File; +import java.io.IOException; +import java.util.Scanner; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.datasource.DataSource; + +public class vAuthFileReader { + + public DataSource database; + public AuthMe plugin; + public CommandSender sender; + + public vAuthFileReader(AuthMe plugin, CommandSender sender) { + this.plugin = plugin; + this.database = plugin.database; + this.sender = sender; + } + + public void convert() throws IOException { + final File file = new File(plugin.getDataFolder().getParent() + "" + File.separator + "vAuth" + File.separator + "passwords.yml"); + Scanner scanner; + try { + scanner = new Scanner(file); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + String name = line.split(": ")[0]; + String password = line.split(": ")[1]; + PlayerAuth auth; + if (isUUIDinstance(password)) { + String pname; + try { + pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName(); + } catch (Exception | NoSuchMethodError e) { + pname = getName(UUID.fromString(name)); + } + if (pname == null) + continue; + auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname); + } else { + auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", name); + } + database.saveAuth(auth); + } + } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); + } + + } + + private String getName(UUID uuid) { + try { + for (OfflinePlayer op : Bukkit.getOfflinePlayers()) { + if (op.getUniqueId().compareTo(uuid) == 0) + return op.getName(); + } + } catch (Exception ignored) { + } + return null; + } + + private boolean isUUIDinstance(String s) { + if (String.valueOf(s.charAt(8)).equalsIgnoreCase("-")) + return true; + return true; + } + +} diff --git a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java new file mode 100644 index 0000000..b7952ab --- /dev/null +++ b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java @@ -0,0 +1,387 @@ +package fr.xephi.authme.datasource; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; + +public class CacheDataSource implements DataSource { + + private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); + private final ExecutorService exec; + private final DataSource source; + + public CacheDataSource(AuthMe pl, DataSource src) { + this.source = src; + this.exec = Executors.newCachedThreadPool(); + + /* + * We need to load all players in cache ... It will took more time to + * load the server, but it will be much easier to check for an + * isAuthAvailable ! + */ + exec.execute(new Runnable() { + @Override + public void run() { + for (PlayerAuth auth : source.getAllAuths()) { + cache.put(auth.getNickname().toLowerCase(), auth); + } + } + }); + } + + @Override + public List autoPurgeDatabase(long until) { + List cleared = source.autoPurgeDatabase(until); + if (cleared.size() > 0) { + for (PlayerAuth auth : cache.values()) { + if (auth.getLastLogin() < until) { + cache.remove(auth.getNickname()); + } + } + } + return cleared; + } + + @Override + public synchronized void close() { + exec.shutdown(); + source.close(); + } + + @Override + public int getAccountsRegistered() { + return cache.size(); + } + + @Override + public List getAllAuths() { + return new ArrayList<>(cache.values()); + } + + @Override + public synchronized List getAllAuthsByEmail(String email) { + List result = new ArrayList<>(); + for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) { + PlayerAuth p = stringPlayerAuthEntry.getValue(); + if (p.getEmail().equals(email)) + result.add(p.getNickname()); + } + return result; + } + + @Override + public synchronized List getAllAuthsByIp(String ip) { + List result = new ArrayList<>(); + for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) { + PlayerAuth p = stringPlayerAuthEntry.getValue(); + if (p.getIp().equals(ip)) + result.add(p.getNickname()); + } + return result; + } + + @Override + public synchronized List getAllAuthsByName(PlayerAuth auth) { + List result = new ArrayList<>(); + for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) { + PlayerAuth p = stringPlayerAuthEntry.getValue(); + if (p.getIp().equals(auth.getIp())) + result.add(p.getNickname()); + } + return result; + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + user = user.toLowerCase(); + if (cache.containsKey(user)) { + return cache.get(user); + } + return null; + } + + @Override + public int getIps(String ip) { + int count = 0; + for (Map.Entry p : cache.entrySet()) { + if (p.getValue().getIp().equals(ip)) { + count++; + } + } + return count; + } + + @Override + public List getLoggedPlayers() { + return new ArrayList<>(PlayerCache.getInstance().getCache().values()); + } + + @Override + public DataSourceType getType() { + return source.getType(); + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + return cache.containsKey(user.toLowerCase()); + } + + @Override + public boolean isLogged(String user) { + user = user.toLowerCase(); + return PlayerCache.getInstance().getCache().containsKey(user); + } + + @Override + public synchronized void purgeBanned(final List banned) { + exec.execute(new Runnable() { + @Override + public void run() { + source.purgeBanned(banned); + for (PlayerAuth auth : cache.values()) { + if (banned.contains(auth.getNickname())) { + cache.remove(auth.getNickname()); + } + } + } + }); + } + + @Override + public int purgeDatabase(long until) { + int cleared = source.purgeDatabase(until); + if (cleared > 0) { + for (PlayerAuth auth : cache.values()) { + if (auth.getLastLogin() < until) { + cache.remove(auth.getNickname()); + } + } + } + return cleared; + } + + @Override + public void purgeLogged() { + exec.execute(new Runnable() { + @Override + public void run() { + source.purgeLogged(); + } + }); + } + + @Override + public void reload() { + exec.execute(new Runnable() { + @Override + public void run() { + cache.clear(); + source.reload(); + for (Player player : Utils.getOnlinePlayers()) { + String user = player.getName().toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(user)) { + PlayerAuth auth = source.getAuth(user); + cache.put(user, auth); + } + } + } + }); + } + + @Override + public synchronized boolean removeAuth(String username) { + final String user = username.toLowerCase(); + final PlayerAuth auth = cache.get(user); + cache.remove(user); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.removeAuth(user)) { + cache.put(user, auth); + } + } + }); + return true; + } + + @Override + public synchronized boolean saveAuth(final PlayerAuth auth) { + cache.put(auth.getNickname(), auth); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.saveAuth(auth)) { + cache.remove(auth.getNickname()); + } + } + }); + return true; + } + + @Override + public void setLogged(final String user) { + exec.execute(new Runnable() { + @Override + public void run() { + source.setLogged(user.toLowerCase()); + } + }); + } + + @Override + public void setUnlogged(final String user) { + exec.execute(new Runnable() { + @Override + public void run() { + source.setUnlogged(user.toLowerCase()); + } + }); + } + + @Override + public synchronized boolean updateEmail(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; + } + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final String oldEmail = cachedAuth.getEmail(); + cachedAuth.setEmail(auth.getEmail()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateEmail(auth)) { + if (cache.containsKey(auth.getNickname())) { + cache.get(auth.getNickname()).setEmail(oldEmail); + } + } + } + }); + return true; + } + + @Override + public void updateName(final String oldone, final String newone) { + if (cache.containsKey(oldone)) { + cache.put(newone, cache.get(oldone)); + cache.remove(oldone); + } + exec.execute(new Runnable() { + @Override + public void run() { + source.updateName(oldone, newone); + } + }); + } + + @Override + public synchronized boolean updatePassword(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; + } + final String oldHash = cache.get(auth.getNickname()).getHash(); + cache.get(auth.getNickname()).setHash(auth.getHash()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updatePassword(auth)) { + if (cache.containsKey(auth.getNickname())) { + cache.get(auth.getNickname()).setHash(oldHash); + } + } + } + }); + return true; + } + + @Override + public boolean updateQuitLoc(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; + } + final PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final double oldX = cachedAuth.getQuitLocX(); + final double oldY = cachedAuth.getQuitLocY(); + final double oldZ = cachedAuth.getQuitLocZ(); + final String oldWorld = cachedAuth.getWorld(); + + cachedAuth.setQuitLocX(auth.getQuitLocX()); + cachedAuth.setQuitLocY(auth.getQuitLocY()); + cachedAuth.setQuitLocZ(auth.getQuitLocZ()); + cachedAuth.setWorld(auth.getWorld()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateQuitLoc(auth)) { + if (cache.containsKey(auth.getNickname())) { + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + cachedAuth.setQuitLocX(oldX); + cachedAuth.setQuitLocY(oldY); + cachedAuth.setQuitLocZ(oldZ); + cachedAuth.setWorld(oldWorld); + } + } + } + }); + return true; + } + + @Override + public synchronized boolean updateSalt(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; + } + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final String oldSalt = cachedAuth.getSalt(); + cachedAuth.setSalt(auth.getSalt()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateSalt(auth)) { + if (cache.containsKey(auth.getNickname())) { + cache.get(auth.getNickname()).setSalt(oldSalt); + } + } + } + }); + return true; + } + + @Override + public boolean updateSession(final PlayerAuth auth) { + if (!cache.containsKey(auth.getNickname())) { + return false; + } + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + final String oldIp = cachedAuth.getIp(); + final long oldLastLogin = cachedAuth.getLastLogin(); + final String oldRealName = cachedAuth.getRealName(); + + cachedAuth.setIp(auth.getIp()); + cachedAuth.setLastLogin(auth.getLastLogin()); + cachedAuth.setRealName(auth.getRealName()); + exec.execute(new Runnable() { + @Override + public void run() { + if (!source.updateSession(auth)) { + if (cache.containsKey(auth.getNickname())) { + PlayerAuth cachedAuth = cache.get(auth.getNickname()); + cachedAuth.setIp(oldIp); + cachedAuth.setLastLogin(oldLastLogin); + cachedAuth.setRealName(oldRealName); + } + } + } + }); + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/datasource/DataSource.java b/src/main/java/fr/xephi/authme/datasource/DataSource.java new file mode 100644 index 0000000..9468a4b --- /dev/null +++ b/src/main/java/fr/xephi/authme/datasource/DataSource.java @@ -0,0 +1,70 @@ +package fr.xephi.authme.datasource; + +import java.util.List; + +import fr.xephi.authme.cache.auth.PlayerAuth; + +public interface DataSource { + + List autoPurgeDatabase(long until); + + void close(); + + int getAccountsRegistered(); + + List getAllAuths(); + + List getAllAuthsByEmail(String email); + + List getAllAuthsByIp(String ip); + + List getAllAuthsByName(PlayerAuth auth); + + PlayerAuth getAuth(String user); + + int getIps(String ip); + + List getLoggedPlayers(); + + DataSourceType getType(); + + boolean isAuthAvailable(String user); + + boolean isLogged(String user); + + void purgeBanned(List banned); + + int purgeDatabase(long until); + + void purgeLogged(); + + void reload(); + + boolean removeAuth(String user); + + boolean saveAuth(PlayerAuth auth); + + void setLogged(String user); + + void setUnlogged(String user); + + boolean updateEmail(PlayerAuth auth); + + void updateName(String oldone, String newone); + + boolean updatePassword(PlayerAuth auth); + + boolean updateQuitLoc(PlayerAuth auth); + + boolean updateSalt(PlayerAuth auth); + + boolean updateSession(PlayerAuth auth); + + enum DataSourceType { + FILE, + MYSQL, + SQLITE, + SQLITEHIKARI + } + +} diff --git a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java new file mode 100644 index 0000000..b517642 --- /dev/null +++ b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java @@ -0,0 +1,330 @@ +package fr.xephi.authme.datasource; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import fr.xephi.authme.cache.auth.PlayerAuth; + +public class DatabaseCalls implements DataSource { + + private DataSource database; + private final ExecutorService exec; + + public DatabaseCalls(DataSource database) { + this.database = database; + this.exec = Executors.newCachedThreadPool(); + } + + @Override + public synchronized List autoPurgeDatabase(final long until) { + try { + return exec.submit(new Callable>() { + public List call() throws Exception { + return database.autoPurgeDatabase(until); + } + }).get(); + } catch (Exception e) { + return new ArrayList<>(); + } + } + + @Override + public synchronized void close() { + exec.shutdown(); + database.close(); + } + + @Override + public synchronized int getAccountsRegistered() { + try { + return exec.submit(new Callable() { + public Integer call() throws Exception { + return database.getAccountsRegistered(); + } + }).get(); + } catch (Exception e) { + return -1; + } + } + + @Override + public synchronized List getAllAuths() { + try { + return exec.submit(new Callable>() { + public List call() throws Exception { + return database.getAllAuths(); + } + }).get(); + } catch (Exception e) { + return new ArrayList<>(); + } + } + + @Override + public synchronized List getAllAuthsByEmail(final String email) { + try { + return exec.submit(new Callable>() { + public List call() throws Exception { + return database.getAllAuthsByEmail(email); + } + }).get(); + } catch (Exception e) { + return new ArrayList<>(); + } + } + + @Override + public synchronized List getAllAuthsByIp(final String ip) { + try { + return exec.submit(new Callable>() { + public List call() throws Exception { + return database.getAllAuthsByIp(ip); + } + }).get(); + } catch (Exception e) { + return new ArrayList<>(); + } + } + + @Override + public synchronized List getAllAuthsByName(final PlayerAuth auth) { + try { + return exec.submit(new Callable>() { + public List call() throws Exception { + return database.getAllAuthsByName(auth); + } + }).get(); + } catch (Exception e) { + return new ArrayList<>(); + } + } + + @Override + public synchronized PlayerAuth getAuth(final String user) { + try { + return exec.submit(new Callable() { + public PlayerAuth call() throws Exception { + return database.getAuth(user); + } + }).get(); + } catch (Exception e) { + return null; + } + } + + @Override + public synchronized int getIps(final String ip) { + try { + return exec.submit(new Callable() { + + public Integer call() throws Exception { + return database.getIps(ip); + } + }).get(); + } catch (Exception e) { + return -1; + } + } + + @Override + public List getLoggedPlayers() { + try { + return exec.submit(new Callable>() { + public List call() throws Exception { + return database.getLoggedPlayers(); + } + }).get(); + } catch (Exception e) { + return new ArrayList<>(); + } + } + + @Override + public synchronized DataSourceType getType() { + return database.getType(); + } + + @Override + public synchronized boolean isAuthAvailable(final String user) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.isAuthAvailable(user); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized boolean isLogged(final String user) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.isLogged(user); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized void purgeBanned(final List banned) { + new Thread(new Runnable() { + public synchronized void run() { + database.purgeBanned(banned); + } + }).start(); + } + + @Override + public synchronized int purgeDatabase(final long until) { + try { + return exec.submit(new Callable() { + public Integer call() throws Exception { + return database.purgeDatabase(until); + } + }).get(); + } catch (Exception e) { + return -1; + } + } + + @Override + public synchronized void purgeLogged() { + exec.execute(new Runnable() { + public synchronized void run() { + database.purgeLogged(); + } + }); + } + + @Override + public synchronized void reload() { + database.reload(); + } + + @Override + public synchronized boolean removeAuth(final String user) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.removeAuth(user); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized boolean saveAuth(final PlayerAuth auth) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.saveAuth(auth); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized void setLogged(final String user) { + exec.execute(new Runnable() { + public synchronized void run() { + database.setLogged(user); + } + }); + } + + @Override + public synchronized void setUnlogged(final String user) { + exec.execute(new Runnable() { + public synchronized void run() { + database.setUnlogged(user); + } + }); + } + + @Override + public synchronized boolean updateEmail(final PlayerAuth auth) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.updateEmail(auth); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized void updateName(final String oldone, final String newone) { + exec.execute(new Runnable() { + public synchronized void run() { + database.updateName(oldone, newone); + } + }); + } + + @Override + public synchronized boolean updatePassword(final PlayerAuth auth) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.updatePassword(auth); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized boolean updateQuitLoc(final PlayerAuth auth) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.updateQuitLoc(auth); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized boolean updateSalt(final PlayerAuth auth) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.updateSalt(auth); + } + }).get(); + } catch (Exception e) { + return false; + } + } + + @Override + public synchronized boolean updateSession(final PlayerAuth auth) { + try { + return exec.submit(new Callable() { + public Boolean call() throws Exception { + return database.updateSession(auth); + } + }).get(); + } catch (Exception e) { + return false; + } + } + +} diff --git a/src/main/java/fr/xephi/authme/datasource/FlatFile.java b/src/main/java/fr/xephi/authme/datasource/FlatFile.java new file mode 100644 index 0000000..4945d9a --- /dev/null +++ b/src/main/java/fr/xephi/authme/datasource/FlatFile.java @@ -0,0 +1,770 @@ +package fr.xephi.authme.datasource; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.settings.Settings; + +public class FlatFile implements DataSource { + + /* + * file layout: + * + * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY:LASTPOSZ: + * LASTPOSWORLD:EMAIL + * + * Old but compatible: + * PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS:LASTPOSX:LASTPOSY + * :LASTPOSZ:LASTPOSWORLD PLAYERNAME:HASHSUM:IP:LOGININMILLIESECONDS + * PLAYERNAME:HASHSUM:IP PLAYERNAME:HASHSUM + */ + private File source; + + public FlatFile() { + source = Settings.AUTH_FILE; + try { + source.createNewFile(); + } catch (IOException e) { + ConsoleLogger.showError(e.getMessage()); + if (Settings.isStopEnabled) { + ConsoleLogger.showError("Can't use FLAT FILE... SHUTDOWN..."); + AuthMe.getInstance().getServer().shutdown(); + } + if (!Settings.isStopEnabled) { + AuthMe.getInstance().getServer().getPluginManager().disablePlugin(AuthMe.getInstance()); + } + e.printStackTrace(); + } + } + + @Override + public List autoPurgeDatabase(long until) { + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + List cleared = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length >= 4) { + if (Long.parseLong(args[3]) >= until) { + lines.add(line); + continue; + } + } + cleared.add(args[0]); + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return cleared; + } + + @Override + public synchronized void close() { + } + + @Override + public int getAccountsRegistered() { + BufferedReader br = null; + int result = 0; + try { + br = new BufferedReader(new FileReader(source)); + while ((br.readLine()) != null) { + result++; + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return result; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return result; + } + + @Override + public List getAllAuths() { + BufferedReader br = null; + List auths = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + switch (args.length) { + case 2: + auths.add(new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0])); + break; + case 3: + auths.add(new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0])); + break; + case 4: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0])); + break; + case 7: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), + "unavailableworld", "your@email.com", args[0])); + break; + case 8: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + "your@email.com", args[0])); + break; + case 9: + auths.add(new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + args[8], args[0])); + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return auths; + } + + @Override + public List getAllAuthsByEmail(String email) { + BufferedReader br = null; + List countEmail = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 8 && args[8].equals(email)) { + countEmail.add(args[0]); + } + } + return countEmail; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public List getAllAuthsByIp(String ip) { + BufferedReader br = null; + List countIp = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 3 && args[2].equals(ip)) { + countIp.add(args[0]); + } + } + return countIp; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public List getAllAuthsByName(PlayerAuth auth) { + BufferedReader br = null; + List countIp = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 3 && args[2].equals(auth.getIp())) { + countIp.add(args[0]); + } + } + return countIp; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equalsIgnoreCase(user)) { + switch (args.length) { + case 2: + return new PlayerAuth(args[0], args[1], "192.168.0.1", 0, "your@email.com", args[0]); + case 3: + return new PlayerAuth(args[0], args[1], args[2], 0, "your@email.com", args[0]); + case 4: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), "your@email.com", args[0]); + case 7: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), + "unavailableworld", "your@email.com", args[0]); + case 8: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + "your@email.com", args[0]); + case 9: + return new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + args[8], args[0]); + } + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return null; + } + + @Override + public int getIps(String ip) { + BufferedReader br = null; + int countIp = 0; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 3 && args[2].equals(ip)) { + countIp++; + } + } + return countIp; + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + } + + @Override + public List getLoggedPlayers() { + return new ArrayList<>(); + } + + @Override + public DataSourceType getType() { + return DataSourceType.FILE; + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 1 && args[0].equalsIgnoreCase(user)) { + return true; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + return false; + } + + @Override + public boolean isLogged(String user) { + return PlayerCache.getInstance().isAuthenticated(user); + } + + @Override + public void purgeBanned(List banned) { + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + try { + if (banned.contains(args[0])) { + lines.add(line); + } + } catch (NullPointerException | ArrayIndexOutOfBoundsException exc) { + } + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return; + } + + @Override + public int purgeDatabase(long until) { + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + int cleared = 0; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length >= 4) { + if (Long.parseLong(args[3]) >= until) { + lines.add(line); + continue; + } + } + cleared++; + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return cleared; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return cleared; + } + + @Override + public void purgeLogged() { + } + + @Override + public void reload() { + } + + @Override + public synchronized boolean removeAuth(String user) { + if (!isAuthAvailable(user)) { + return false; + } + BufferedReader br = null; + BufferedWriter bw = null; + ArrayList lines = new ArrayList<>(); + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args.length > 1 && !args[0].equals(user)) { + lines.add(line); + } + } + bw = new BufferedWriter(new FileWriter(source)); + for (String l : lines) { + bw.write(l + "\n"); + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return true; + } + + @Override + public synchronized boolean saveAuth(PlayerAuth auth) { + if (isAuthAvailable(auth.getNickname())) { + return false; + } + BufferedWriter bw = null; + try { + bw = new BufferedWriter(new FileWriter(source, true)); + bw.write(auth.getNickname() + ":" + auth.getHash() + ":" + auth.getIp() + ":" + auth.getLastLogin() + ":" + auth.getQuitLocX() + ":" + auth.getQuitLocY() + ":" + auth.getQuitLocZ() + ":" + + auth.getWorld() + ":" + auth.getEmail() + "\n"); + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (bw != null) { + try { + bw.close(); + } catch (IOException ex) { + } + } + } + return true; + } + + @Override + public void setLogged(String user) { + } + + @Override + public void setUnlogged(String user) { + } + + @Override + public boolean updateEmail(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line = ""; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equals(auth.getNickname())) { + newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + auth.getEmail(), args[0]); + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public void updateName(String oldone, String newone) { + PlayerAuth auth = this.getAuth(oldone); + auth.setName(newone); + this.saveAuth(auth); + this.removeAuth(oldone); + } + + @Override + public synchronized boolean updatePassword(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equals(auth.getNickname())) { + switch (args.length) { + case 4: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + case 7: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), + "world", "your@email.com", args[0]); + break; + } + case 8: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), + args[7], "your@email.com", args[0]); + break; + } + case 9: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], Long.parseLong(args[3]), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), + args[7], args[8], args[0]); + break; + } + default: { + newAuth = new PlayerAuth(args[0], auth.getHash(), args[2], 0, 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + } + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public boolean updateQuitLoc(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equalsIgnoreCase(auth.getNickname())) { + newAuth = new PlayerAuth(args[0], args[1], args[2], Long.parseLong(args[3]), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), auth.getEmail(), args[0]); + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } + + @Override + public boolean updateSalt(PlayerAuth auth) { + return false; + } + + @Override + public boolean updateSession(PlayerAuth auth) { + if (!isAuthAvailable(auth.getNickname())) { + return false; + } + PlayerAuth newAuth = null; + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(source)); + String line; + while ((line = br.readLine()) != null) { + String[] args = line.split(":"); + if (args[0].equalsIgnoreCase(auth.getNickname())) { + switch (args.length) { + case 4: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + case 7: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), "world", + "your@email.com", args[0]); + break; + } + case 8: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + "your@email.com", args[0]); + break; + } + case 9: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), Double.parseDouble(args[4]), Double.parseDouble(args[5]), Double.parseDouble(args[6]), args[7], + args[8], args[0]); + break; + } + default: { + newAuth = new PlayerAuth(args[0], args[1], auth.getIp(), auth.getLastLogin(), 0, 0, 0, "world", "your@email.com", args[0]); + break; + } + } + break; + } + } + } catch (FileNotFoundException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } catch (IOException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ex) { + } + } + } + if (newAuth != null) { + removeAuth(auth.getNickname()); + saveAuth(newAuth); + } + return true; + } +} diff --git a/src/main/java/fr/xephi/authme/datasource/MySQL.java b/src/main/java/fr/xephi/authme/datasource/MySQL.java new file mode 100644 index 0000000..e5b3c51 --- /dev/null +++ b/src/main/java/fr/xephi/authme/datasource/MySQL.java @@ -0,0 +1,1085 @@ +package fr.xephi.authme.datasource; + +import java.sql.Blob; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.pool.PoolInitializationException; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.security.HashAlgorithm; +import fr.xephi.authme.settings.Settings; + +public class MySQL implements DataSource { + + private String columnEmail; + private String columnGroup; + private String columnID; + private String columnIp; + private String columnLastLogin; + private String columnLogged; + private String columnName; + private List columnOthers; + private String columnPassword; + private String columnRealName; + private String columnSalt; + private String database; + private HikariDataSource ds; + private String host; + private String lastlocWorld; + private String lastlocX; + private String lastlocY; + private String lastlocZ; + private int maxConnections; + private String password; + private String port; + private String tableName; + private String username; + + public MySQL() throws ClassNotFoundException, SQLException, PoolInitializationException { + this.host = Settings.getMySQLHost; + this.port = Settings.getMySQLPort; + this.username = Settings.getMySQLUsername; + this.password = Settings.getMySQLPassword; + this.database = Settings.getMySQLDatabase; + this.tableName = Settings.getMySQLTablename; + this.columnName = Settings.getMySQLColumnName; + this.columnPassword = Settings.getMySQLColumnPassword; + this.columnIp = Settings.getMySQLColumnIp; + this.columnLastLogin = Settings.getMySQLColumnLastLogin; + this.lastlocX = Settings.getMySQLlastlocX; + this.lastlocY = Settings.getMySQLlastlocY; + this.lastlocZ = Settings.getMySQLlastlocZ; + this.lastlocWorld = Settings.getMySQLlastlocWorld; + this.columnSalt = Settings.getMySQLColumnSalt; + this.columnGroup = Settings.getMySQLColumnGroup; + this.columnEmail = Settings.getMySQLColumnEmail; + this.columnOthers = Settings.getMySQLOtherUsernameColumn; + this.columnID = Settings.getMySQLColumnId; + this.columnLogged = Settings.getMySQLColumnLogged; + this.columnRealName = Settings.getMySQLColumnRealName; + this.maxConnections = Settings.getMySQLMaxConnections; + + // Set the connection arguments (and check if connection is ok) + try { + this.setConnectionArguments(); + } catch (RuntimeException e) { + if (e instanceof IllegalArgumentException) { + ConsoleLogger.showError("Invalid database arguments! Please check your configuration!"); + ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN..."); + throw new IllegalArgumentException(e); + } + if (e instanceof PoolInitializationException) { + ConsoleLogger.showError("Can't initialize database connection! Please check your configuration!"); + ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN..."); + throw new PoolInitializationException(e); + } + ConsoleLogger.showError("Can't use the Hikari Connection Pool! Please, report this error to the developer! SHUTDOWN..."); + throw e; + } + + // Initialize the database + try { + this.setupConnection(); + } catch (SQLException e) { + this.close(); + ConsoleLogger.showError("Can't initialize the MySQL database... Please check your database settings in the config.yml file! SHUTDOWN..."); + ConsoleLogger.showError("If this error persists, please report it to the developer! SHUTDOWN..."); + throw e; + } + } + + @Override + public synchronized List autoPurgeDatabase(long until) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List list = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized void close() { + if (ds != null) + ds.close(); + } + + @Override + public int getAccountsRegistered() { + int result = 0; + Connection con = null; + PreparedStatement pst = null; + ResultSet rs; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); + rs = pst.executeQuery(); + if (rs != null && rs.next()) { + result = rs.getInt(1); + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return result; + } finally { + close(pst); + close(con); + } + return result; + } + + @Override + public List getAllAuths() { + List auths = new ArrayList<>(); + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); + rs = pst.executeQuery(); + while (rs.next()) { + PlayerAuth pAuth; + int id = rs.getInt(columnID); + if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + if (!columnGroup.isEmpty()) + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + else + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), + rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { + ResultSet rsid; + pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); + pst.setInt(1, id); + rsid = pst.executeQuery(); + if (rsid.next()) { + Blob blob = rsid.getBlob("data"); + byte[] bytes = blob.getBytes(1, (int) blob.length()); + pAuth.setHash(new String(bytes)); + } + rsid.close(); + } + auths.add(pAuth); + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + close(pst); + close(con); + close(rs); + } + return auths; + } + + @Override + public synchronized List getAllAuthsByEmail(String email) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countEmail = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); + pst.setString(1, email); + rs = pst.executeQuery(); + while (rs.next()) { + countEmail.add(rs.getString(columnName)); + } + return countEmail; + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized List getAllAuthsByIp(String ip) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while (rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized List getAllAuthsByName(PlayerAuth auth) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, auth.getIp()); + rs = pst.executeQuery(); + while (rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + PlayerAuth pAuth = null; + int id; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) { + id = rs.getInt(columnID); + if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { + pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + if (!columnGroup.isEmpty()) + pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + else + pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), + rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName).toLowerCase(), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { + rs.close(); + pst.close(); + pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); + pst.setInt(1, id); + rs = pst.executeQuery(); + if (rs.next()) { + Blob blob = rs.getBlob("data"); + byte[] bytes = blob.getBytes(1, (int) blob.length()); + pAuth.setHash(new String(bytes)); + } + } + } else { + return null; + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + close(rs); + close(pst); + close(con); + } + return pAuth; + } + + @Override + public synchronized int getIps(String ip) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + int countIp = 0; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while (rs.next()) { + countIp++; + } + return countIp; + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public List getLoggedPlayers() { + List auths = new ArrayList<>(); + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); + rs = pst.executeQuery(); + while (rs.next()) { + PlayerAuth pAuth; + int id = rs.getInt(columnID); + if (rs.getString(columnIp).isEmpty() && rs.getString(columnIp) != null) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + if (!columnGroup.isEmpty()) + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + else + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getString(columnIp), rs.getLong(columnLastLogin), + rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + if (Settings.getPasswordHash == HashAlgorithm.XENFORO) { + ResultSet rsid; + pst = con.prepareStatement("SELECT * FROM xf_user_authenticate WHERE " + columnID + "=?;"); + pst.setInt(1, id); + rsid = pst.executeQuery(); + if (rsid.next()) { + Blob blob = rsid.getBlob("data"); + byte[] bytes = blob.getBytes(1, (int) blob.length()); + pAuth.setHash(new String(bytes)); + } + rsid.close(); + } + auths.add(pAuth); + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + close(pst); + close(rs); + close(con); + } + return auths; + } + + @Override + public DataSourceType getType() { + return DataSourceType.MYSQL; + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); + pst.setString(1, user); + rs = pst.executeQuery(); + return rs.next(); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public boolean isLogged(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) + return (rs.getInt(columnLogged) == 1); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + close(con); + } + return false; + } + + @Override + public synchronized void purgeBanned(List banned) { + Connection con = null; + PreparedStatement pst = null; + try { + for (String name : banned) { + con = getConnection(); + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + pst.setString(1, name); + pst.executeUpdate(); + } + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + } finally { + close(pst); + close(con); + } + } + + @Override + public synchronized int purgeDatabase(long until) { + Connection con = null; + PreparedStatement pst = null; + try { + con = getConnection(); + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + " autoPurgeDatabase(long until) { + PreparedStatement pst = null; + ResultSet rs = null; + List list = new ArrayList<>(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "(); + } finally { + close(rs); + close(pst); + } + } + + @Override + public synchronized void close() { + try { + con.close(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + } + } + + @Override + public int getAccountsRegistered() { + int result = 0; + PreparedStatement pst = null; + ResultSet rs; + try { + pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); + rs = pst.executeQuery(); + if (rs != null && rs.next()) { + result = rs.getInt(1); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return result; + } finally { + close(pst); + } + return result; + } + + @Override + public List getAllAuths() { + List auths = new ArrayList<>(); + PreparedStatement pst = null; + ResultSet rs; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); + rs = pst.executeQuery(); + while (rs.next()) { + PlayerAuth pAuth; + if (rs.getString(columnIp).isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + auths.add(pAuth); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + close(pst); + } + return auths; + } + + @Override + public List getAllAuthsByEmail(String email) { + PreparedStatement pst = null; + ResultSet rs = null; + List countEmail = new ArrayList<>(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); + pst.setString(1, email); + rs = pst.executeQuery(); + while (rs.next()) { + countEmail.add(rs.getString(columnName)); + } + return countEmail; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (NullPointerException npe) { + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + } + } + + @Override + public List getAllAuthsByIp(String ip) { + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList<>(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while (rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (NullPointerException npe) { + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + } + } + + @Override + public List getAllAuthsByName(PlayerAuth auth) { + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList<>(); + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, auth.getIp()); + rs = pst.executeQuery(); + while (rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (NullPointerException npe) { + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + } + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + PreparedStatement pst = null; + ResultSet rs = null; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) { + if (rs.getString(columnIp).isEmpty()) { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + } else { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + } else { + return null; + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + close(rs); + close(pst); + } + } + + @Override + public int getIps(String ip) { + PreparedStatement pst = null; + ResultSet rs = null; + int countIp = 0; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while (rs.next()) { + countIp++; + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } finally { + close(rs); + close(pst); + } + } + + @Override + public List getLoggedPlayers() { + List auths = new ArrayList<>(); + PreparedStatement pst = null; + ResultSet rs; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); + rs = pst.executeQuery(); + while (rs.next()) { + PlayerAuth pAuth; + if (rs.getString(columnIp).isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + auths.add(pAuth); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + close(pst); + } + return auths; + } + + @Override + public DataSourceType getType() { + return DataSourceType.SQLITE; + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + PreparedStatement pst = null; + ResultSet rs = null; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); + pst.setString(1, user); + rs = pst.executeQuery(); + return rs.next(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + } + } + + @Override + public boolean isLogged(String user) { + PreparedStatement pst = null; + ResultSet rs = null; + try { + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) + return (rs.getInt(columnLogged) == 1); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + } + return false; + } + + @Override + public void purgeBanned(List banned) { + PreparedStatement pst = null; + try { + for (String name : banned) { + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); + pst.setString(1, name); + pst.executeUpdate(); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + } finally { + close(pst); + } + } + + @Override + public int purgeDatabase(long until) { + PreparedStatement pst = null; + try { + + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + " autoPurgeDatabase(long until) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List list = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLastLogin + "(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized void close() { + if (ds != null) + ds.close(); + } + + @Override + public int getAccountsRegistered() { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs; + int result = 0; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT COUNT(*) FROM " + tableName + ";"); + rs = pst.executeQuery(); + if (rs != null && rs.next()) { + result = rs.getInt(1); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return result; + } finally { + close(pst); + close(con); + } + return result; + } + + @Override + public List getAllAuths() { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs; + List auths = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + ";"); + rs = pst.executeQuery(); + while (rs.next()) { + PlayerAuth pAuth; + if (rs.getString(columnIp).isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + auths.add(pAuth); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return auths; + } finally { + close(pst); + close(con); + } + return auths; + } + + @Override + public List getAllAuthsByEmail(String email) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countEmail = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnEmail + "=?;"); + pst.setString(1, email); + rs = pst.executeQuery(); + while (rs.next()) { + countEmail.add(rs.getString(columnName)); + } + return countEmail; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (NullPointerException npe) { + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public List getAllAuthsByIp(String ip) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while (rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (NullPointerException npe) { + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public List getAllAuthsByName(PlayerAuth auth) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + List countIp = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, auth.getIp()); + rs = pst.executeQuery(); + while (rs.next()) { + countIp.add(rs.getString(columnName)); + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return new ArrayList<>(); + } catch (NullPointerException npe) { + return new ArrayList<>(); + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public synchronized PlayerAuth getAuth(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) { + if (rs.getString(columnIp).isEmpty()) { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "192.168.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + } else { + return new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + } else { + return null; + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return null; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public int getIps(String ip) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + int countIp = 0; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnIp + "=?;"); + pst.setString(1, ip); + rs = pst.executeQuery(); + while (rs.next()) { + countIp++; + } + return countIp; + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return 0; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public List getLoggedPlayers() { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs; + List auths = new ArrayList<>(); + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + columnLogged + "=1;"); + rs = pst.executeQuery(); + while (rs.next()) { + PlayerAuth pAuth; + if (rs.getString(columnIp).isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), "127.0.0.1", rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), + rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } else { + if (!columnSalt.isEmpty()) { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnSalt), rs.getInt(columnGroup), rs.getString(columnIp), + rs.getLong(columnLastLogin), rs.getDouble(lastlocX), rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), + rs.getString(columnRealName)); + } else { + pAuth = new PlayerAuth(rs.getString(columnName), rs.getString(columnPassword), rs.getString(columnIp), rs.getLong(columnLastLogin), rs.getDouble(lastlocX), + rs.getDouble(lastlocY), rs.getDouble(lastlocZ), rs.getString(lastlocWorld), rs.getString(columnEmail), rs.getString(columnRealName)); + } + } + auths.add(pAuth); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + } finally { + close(pst); + close(con); + } + return auths; + } + + @Override + public DataSourceType getType() { + return DataSourceType.SQLITEHIKARI; + } + + @Override + public synchronized boolean isAuthAvailable(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=LOWER(?);"); + pst.setString(1, user); + rs = pst.executeQuery(); + return rs.next(); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + close(con); + } + } + + @Override + public boolean isLogged(String user) { + Connection con = null; + PreparedStatement pst = null; + ResultSet rs = null; + try { + con = getConnection(); + pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE LOWER(" + columnName + ")=?;"); + pst.setString(1, user); + rs = pst.executeQuery(); + if (rs.next()) + return (rs.getInt(columnLogged) == 1); + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + return false; + } finally { + close(rs); + close(pst); + close(con); + } + return false; + } + + @Override + public void purgeBanned(List banned) { + Connection con = null; + PreparedStatement pst = null; + try { + con = getConnection(); + for (String name : banned) { + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnName + "=?;"); + pst.setString(1, name); + pst.executeUpdate(); + } + } catch (SQLException ex) { + ConsoleLogger.showError(ex.getMessage()); + } finally { + close(pst); + close(con); + } + } + + @Override + public int purgeDatabase(long until) { + Connection con = null; + PreparedStatement pst = null; + try { + con = getConnection(); + pst = con.prepareStatement("DELETE FROM " + tableName + " WHERE " + columnLastLogin + " + * This event is called when we need to compare or get an hash password, for set + * a custom EncryptionMethod + *

+ * + * @see fr.xephi.authme.security.crypts.EncryptionMethod + * + * @author Xephi59 + */ +public class PasswordEncryptionEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private EncryptionMethod method = null; + private String playerName = ""; + + public PasswordEncryptionEvent(EncryptionMethod method, String playerName) { + super(false); + this.method = method; + this.playerName = playerName; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public EncryptionMethod getMethod() { + return method; + } + + public String getPlayerName() { + return playerName; + } + + public void setMethod(EncryptionMethod method) { + this.method = method; + } + +} diff --git a/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java b/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java new file mode 100644 index 0000000..8eb93ff --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/ProtectInventoryEvent.java @@ -0,0 +1,58 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +/** + * + * This event is call just after store inventory into cache and will empty the + * player inventory. + * + * @author Xephi59 + */ +public class ProtectInventoryEvent extends CustomEvent { + + private ItemStack[] emptyArmor = null; + private ItemStack[] emptyInventory = null; + private Player player; + private ItemStack[] storedarmor; + private ItemStack[] storedinventory; + + public ProtectInventoryEvent(Player player) { + super(true); + this.player = player; + this.storedinventory = player.getInventory().getContents(); + this.storedarmor = player.getInventory().getArmorContents(); + this.emptyInventory = new ItemStack[36]; + this.emptyArmor = new ItemStack[4]; + } + + public ItemStack[] getEmptyArmor() { + return this.emptyArmor; + } + + public ItemStack[] getEmptyInventory() { + return this.emptyInventory; + } + + public Player getPlayer() { + return this.player; + } + + public ItemStack[] getStoredArmor() { + return this.storedarmor; + } + + public ItemStack[] getStoredInventory() { + return this.storedinventory; + } + + public void setNewArmor(ItemStack[] emptyArmor) { + this.emptyArmor = emptyArmor; + } + + public void setNewInventory(ItemStack[] emptyInventory) { + this.emptyInventory = emptyInventory; + } + +} diff --git a/src/main/java/fr/xephi/authme/events/RegisterTeleportEvent.java b/src/main/java/fr/xephi/authme/events/RegisterTeleportEvent.java new file mode 100644 index 0000000..c9b4d61 --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/RegisterTeleportEvent.java @@ -0,0 +1,41 @@ +package fr.xephi.authme.events; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +/** + * + * This event is call if, and only if, a player is teleported just after a + * register. + * + * @author Xephi59 + */ +public class RegisterTeleportEvent extends CustomEvent { + + private Location from; + private Player player; + private Location to; + + public RegisterTeleportEvent(Player player, Location to) { + this.player = player; + this.from = player.getLocation(); + this.to = to; + } + + public Location getFrom() { + return from; + } + + public Player getPlayer() { + return player; + } + + public Location getTo() { + return to; + } + + public void setTo(Location to) { + this.to = to; + } + +} diff --git a/src/main/java/fr/xephi/authme/events/ResetInventoryEvent.java b/src/main/java/fr/xephi/authme/events/ResetInventoryEvent.java new file mode 100644 index 0000000..7d59736 --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/ResetInventoryEvent.java @@ -0,0 +1,28 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; + +/** + * + * This event is call when a creative inventory is reseted. + * + * @author Xephi59 + */ +public class ResetInventoryEvent extends CustomEvent { + + private Player player; + + public ResetInventoryEvent(Player player) { + super(true); + this.player = player; + } + + public Player getPlayer() { + return this.player; + } + + public void setPlayer(Player player) { + this.player = player; + } + +} diff --git a/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java b/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java new file mode 100644 index 0000000..22f01b5 --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/RestoreInventoryEvent.java @@ -0,0 +1,30 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; + +/** + * This event restore the inventory. + * + * @author Xephi59 + */ +public class RestoreInventoryEvent extends CustomEvent { + + private Player player; + + public RestoreInventoryEvent(Player player) { + this.player = player; + } + + public RestoreInventoryEvent(Player player, boolean async) { + super(async); + this.player = player; + } + + public Player getPlayer() { + return this.player; + } + + public void setPlayer(Player player) { + this.player = player; + } +} diff --git a/src/main/java/fr/xephi/authme/events/SpawnTeleportEvent.java b/src/main/java/fr/xephi/authme/events/SpawnTeleportEvent.java new file mode 100644 index 0000000..157d05c --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/SpawnTeleportEvent.java @@ -0,0 +1,46 @@ +package fr.xephi.authme.events; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +/** + * + * Called if a player is teleported to a specific spawn + * + * @author Xephi59 + */ +public class SpawnTeleportEvent extends CustomEvent { + + private Location from; + private boolean isAuthenticated; + private Player player; + private Location to; + + public SpawnTeleportEvent(Player player, Location from, Location to, boolean isAuthenticated) { + this.player = player; + this.from = from; + this.to = to; + this.isAuthenticated = isAuthenticated; + } + + public Location getFrom() { + return from; + } + + public Player getPlayer() { + return player; + } + + public Location getTo() { + return to; + } + + public boolean isAuthenticated() { + return isAuthenticated; + } + + public void setTo(Location to) { + this.to = to; + } + +} diff --git a/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java b/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java new file mode 100644 index 0000000..a3cb114 --- /dev/null +++ b/src/main/java/fr/xephi/authme/events/StoreInventoryEvent.java @@ -0,0 +1,54 @@ +package fr.xephi.authme.events; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import fr.xephi.authme.cache.backup.JsonCache; + +/** + * This event is call just before write inventory content to cache + * + * @author Xephi59 + */ +public class StoreInventoryEvent extends CustomEvent { + + private ItemStack[] armor; + private ItemStack[] inventory; + private Player player; + + public StoreInventoryEvent(Player player) { + this.player = player; + this.inventory = player.getInventory().getContents(); + this.armor = player.getInventory().getArmorContents(); + } + + public StoreInventoryEvent(Player player, JsonCache jsonCache) { + this.player = player; + this.inventory = player.getInventory().getContents(); + this.armor = player.getInventory().getArmorContents(); + } + + public ItemStack[] getArmor() { + return this.armor; + } + + public ItemStack[] getInventory() { + return this.inventory; + } + + public Player getPlayer() { + return this.player; + } + + public void setArmor(ItemStack[] armor) { + this.armor = armor; + } + + public void setInventory(ItemStack[] inventory) { + this.inventory = inventory; + } + + public void setPlayer(Player player) { + this.player = player; + } +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java new file mode 100644 index 0000000..51d2c23 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMeBlockListener.java @@ -0,0 +1,37 @@ +package fr.xephi.authme.listener; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; + +public class AuthMeBlockListener implements Listener { + + public AuthMe instance; + + public AuthMeBlockListener(AuthMe instance) { + + this.instance = instance; + } + + @EventHandler(ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + if (Utils.checkAuth(event.getPlayer())) + return; + event.setCancelled(true); + } + +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java new file mode 100644 index 0000000..83bb463 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMeEntityListener.java @@ -0,0 +1,191 @@ +package fr.xephi.authme.listener; + +import java.lang.reflect.Method; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityInteractEvent; +import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.projectiles.ProjectileSource; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; + +public class AuthMeEntityListener implements Listener { + + private static Method getShooter; + private static boolean shooterIsProjectileSource; + public AuthMe instance; + + public AuthMeEntityListener(AuthMe instance) { + this.instance = instance; + try { + Method m = Projectile.class.getDeclaredMethod("getShooter"); + shooterIsProjectileSource = m.getReturnType() != LivingEntity.class; + } catch (Exception ignored) { + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void entityRegainHealthEvent(EntityRegainHealthEvent event) { + Entity entity = event.getEntity(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + if (Utils.checkAuth((Player) entity)) { + return; + } + + event.setAmount(0); + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onDmg(EntityDamageByEntityEvent event) { + Entity entity = event.getDamager(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + if (Utils.checkAuth(player)) { + return; + } + + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onEntityDamage(EntityDamageEvent event) { + Entity entity = event.getEntity(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + if (Utils.checkAuth(player)) { + return; + } + player.setFireTicks(0); + event.setDamage(0); + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onEntityInteract(EntityInteractEvent event) { + Entity entity = event.getEntity(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + if (Utils.checkAuth((Player) entity)) { + return; + } + + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onEntityTarget(EntityTargetEvent event) { + Entity entity = event.getTarget(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + if (Utils.checkAuth((Player) entity)) { + return; + } + + event.setTarget(null); + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onFoodLevelChange(FoodLevelChangeEvent event) { + Entity entity = event.getEntity(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + if (Utils.checkAuth((Player) entity)) { + return; + } + + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onLowestEntityInteract(EntityInteractEvent event) { + Entity entity = event.getEntity(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + if (Utils.checkAuth((Player) entity)) { + return; + } + + event.setCancelled(true); + } + + // TODO: Need to check this, player can't throw snowball but the item is taken. + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onProjectileLaunch(ProjectileLaunchEvent event) { + Projectile projectile = event.getEntity(); + Player player = null; + if (projectile == null) { + return; + } + + if (shooterIsProjectileSource) { + ProjectileSource shooter = projectile.getShooter(); + if (shooter == null || !(shooter instanceof Player)) { + return; + } + player = (Player) shooter; + } else { + try { + if (getShooter == null) { + getShooter = Projectile.class.getMethod("getShooter"); + } + Object obj = getShooter.invoke(null); + player = (Player) obj; + } catch (Exception ignored) { + } + } + + if (Utils.checkAuth(player)) { + return; + } + + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) + public void onShoot(EntityShootBowEvent event) { + Entity entity = event.getEntity(); + if (entity == null || !(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + if (Utils.checkAuth(player)) { + return; + } + + event.setCancelled(true); + } + +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeInventoryPacketAdapter.java b/src/main/java/fr/xephi/authme/listener/AuthMeInventoryPacketAdapter.java new file mode 100644 index 0000000..55b4a9f --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMeInventoryPacketAdapter.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2015 AuthMe-Team + * + * 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 . + */ +package fr.xephi.authme.listener; + +import java.lang.reflect.InvocationTargetException; +import java.util.Arrays; +import java.util.Collections; +import java.util.logging.Level; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.events.PacketEvent; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.settings.Settings; + +public class AuthMeInventoryPacketAdapter extends PacketAdapter { + + private static final int HOTBAR_SIZE = 9; + // http://wiki.vg/Inventory#Inventory (0-4 crafting, 5-8 armor, 9-35 main inventory, 36-44 inventory) + // +1 because an index starts with 0 + private static final int PLAYER_CRAFTING_SIZE = 5; + private static final int PLAYER_INVENTORY = 0; + + public AuthMeInventoryPacketAdapter(AuthMe plugin) { + super(plugin, PacketType.Play.Server.SET_SLOT, PacketType.Play.Server.WINDOW_ITEMS); + } + + @Override + public void onPacketSending(PacketEvent packetEvent) { + Player player = packetEvent.getPlayer(); + PacketContainer packet = packetEvent.getPacket(); + + byte windowId = packet.getIntegers().read(0).byteValue(); + if (windowId == PLAYER_INVENTORY && Settings.protectInventoryBeforeLogInEnabled && !PlayerCache.getInstance().isAuthenticated(player.getName())) { + packetEvent.setCancelled(true); + } + } + + public void register() { + ProtocolLibrary.getProtocolManager().addPacketListener(this); + } + + public void sendInventoryPacket(Player player) { + ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); + PacketContainer inventoryPacket = protocolManager.createPacket(PacketType.Play.Server.WINDOW_ITEMS); + + // we are sending our own inventory + inventoryPacket.getIntegers().write(0, PLAYER_INVENTORY); + + ItemStack[] playerCrafting = new ItemStack[PLAYER_CRAFTING_SIZE]; + Arrays.fill(playerCrafting, new ItemStack(Material.AIR)); + ItemStack[] armorContents = player.getInventory().getArmorContents(); + ItemStack[] mainInventory = player.getInventory().getContents(); + + // bukkit saves the armor in reversed order + Collections.reverse(Arrays.asList(armorContents)); + + // same main inventory. The hotbar is at the beginning but it should be at the end of the array + ItemStack[] hotbar = Arrays.copyOfRange(mainInventory, 0, HOTBAR_SIZE); + ItemStack[] storedInventory = Arrays.copyOfRange(mainInventory, HOTBAR_SIZE, mainInventory.length); + + // concat all parts of the inventory together + int inventorySize = playerCrafting.length + armorContents.length + mainInventory.length; + ItemStack[] completeInventory = new ItemStack[inventorySize]; + + System.arraycopy(playerCrafting, 0, completeInventory, 0, playerCrafting.length); + System.arraycopy(armorContents, 0, completeInventory, playerCrafting.length, armorContents.length); + + // storedInventory and hotbar + System.arraycopy(storedInventory, 0, completeInventory, playerCrafting.length + armorContents.length, storedInventory.length); + System.arraycopy(hotbar, 0, completeInventory, playerCrafting.length + armorContents.length + storedInventory.length, hotbar.length); + + inventoryPacket.getItemArrayModifier().write(0, completeInventory); + try { + protocolManager.sendServerPacket(player, inventoryPacket, false); + } catch (InvocationTargetException invocationExc) { + plugin.getLogger().log(Level.WARNING, "Error during inventory recovery", invocationExc); + } + } +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java new file mode 100644 index 0000000..fc4df04 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener.java @@ -0,0 +1,573 @@ +package fr.xephi.authme.listener; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.PatternSyntaxException; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerGameModeChangeEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerShearEntityEvent; + +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class AuthMePlayerListener implements Listener { + + public static ConcurrentHashMap causeByAuthMe = new ConcurrentHashMap<>(); + public static ConcurrentHashMap gameMode = new ConcurrentHashMap<>(); + public static ConcurrentHashMap joinMessage = new ConcurrentHashMap<>(); + public AuthMe plugin; + private final List antibot = new ArrayList<>(); + private final Messages m = Messages.getInstance(); + + public AuthMePlayerListener(final AuthMe plugin) { + this.plugin = plugin; + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerBedEnter(final PlayerBedEnterEvent event) { + if (Utils.checkAuth(event.getPlayer())) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerChat(final AsyncPlayerChatEvent event) { + handleChat(event); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { + final String msg = event.getMessage(); + if (msg.equalsIgnoreCase("/worldedit cui")) { + return; + } + + final String cmd = msg.split(" ")[0]; + if (cmd.equalsIgnoreCase("/login") || cmd.equalsIgnoreCase("/register") || cmd.equalsIgnoreCase("/l") || cmd.equalsIgnoreCase("/reg") || cmd.equalsIgnoreCase("/email") + || cmd.equalsIgnoreCase("/captcha")) { + return; + } + if (Settings.useEssentialsMotd && cmd.equalsIgnoreCase("/motd")) { + return; + } + if (Settings.allowCommands.contains(cmd)) { + return; + } + + if (!Utils.checkAuth(event.getPlayer())) { + event.setMessage("/notloggedin"); + event.setCancelled(true); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) + public void onPlayerConsumeItem(final PlayerItemConsumeEvent event) { + if (Utils.checkAuth(event.getPlayer())) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerDropItem(final PlayerDropItemEvent event) { + if (Utils.checkAuth(event.getPlayer())) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerEarlyChat(final AsyncPlayerChatEvent event) { + handleChat(event); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) + public void onPlayerFish(final PlayerFishEvent event) { + final Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPlayerGameModeChange(final PlayerGameModeChangeEvent event) { + final Player player = event.getPlayer(); + if (player == null) { + return; + } + if (plugin.authmePermissible(player, "authme.bypassforcesurvival")) { + return; + } + if (Utils.checkAuth(player)) { + return; + } + + final String name = player.getName().toLowerCase(); + if (causeByAuthMe.containsKey(name)) { + causeByAuthMe.remove(name); + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onPlayerHighChat(final AsyncPlayerChatEvent event) { + handleChat(event); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPlayerHighestChat(final AsyncPlayerChatEvent event) { + handleChat(event); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPlayerInteract(final PlayerInteractEvent event) { + final Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerInteractEntity(final PlayerInteractEntityEvent event) { + final Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerInventoryClick(final InventoryClickEvent event) { + if (event.getWhoClicked() == null) { + return; + } + if (!(event.getWhoClicked() instanceof Player)) { + return; + } + if (Utils.checkAuth((Player) event.getWhoClicked())) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPlayerInventoryOpen(final InventoryOpenEvent event) { + final Player player = (Player) event.getPlayer(); + if (Utils.checkAuth(player)) { + return; + } + event.setCancelled(true); + + /* + * @note little hack cause InventoryOpenEvent cannot be cancelled for + * real, cause no packet is send to server by client for the main inv + */ + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.closeInventory(); + } + }, 1); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerJoin(final PlayerJoinEvent event) { + if (event.getPlayer() == null) { + return; + } + + // Shedule login task so works after the prelogin + // (Fix found by Koolaid5000) + Bukkit.getScheduler().runTask(plugin, new Runnable() { + @Override + public void run() { + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + plugin.management.performJoin(player); + + // Remove the join message while the player isn't logging in + if ((Settings.enableProtection || Settings.delayJoinMessage) && event.getJoinMessage() != null) { + joinMessage.put(name, event.getJoinMessage()); + event.setJoinMessage(null); + } + } + }); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerKick(final PlayerKickEvent event) { + if (event.getPlayer() == null) { + return; + } + + if ((!Settings.isForceSingleSessionEnabled) && (event.getReason().contains(m.getString("same_nick")))) { + event.setCancelled(true); + return; + } + + final Player player = event.getPlayer(); + plugin.management.performQuit(player, true); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerLogin(final PlayerLoginEvent event) { + final Player player = event.getPlayer(); + if (player == null) { + return; + } + final String name = player.getName().toLowerCase(); + final boolean isAuthAvailable = plugin.database.isAuthAvailable(name); + + if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { + return; + } + + if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) { + return; + } + + if (!Settings.countriesBlacklist.isEmpty() && !isAuthAvailable && !plugin.authmePermissible(player, "authme.bypassantibot")) { + final String code = Utils.getCountryCode(event.getAddress().getHostAddress()); + if (((code == null) || Settings.countriesBlacklist.contains(code))) { + event.setKickMessage(m.send("country_banned")[0]); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + return; + } + } + if (Settings.enableProtection && !Settings.countries.isEmpty() && !isAuthAvailable && !plugin.authmePermissible(player, "authme.bypassantibot")) { + final String code = Utils.getCountryCode(event.getAddress().getHostAddress()); + if (((code == null) || !Settings.countries.contains(code))) { + event.setKickMessage(m.send("country_banned")[0]); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + return; + } + } + + // TODO: Add message to the messages file!!! + if (Settings.isKickNonRegisteredEnabled && !isAuthAvailable) { + if (Settings.antiBotInAction) { + event.setKickMessage("AntiBot service in action! You actually need to be registered!"); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + return; + } else { + event.setKickMessage(m.send("reg_only")[0]); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + return; + } + } + + final int min = Settings.getMinNickLength; + final int max = Settings.getMaxNickLength; + final String regex = Settings.getNickRegex; + + if (name.length() > max || name.length() < min) { + event.setKickMessage(Arrays.toString(m.send("name_len"))); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + return; + } + try { + if (!player.getName().matches(regex) || name.equalsIgnoreCase("Player")) { + try { + event.setKickMessage(m.send("regex")[0].replace("REG_EX", regex)); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + } catch (final Exception exc) { + event.setKickMessage("allowed char : " + regex); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + } + return; + } + } catch (final PatternSyntaxException pse) { + if (regex == null || regex.isEmpty()) { + event.setKickMessage("Your nickname do not match"); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + return; + } + try { + event.setKickMessage(m.send("regex")[0].replace("REG_EX", regex)); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + } catch (final Exception exc) { + event.setKickMessage("allowed char : " + regex); + event.setResult(PlayerLoginEvent.Result.KICK_OTHER); + } + return; + } + + if (event.getResult() == PlayerLoginEvent.Result.ALLOWED) { + checkAntiBotMod(player); + if (Settings.bungee) { + final ByteArrayDataOutput out = ByteStreams.newDataOutput(); + out.writeUTF("IP"); + player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); + } + return; + } + if (event.getResult() != PlayerLoginEvent.Result.KICK_FULL) { + return; + } + if (!plugin.authmePermissible(player, "authme.vip")) { + event.setKickMessage(m.send("kick_fullserver")[0]); + event.setResult(PlayerLoginEvent.Result.KICK_FULL); + return; + } + + final int playersOnline = Utils.getOnlinePlayers().size(); + if (playersOnline > plugin.getServer().getMaxPlayers()) { + event.allow(); + } else { + final Player pl = plugin.generateKickPlayer(Utils.getOnlinePlayers()); + if (pl != null) { + pl.kickPlayer(m.send("kick_forvip")[0]); + event.allow(); + } else { + ConsoleLogger.info("The player " + player.getName() + " tryed to join, but the server was full"); + event.setKickMessage(m.send("kick_fullserver")[0]); + event.setResult(PlayerLoginEvent.Result.KICK_FULL); + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) + public void onPlayerLowChat(final AsyncPlayerChatEvent event) { + handleChat(event); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerMove(final PlayerMoveEvent event) { + final Player player = event.getPlayer(); + if (Utils.checkAuth(player)) { + return; + } + + if (!Settings.isMovementAllowed) { + if (!event.getFrom().getBlock().equals(event.getTo().getBlock())) { + event.setTo(event.getFrom()); + } + return; + } + + if (Settings.getMovementRadius == 0) { + return; + } + + final int radius = Settings.getMovementRadius; + final Location spawn = plugin.getSpawnLocation(player); + + if (spawn != null && spawn.getWorld() != null) { + if (!event.getPlayer().getWorld().equals(spawn.getWorld())) { + event.getPlayer().teleport(spawn); + return; + } + if ((spawn.distance(player.getLocation()) > radius)) { + event.getPlayer().teleport(spawn); + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) + public void onPlayerNormalChat(final AsyncPlayerChatEvent event) { + handleChat(event); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPlayerPickupItem(final PlayerPickupItemEvent event) { + if (Utils.checkAuth(event.getPlayer())) { + return; + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerQuit(final PlayerQuitEvent event) { + if (event.getPlayer() == null) { + return; + } + + final Player player = event.getPlayer(); + final String name = player.getName().toLowerCase(); + + plugin.management.performQuit(player, false); + + if (!PlayerCache.getInstance().isAuthenticated(name) && Settings.enableProtection) { + event.setQuitMessage(null); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerRespawn(final PlayerRespawnEvent event) { + final Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) { + return; + } + final String name = player.getName().toLowerCase(); + final Location spawn = plugin.getSpawnLocation(player); + if (Settings.isSaveQuitLocationEnabled && plugin.database.isAuthAvailable(name)) { + final PlayerAuth auth = new PlayerAuth(name, spawn.getX(), spawn.getY(), spawn.getZ(), spawn.getWorld().getName(), player.getName()); + plugin.database.updateQuitLoc(auth); + } + if (spawn != null && spawn.getWorld() != null) { + event.setRespawnLocation(spawn); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) + public void onPlayerShear(final PlayerShearEntityEvent event) { + final Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPreLogin(final AsyncPlayerPreLoginEvent event) { + final String name = event.getName().toLowerCase(); + final Player player = Bukkit.getServer().getPlayer(name); + if (player == null) { + return; + } + + // Check if forceSingleSession is set to true, so kick player that has + // joined with same nick of online player + if (Settings.isForceSingleSessionEnabled && plugin.dataManager.isOnline(player, name)) { + event.setKickMessage(m.send("same_nick")[0]); + event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER); + if (LimboCache.getInstance().hasLimboPlayer(name)) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + final LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); + if (limbo != null && PlayerCache.getInstance().isAuthenticated(player.getName().toLowerCase())) { + Utils.addNormal(player, limbo.getGroup()); + LimboCache.getInstance().deleteLimboPlayer(player.getName().toLowerCase()); + } + } + }); + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onSignChange(final SignChangeEvent event) { + if (Utils.checkAuth(event.getPlayer())) { + return; + } + event.setCancelled(true); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void playerHitPlayerEvent(final EntityDamageByEntityEvent event) { + final Entity damager = event.getDamager(); + if (!(damager instanceof Player)) { + return; + } + if (Utils.checkAuth((Player) damager)) { + return; + } + + event.setCancelled(true); + } + + private void checkAntiBotMod(final Player player) { + if (plugin.delayedAntiBot || plugin.antibotMod) { + return; + } + if (plugin.authmePermissible(player, "authme.bypassantibot")) { + return; + } + if (antibot.size() > Settings.antiBotSensibility) { + plugin.switchAntiBotMod(true); + for (final String s : m.send("antibot_auto_enabled")) { + Bukkit.broadcastMessage(s); + } + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + if (plugin.antibotMod) { + plugin.switchAntiBotMod(false); + antibot.clear(); + for (final String s : m.send("antibot_auto_disabled")) { + Bukkit.broadcastMessage(s.replace("%m", "" + Settings.antiBotDuration)); + } + } + } + }, Settings.antiBotDuration * 1200); + return; + } + antibot.add(player.getName().toLowerCase()); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + antibot.remove(player.getName().toLowerCase()); + } + }, 300); + } + + private void handleChat(final AsyncPlayerChatEvent event) { + final Player player = event.getPlayer(); + if (!Utils.checkAuth(player)) { + final String cmd = event.getMessage().split(" ")[0]; + if (!Settings.isChatAllowed && !(Settings.allowCommands.contains(cmd))) { + event.setCancelled(true); + } + if (plugin.database.isAuthAvailable(player.getName().toLowerCase())) { + m.send(player, "login_msg"); + } else { + if (Settings.emailRegistration) { + m.send(player, "reg_email_msg"); + } else { + m.send(player, "reg_msg"); + } + } + } + } + +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener16.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener16.java new file mode 100644 index 0000000..5c90dea --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener16.java @@ -0,0 +1,28 @@ +package fr.xephi.authme.listener; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerEditBookEvent; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; + +public class AuthMePlayerListener16 implements Listener { + + public AuthMe plugin; + + public AuthMePlayerListener16(AuthMe plugin) { + this.plugin = plugin; + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.NORMAL) + public void onPlayerEditBook(PlayerEditBookEvent event) { + Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) + return; + event.setCancelled(true); + } + +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener18.java b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener18.java new file mode 100644 index 0000000..ae92d88 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMePlayerListener18.java @@ -0,0 +1,28 @@ +package fr.xephi.authme.listener; + +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; + +public class AuthMePlayerListener18 implements Listener { + + public AuthMe plugin; + + public AuthMePlayerListener18(AuthMe plugin) { + this.plugin = plugin; + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { + Player player = event.getPlayer(); + if (player == null || Utils.checkAuth(player)) + return; + event.setCancelled(true); + } + +} diff --git a/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java new file mode 100644 index 0000000..0f324e2 --- /dev/null +++ b/src/main/java/fr/xephi/authme/listener/AuthMeServerListener.java @@ -0,0 +1,81 @@ +package fr.xephi.authme.listener; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.event.server.ServerListPingEvent; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class AuthMeServerListener implements Listener { + + public AuthMe plugin; + private final Messages m = Messages.getInstance(); + + public AuthMeServerListener(final AuthMe plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPluginDisable(final PluginDisableEvent event) { + final String pluginName = event.getPlugin().getName(); + if (pluginName.equalsIgnoreCase("Essentials")) { + plugin.ess = null; + ConsoleLogger.info("Essentials has been disabled, unhook!"); + return; + } + if (pluginName.equalsIgnoreCase("EssentialsSpawn")) { + plugin.essentialsSpawn = null; + ConsoleLogger.info("EssentialsSpawn has been disabled, unhook!"); + return; + } + if (pluginName.equalsIgnoreCase("Vault")) { + plugin.permission = null; + ConsoleLogger.showError("Vault has been disabled, unhook permissions!"); + } + if (pluginName.equalsIgnoreCase("ProtocolLib")) { + plugin.inventoryProtector = null; + ConsoleLogger.showError("ProtocolLib has been disabled, unhook packet inventory protection!"); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPluginEnable(final PluginEnableEvent event) { + final String pluginName = event.getPlugin().getName(); + if (pluginName.equalsIgnoreCase("Essentials") || pluginName.equalsIgnoreCase("EssentialsSpawn")) { + plugin.checkEssentials(); + } + if (pluginName.equalsIgnoreCase("Vault")) { + plugin.checkVault(); + } + if (pluginName.equalsIgnoreCase("ProtocolLib")) { + plugin.checkProtocolLib(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onServerPing(final ServerListPingEvent event) { + if (!Settings.enableProtection) { + return; + } + if (Settings.countries.isEmpty()) { + return; + } + if (!Settings.countriesBlacklist.isEmpty()) { + if (Settings.countriesBlacklist.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) { + event.setMotd(m.send("country_banned")[0]); + } + } + if (Settings.countries.contains(Utils.getCountryCode(event.getAddress().getHostAddress()))) { + event.setMotd(plugin.getServer().getMotd()); + } else { + event.setMotd(m.send("country_banned")[0]); + } + } +} diff --git a/src/main/java/fr/xephi/authme/modules/Module.java b/src/main/java/fr/xephi/authme/modules/Module.java new file mode 100644 index 0000000..00cc68a --- /dev/null +++ b/src/main/java/fr/xephi/authme/modules/Module.java @@ -0,0 +1,24 @@ +package fr.xephi.authme.modules; + +public abstract class Module { + + public abstract String getName(); + + public abstract ModuleType getType(); + + public void load() { + } + + public void unload() { + } + + enum ModuleType { + ACTIONS, + CONVERTERS, + CUSTOM, + EMAILS, + MANAGER, + MYSQL, + REDIS + } +} diff --git a/src/main/java/fr/xephi/authme/modules/ModuleManager.java b/src/main/java/fr/xephi/authme/modules/ModuleManager.java new file mode 100644 index 0000000..181cbbd --- /dev/null +++ b/src/main/java/fr/xephi/authme/modules/ModuleManager.java @@ -0,0 +1,140 @@ +package fr.xephi.authme.modules; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.settings.Settings; + +public class ModuleManager { + + private List modules = new ArrayList<>(); + + public ModuleManager(AuthMe plugin) { + } + + public Module getModule(Module.ModuleType type) { + for (Module m : modules) { + if (m.getType() == type) + return m; + } + return null; + } + + public Module getModule(String name) { + for (Module m : modules) { + if (m.getName().equalsIgnoreCase(name)) + return m; + } + return null; + } + + public boolean isModuleEnabled(Module.ModuleType type) { + for (Module m : modules) { + if (m.getType() == type) + return true; + } + return false; + } + + public boolean isModuleEnabled(String name) { + for (Module m : modules) { + if (m.getName().equalsIgnoreCase(name)) + return true; + } + return false; + } + + public int loadModules() { + File dir = Settings.MODULE_FOLDER; + int count = 0; + if (!dir.isDirectory()) { + dir.mkdirs(); + return count; + } + + File[] files = dir.listFiles(); + if (files == null) { + return count; + } + for (File pathToJar : files) { + JarFile jarFile = null; + URLClassLoader cl = null; + try { + jarFile = new JarFile(pathToJar); + URL[] urls = { new URL("jar:file:" + pathToJar.getAbsolutePath() + "!/") }; + cl = URLClassLoader.newInstance(urls); + + Enumeration e = jarFile.entries(); + while (e.hasMoreElements()) { + JarEntry je = (JarEntry) e.nextElement(); + if (je.isDirectory() || !je.getName().endsWith("Main.class")) { + continue; + } + String className = je.getName().substring(0, je.getName().length() - 6); + className = className.replace('/', '.'); + Class c = cl.loadClass(className); + if (!Module.class.isAssignableFrom(c)) { + continue; + } + + Module mod = (Module) c.newInstance(); + mod.load(); + modules.add(mod); + count++; + break; + } + + } catch (Exception ex) { + ConsoleLogger.writeStackTrace(ex); + ConsoleLogger.showError("Cannot load " + pathToJar.getName() + " jar file !"); + } finally { + try { + if (jarFile != null) { + jarFile.close(); + } + if (cl != null) { + cl.close(); + } + } catch (IOException ignored) { + } + } + } + return count; + } + + public void reloadModules() { + unloadModules(); + loadModules(); + } + + public void unloadModule(String name) { + Iterator it = modules.iterator(); + while (it.hasNext()) { + Module m = it.next(); + if (m.getName().equalsIgnoreCase(name)) { + m.unload(); + it.remove(); + return; + } + } + } + + public void unloadModules() { + Iterator it = modules.iterator(); + while (it.hasNext()) { + it.next().unload(); + it.remove(); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java b/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java new file mode 100644 index 0000000..8dad1ff --- /dev/null +++ b/src/main/java/fr/xephi/authme/plugin/manager/BungeeCordMessage.java @@ -0,0 +1,33 @@ +package fr.xephi.authme.plugin.manager; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.messaging.PluginMessageListener; + +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteStreams; + +import fr.xephi.authme.AuthMe; + +public class BungeeCordMessage implements PluginMessageListener { + + public AuthMe plugin; + + public BungeeCordMessage(AuthMe plugin) { + this.plugin = plugin; + } + + @Override + public void onPluginMessageReceived(String channel, Player player, byte[] message) { + if (!channel.equals("BungeeCord")) { + return; + } + ByteArrayDataInput in = ByteStreams.newDataInput(message); + String subChannel = in.readUTF(); + if (subChannel.equals("IP")) { // We need only the IP channel + String ip = in.readUTF(); + // Put the IP (only the ip not the port) in the hashMap + plugin.realIp.put(player.getName().toLowerCase(), ip); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java b/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java new file mode 100644 index 0000000..10d6e89 --- /dev/null +++ b/src/main/java/fr/xephi/authme/plugin/manager/EssSpawn.java @@ -0,0 +1,41 @@ +package fr.xephi.authme.plugin.manager; + +import java.io.File; + +import org.bukkit.Bukkit; +import org.bukkit.Location; + +import fr.xephi.authme.settings.CustomConfiguration; + +public class EssSpawn extends CustomConfiguration { + + private static EssSpawn spawn; + + public EssSpawn() { + super(new File("." + File.separator + "plugins" + File.separator + "Essentials" + File.separator + "spawn.yml")); + spawn = this; + load(); + } + + public static EssSpawn getInstance() { + if (spawn == null) { + spawn = new EssSpawn(); + } + return spawn; + } + + public Location getLocation() { + try { + if (!this.contains("spawns.default.world")) + return null; + if (this.getString("spawns.default.world").isEmpty() || this.getString("spawns.default.world").equals("")) + return null; + Location location = new Location(Bukkit.getWorld(this.getString("spawns.default.world")), this.getDouble("spawns.default.x"), this.getDouble("spawns.default.y"), + this.getDouble("spawns.default.z"), Float.parseFloat(this.getString("spawns.default.yaw")), Float.parseFloat(this.getString("spawns.default.pitch"))); + return location; + } catch (NullPointerException | NumberFormatException npe) { + return null; + } + } + +} diff --git a/src/main/java/fr/xephi/authme/process/Management.java b/src/main/java/fr/xephi/authme/process/Management.java new file mode 100644 index 0000000..ffc1f00 --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/Management.java @@ -0,0 +1,84 @@ +package fr.xephi.authme.process; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.process.join.AsyncronousJoin; +import fr.xephi.authme.process.login.AsyncronousLogin; +import fr.xephi.authme.process.logout.AsyncronousLogout; +import fr.xephi.authme.process.quit.AsyncronousQuit; +import fr.xephi.authme.process.register.AsyncronousRegister; +import fr.xephi.authme.security.RandomString; +import fr.xephi.authme.settings.Settings; + +/** + * + * @authors Xephi59, + * Possible + * + */ +public class Management { + + public static RandomString rdm = new RandomString(Settings.captchaLength); + public AuthMe plugin; + public PluginManager pm; + + public Management(AuthMe plugin) { + this.plugin = plugin; + this.pm = plugin.getServer().getPluginManager(); + } + + public void performJoin(final Player player) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + new AsyncronousJoin(player, plugin, plugin.database).process(); + } + + }); + } + + public void performLogin(final Player player, final String password, final boolean forceLogin) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + new AsyncronousLogin(player, password, forceLogin, plugin, plugin.database).process(); + } + }); + } + + public void performLogout(final Player player) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + new AsyncronousLogout(player, plugin, plugin.database).process(); + } + }); + } + + public void performQuit(final Player player, final boolean isKick) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + new AsyncronousQuit(player, plugin, plugin.database, isKick).process(); + } + + }); + } + + public void performRegister(final Player player, final String password, final String email) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + new AsyncronousRegister(player, password, email, plugin, plugin.database).process(); + } + }); + } +} diff --git a/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java b/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java new file mode 100644 index 0000000..0dab1bc --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/join/AsyncronousJoin.java @@ -0,0 +1,296 @@ +package fr.xephi.authme.process.join; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.FirstSpawnTeleportEvent; +import fr.xephi.authme.events.ProtectInventoryEvent; +import fr.xephi.authme.events.SpawnTeleportEvent; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.settings.Spawn; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; + +public class AsyncronousJoin { + + private Messages m = Messages.getInstance(); + protected DataSource database; + protected String name; + protected Player player; + protected AuthMe plugin; + + public AsyncronousJoin(Player player, AuthMe plugin, DataSource database) { + this.player = player; + this.plugin = plugin; + this.database = database; + this.name = player.getName().toLowerCase(); + } + + public void process() { + if (AuthMePlayerListener.gameMode.containsKey(name)) + AuthMePlayerListener.gameMode.remove(name); + AuthMePlayerListener.gameMode.putIfAbsent(name, player.getGameMode()); + BukkitScheduler sched = plugin.getServer().getScheduler(); + + if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { + return; + } + + if (plugin.ess != null && Settings.disableSocialSpy) { + plugin.ess.getUser(player).setSocialSpyEnabled(false); + } + + final String ip = plugin.getIP(player); + if (Settings.isAllowRestrictedIp && !Settings.getRestrictedIp(name, ip)) { + final GameMode gM = AuthMePlayerListener.gameMode.get(name); + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); + player.setGameMode(gM); + player.kickPlayer("You are not the Owner of this account, please try another name!"); + if (Settings.banUnsafeIp) + plugin.getServer().banIP(ip); + } + + }); + return; + } + if (Settings.getMaxJoinPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !ip.equalsIgnoreCase("127.0.0.1") && !ip.equalsIgnoreCase("localhost")) { + if (plugin.hasJoinedIp(player.getName(), ip)) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.kickPlayer("A player with the same IP is already in game!"); + } + + }); + return; + } + } + final Location spawnLoc = plugin.getSpawnLocation(player); + final boolean isAuthAvailable = database.isAuthAvailable(name); + if (isAuthAvailable) { + if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); + Utils.forceGM(player); + } + + }); + } + if (!Settings.noTeleport) + if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (player.isOnline() && tpEvent.getTo() != null) { + if (tpEvent.getTo().getWorld() != null) + player.teleport(tpEvent.getTo()); + } + } + } + + }); + } + placePlayerSafely(player, spawnLoc); + LimboCache.getInstance().updateLimboPlayer(player); + // protect inventory + if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { + ProtectInventoryEvent ev = new ProtectInventoryEvent(player); + plugin.getServer().getPluginManager().callEvent(ev); + if (ev.isCancelled()) { + plugin.inventoryProtector.sendInventoryPacket(player); + if (!Settings.noConsoleSpam) + ConsoleLogger.info("ProtectInventoryEvent has been cancelled for " + player.getName() + " ..."); + } + } + } else { + if (Settings.isForceSurvivalModeEnabled && !Settings.forceOnlyAfterLogin) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + AuthMePlayerListener.causeByAuthMe.putIfAbsent(name, true); + Utils.forceGM(player); + } + + }); + } + if (!Settings.unRegisteredGroup.isEmpty()) { + Utils.setGroup(player, Utils.GroupType.UNREGISTERED); + } + if (!Settings.isForcedRegistrationEnabled) { + return; + } + if (!Settings.noTeleport) + if (!needFirstspawn() && Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) { + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + @Override + public void run() { + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnLoc, PlayerCache.getInstance().isAuthenticated(name)); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (player.isOnline() && tpEvent.getTo() != null) { + if (tpEvent.getTo().getWorld() != null) + player.teleport(tpEvent.getTo()); + } + } + } + + }); + } + + } + String[] msg; + if (Settings.emailRegistration) { + msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_email_msg"); + } else { + msg = isAuthAvailable ? m.send("login_msg") : m.send("reg_msg"); + } + int time = Settings.getRegistrationTimeout * 20; + int msgInterval = Settings.getWarnMessageInterval; + if (time != 0) { + BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time); + if (!LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().addLimboPlayer(player); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + } + if (!LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().addLimboPlayer(player); + if (isAuthAvailable) { + Utils.setGroup(player, GroupType.NOTLOGGEDIN); + } else { + Utils.setGroup(player, GroupType.UNREGISTERED); + } + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + if (player.isOp()) + player.setOp(false); + if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { + player.setAllowFlight(true); + player.setFlying(true); + } + player.setNoDamageTicks(Settings.getRegistrationTimeout * 20); + if (Settings.useEssentialsMotd) + player.performCommand("motd"); + if (Settings.applyBlindEffect) + player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + player.setWalkSpeed(0.0f); + player.setFlySpeed(0.0f); + } + } + + }); + if (Settings.isSessionsEnabled && isAuthAvailable && (PlayerCache.getInstance().isAuthenticated(name) || database.isLogged(name))) { + if (plugin.sessions.containsKey(name)) + plugin.sessions.get(name).cancel(); + plugin.sessions.remove(name); + PlayerAuth auth = database.getAuth(name); + if (auth != null && auth.getIp().equals(ip)) { + m.send(player, "valid_session"); + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + plugin.management.performLogin(player, "dontneed", true); + } else if (Settings.sessionExpireOnIpChange) { + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + m.send(player, "invalid_session"); + } + return; + } + BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, msgInterval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + } + + private boolean needFirstspawn() { + if (player.hasPlayedBefore()) + return false; + if (Spawn.getInstance().getFirstSpawn() == null || Spawn.getInstance().getFirstSpawn().getWorld() == null) + return false; + FirstSpawnTeleportEvent tpEvent = new FirstSpawnTeleportEvent(player, player.getLocation(), Spawn.getInstance().getFirstSpawn()); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (player.isOnline() && tpEvent.getTo() != null && tpEvent.getTo().getWorld() != null) { + final Location fLoc = tpEvent.getTo(); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.teleport(fLoc); + } + + }); + } + } + return true; + + } + + private void placePlayerSafely(final Player player, final Location spawnLoc) { + Location loc = null; + if (spawnLoc == null) + return; + if (!Settings.noTeleport) + return; + if (Settings.isTeleportToSpawnEnabled || (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName()))) + return; + if (!player.hasPlayedBefore()) + return; + Block b = player.getLocation().getBlock(); + if (b.getType() == Material.PORTAL || b.getType() == Material.ENDER_PORTAL) { + m.send(player, "unsafe_spawn"); + if (spawnLoc.getWorld() != null) + loc = spawnLoc; + } else { + Block c = player.getLocation().add(0D, 1D, 0D).getBlock(); + if (c.getType() == Material.PORTAL || c.getType() == Material.ENDER_PORTAL) { + m.send(player, "unsafe_spawn"); + if (spawnLoc.getWorld() != null) + loc = spawnLoc; + } + } + if (loc != null) { + final Location floc = loc; + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + player.teleport(floc); + } + + }); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java b/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java new file mode 100644 index 0000000..272a0c6 --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/login/AsyncronousLogin.java @@ -0,0 +1,246 @@ +package fr.xephi.authme.process.login; + +import java.util.Date; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.security.RandomString; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.task.MessageTask; + +public class AsyncronousLogin { + + private static RandomString rdm = new RandomString(Settings.captchaLength); + private DataSource database; + private Messages m = Messages.getInstance(); + private AuthMe plugin; + protected boolean forceLogin; + protected String name; + protected String password; + protected Player player; + protected String realName; + + public AsyncronousLogin(Player player, String password, boolean forceLogin, AuthMe plugin, DataSource data) { + this.player = player; + this.password = password; + name = player.getName().toLowerCase(); + realName = player.getName(); + this.forceLogin = forceLogin; + this.plugin = plugin; + this.database = data; + } + + public void displayOtherAccounts(PlayerAuth auth, Player p) { + if (!Settings.displayOtherAccounts) { + return; + } + if (auth == null) { + return; + } + List auths = this.database.getAllAuthsByName(auth); + // List uuidlist = + // plugin.otherAccounts.getAllPlayersByUUID(player.getUniqueId()); + if (auths.isEmpty()) { + return; + } + if (auths.size() == 1) { + return; + } + StringBuilder message = new StringBuilder("[AuthMe] "); + // String uuidaccounts = + // "[AuthMe] PlayerNames has %size% links to this UUID : "; + int i = 0; + for (String account : auths) { + i++; + message.append(account); + if (i != auths.size()) { + message.append(", "); + } else { + message.append("."); + } + } + /* + * TODO: Active uuid system i = 0; for (String account : uuidlist) { + * i++; uuidaccounts = uuidaccounts + account; if (i != auths.size()) { + * uuidaccounts = uuidaccounts + ", "; } else { uuidaccounts = + * uuidaccounts + "."; } } + */ + for (Player player : Utils.getOnlinePlayers()) { + if (plugin.authmePermissible(player, "authme.seeOtherAccounts")) { + player.sendMessage("[AuthMe] The player " + auth.getNickname() + " has " + auths.size() + " accounts"); + player.sendMessage(message.toString()); + // player.sendMessage(uuidaccounts.replace("%size%", + // ""+uuidlist.size())); + } + } + } + + public void process() { + PlayerAuth pAuth = preAuth(); + if (pAuth == null || needsCaptcha()) + return; + + String hash = pAuth.getHash(); + String email = pAuth.getEmail(); + boolean passwordVerified = true; + if (!forceLogin) + try { + passwordVerified = PasswordSecurity.comparePasswordWithHash(password, hash, realName); + } catch (Exception ex) { + ConsoleLogger.showError(ex.getMessage()); + m.send(player, "error"); + return; + } + if (passwordVerified && player.isOnline()) { + PlayerAuth auth = new PlayerAuth(name, hash, getIP(), new Date().getTime(), email, realName); + database.updateSession(auth); + + if (Settings.useCaptcha) { + if (plugin.captcha.containsKey(name)) { + plugin.captcha.remove(name); + } + if (plugin.cap.containsKey(name)) { + plugin.cap.remove(name); + } + } + + player.setNoDamageTicks(0); + if (!forceLogin) + m.send(player, "login"); + + displayOtherAccounts(auth, player); + + if (Settings.recallEmail) { + if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com")) + m.send(player, "add_email"); + } + + if (!Settings.noConsoleSpam) + ConsoleLogger.info(realName + " logged in!"); + + // makes player isLoggedin via API + PlayerCache.getInstance().addPlayer(auth); + database.setLogged(name); + plugin.otherAccounts.addPlayer(player.getUniqueId()); + + // As the scheduling executes the Task most likely after the current + // task, we schedule it in the end + // so that we can be sure, and have not to care if it might be + // processed in other order. + ProcessSyncronousPlayerLogin syncronousPlayerLogin = new ProcessSyncronousPlayerLogin(player, plugin, database); + if (syncronousPlayerLogin.getLimbo() != null) { + if (syncronousPlayerLogin.getLimbo().getTimeoutTaskId() != null) + syncronousPlayerLogin.getLimbo().getTimeoutTaskId().cancel(); + if (syncronousPlayerLogin.getLimbo().getMessageTaskId() != null) + syncronousPlayerLogin.getLimbo().getMessageTaskId().cancel(); + } + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, syncronousPlayerLogin); + } else if (player.isOnline()) { + if (!Settings.noConsoleSpam) + ConsoleLogger.info(realName + " used the wrong password"); + if (Settings.isKickOnWrongPasswordEnabled) { + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + if (AuthMePlayerListener.gameMode != null && AuthMePlayerListener.gameMode.containsKey(name)) { + player.setGameMode(AuthMePlayerListener.gameMode.get(name)); + } + player.kickPlayer(m.send("wrong_pwd")[0]); + } + }); + } else { + m.send(player, "wrong_pwd"); + } + } else { + ConsoleLogger.showError("Player " + name + " wasn't online during login process, aborted... "); + } + } + + protected String getIP() { + return plugin.getIP(player); + } + + protected boolean needsCaptcha() { + if (Settings.useCaptcha) { + if (!plugin.captcha.containsKey(name)) { + plugin.captcha.putIfAbsent(name, 1); + } else { + int i = plugin.captcha.get(name) + 1; + plugin.captcha.remove(name); + plugin.captcha.putIfAbsent(name, i); + } + if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) { + plugin.cap.put(name, rdm.nextString()); + for (String s : m.send("usage_captcha")) { + player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)).replace("", plugin.cap.get(name))); + } + return true; + } else if (plugin.captcha.containsKey(name) && plugin.captcha.get(name) >= Settings.maxLoginTry) { + plugin.captcha.remove(name); + plugin.cap.remove(name); + } + } + return false; + } + + /** + * Checks the precondition for authentication (like user known) and returns + * the playerAuth-State + */ + protected PlayerAuth preAuth() { + if (PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "logged_in"); + return null; + } + if (!database.isAuthAvailable(name)) { + m.send(player, "user_unknown"); + if (LimboCache.getInstance().hasLimboPlayer(name)) { + LimboCache.getInstance().getLimboPlayer(name).getMessageTaskId().cancel(); + String[] msg; + if (Settings.emailRegistration) { + msg = m.send("reg_email_msg"); + } else { + msg = m.send("reg_msg"); + } + BukkitTask msgT = Bukkit.getScheduler().runTaskAsynchronously(plugin, new MessageTask(plugin, name, msg, Settings.getWarnMessageInterval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + } + return null; + } + if (Settings.getMaxLoginPerIp > 0 && !plugin.authmePermissible(player, "authme.allow2accounts") && !getIP().equalsIgnoreCase("127.0.0.1") && !getIP().equalsIgnoreCase("localhost")) { + if (plugin.isLoggedIp(name, getIP())) { + m.send(player, "logged_in"); + return null; + } + } + PlayerAuth pAuth = database.getAuth(name); + if (pAuth == null) { + m.send(player, "user_unknown"); + return null; + } + if (!Settings.getMySQLColumnGroup.isEmpty() && pAuth.getGroupId() == Settings.getNonActivatedGroup) { + m.send(player, "vb_nonActiv"); + return null; + } + AuthMeAsyncPreLoginEvent event = new AuthMeAsyncPreLoginEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.canLogin()) + return null; + return pAuth; + } +} diff --git a/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java new file mode 100644 index 0000000..9b473cf --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/login/ProcessSyncronousPlayerLogin.java @@ -0,0 +1,205 @@ +package fr.xephi.authme.process.login; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; +import org.bukkit.potion.PotionEffectType; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.backup.JsonCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.AuthMeTeleportEvent; +import fr.xephi.authme.events.LoginEvent; +import fr.xephi.authme.events.RestoreInventoryEvent; +import fr.xephi.authme.events.SpawnTeleportEvent; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.settings.Settings; + +public class ProcessSyncronousPlayerLogin implements Runnable { + + private PlayerAuth auth; + private DataSource database; + private LimboPlayer limbo; + private String name; + private Player player; + private JsonCache playerCache; + private AuthMe plugin; + private PluginManager pm; + + public ProcessSyncronousPlayerLogin(Player player, AuthMe plugin, DataSource data) { + this.plugin = plugin; + this.database = data; + this.pm = plugin.getServer().getPluginManager(); + this.player = player; + this.name = player.getName().toLowerCase(); + this.limbo = LimboCache.getInstance().getLimboPlayer(name); + this.auth = database.getAuth(name); + this.playerCache = new JsonCache(); + } + + public LimboPlayer getLimbo() { + return limbo; + } + + @Override + public void run() { + // Limbo contains the State of the Player before /login + if (limbo != null) { + // Op & Flying + restoreOpState(); + + /* + * Restore Inventories and GameMode We need to restore them before + * teleport the player Cause in AuthMePlayerListener, we call + * ProtectInventoryEvent after Teleporting Also it's the current + * world inventory ! + */ + player.setGameMode(limbo.getGameMode()); + // Inventory - Make it after restore GameMode , cause we need to + // restore the + // right inventory in the right gamemode + if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { + restoreInventory(); + } + if (Settings.forceOnlyAfterLogin) { + player.setGameMode(GameMode.SURVIVAL); + } + + if (!Settings.noTeleport) { + // Teleport + if (Settings.isTeleportToSpawnEnabled && !Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) { + if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) { + packQuitLocation(); + } else { + teleportBackFromSpawn(); + } + } else if (Settings.isForceSpawnLocOnJoinEnabled && Settings.getForcedWorlds.contains(player.getWorld().getName())) { + teleportToSpawn(); + } else if (Settings.isSaveQuitLocationEnabled && auth.getQuitLocY() != 0) { + packQuitLocation(); + } else { + teleportBackFromSpawn(); + } + } + + // Re-Force Survival GameMode if we need due to world change + // specification + if (Settings.isForceSurvivalModeEnabled) + Utils.forceGM(player); + + // Restore Permission Group + Utils.setGroup(player, GroupType.LOGGEDIN); + + // Cleanup no longer used temporary data + LimboCache.getInstance().deleteLimboPlayer(name); + if (playerCache.doesCacheExist(player)) { + playerCache.removeCache(player); + } + } + + // We can now display the join message + if (AuthMePlayerListener.joinMessage.containsKey(name) && AuthMePlayerListener.joinMessage.get(name) != null && !AuthMePlayerListener.joinMessage.get(name).isEmpty()) { + for (Player p : Utils.getOnlinePlayers()) { + if (p.isOnline()) + p.sendMessage(AuthMePlayerListener.joinMessage.get(name)); + } + AuthMePlayerListener.joinMessage.remove(name); + } + + if (Settings.applyBlindEffect) + player.removePotionEffect(PotionEffectType.BLINDNESS); + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + player.setWalkSpeed(0.2f); + player.setFlySpeed(0.1f); + } + + // The Loginevent now fires (as intended) after everything is processed + Bukkit.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); + player.saveData(); + + // Login is finish, display welcome message + if (Settings.useWelcomeMessage) + if (Settings.broadcastWelcomeMessage) { + for (String s : Settings.welcomeMsg) { + Bukkit.getServer().broadcastMessage(plugin.replaceAllInfos(s, player)); + } + } else { + for (String s : Settings.welcomeMsg) { + player.sendMessage(plugin.replaceAllInfos(s, player)); + } + } + + // Login is now finish , we can force all commands + forceCommands(); + } + + protected void forceCommands() { + for (String command : Settings.forceCommands) { + try { + player.performCommand(command.replace("%p", player.getName())); + } catch (Exception ignored) { + } + } + for (String command : Settings.forceCommandsAsConsole) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName())); + } + } + + protected void packQuitLocation() { + Utils.packCoords(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(), player); + } + + protected void restoreInventory() { + RestoreInventoryEvent event = new RestoreInventoryEvent(player); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + plugin.inventoryProtector.sendInventoryPacket(player); + } + } + + protected void restoreOpState() { + player.setOp(limbo.getOperator()); + if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { + if (limbo.getGameMode() != GameMode.CREATIVE) { + player.setAllowFlight(limbo.isFlying()); + player.setFlying(limbo.isFlying()); + } else { + player.setAllowFlight(false); + player.setFlying(false); + } + } + } + + protected void teleportBackFromSpawn() { + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, limbo.getLoc()); + pm.callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + Location fLoc = tpEvent.getTo(); + if (!fLoc.getChunk().isLoaded()) { + fLoc.getChunk().load(); + } + player.teleport(fLoc); + } + } + + protected void teleportToSpawn() { + Location spawnL = plugin.getSpawnLocation(player); + SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawnL, true); + pm.callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + Location fLoc = tpEvent.getTo(); + if (!fLoc.getChunk().isLoaded()) { + fLoc.getChunk().load(); + } + player.teleport(fLoc); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java b/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java new file mode 100644 index 0000000..952a5dd --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/logout/AsyncronousLogout.java @@ -0,0 +1,80 @@ +package fr.xephi.authme.process.logout; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitScheduler; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.Utils.GroupType; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.events.AuthMeTeleportEvent; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class AsyncronousLogout { + + private Messages m = Messages.getInstance(); + protected boolean canLogout = true; + protected DataSource database; + protected String name; + protected Player player; + protected AuthMe plugin; + + public AsyncronousLogout(Player player, AuthMe plugin, DataSource database) { + this.player = player; + this.plugin = plugin; + this.database = database; + this.name = player.getName().toLowerCase(); + } + + public void process() { + preLogout(); + if (!canLogout) + return; + final Player p = player; + BukkitScheduler sched = p.getServer().getScheduler(); + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + database.updateSession(auth); + auth.setQuitLocX(p.getLocation().getX()); + auth.setQuitLocY(p.getLocation().getY()); + auth.setQuitLocZ(p.getLocation().getZ()); + auth.setWorld(p.getWorld().getName()); + database.updateQuitLoc(auth); + + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + Location spawnLoc = plugin.getSpawnLocation(p); + final AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(p, spawnLoc); + sched.scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (tpEvent.getTo() != null) + p.teleport(tpEvent.getTo()); + } + } + }); + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().deleteLimboPlayer(name); + LimboCache.getInstance().addLimboPlayer(player); + Utils.setGroup(player, GroupType.NOTLOGGEDIN); + + sched.scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerLogout(p, plugin)); + } + + private void preLogout() { + if (!PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "not_logged_in"); + canLogout = false; + } + } +} diff --git a/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java new file mode 100644 index 0000000..e327c63 --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/logout/ProcessSyncronousPlayerLogout.java @@ -0,0 +1,65 @@ +package fr.xephi.authme.process.logout; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.events.LogoutEvent; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; + +public class ProcessSyncronousPlayerLogout implements Runnable { + + private Messages m = Messages.getInstance(); + protected String name; + protected Player player; + protected AuthMe plugin; + + public ProcessSyncronousPlayerLogout(Player player, AuthMe plugin) { + this.player = player; + this.plugin = plugin; + this.name = player.getName().toLowerCase(); + } + + @Override + public void run() { + if (plugin.sessions.containsKey(name)) + plugin.sessions.get(name).cancel(); + plugin.sessions.remove(name); + int delay = Settings.getRegistrationTimeout * 20; + int interval = Settings.getWarnMessageInterval; + BukkitScheduler sched = player.getServer().getScheduler(); + if (delay != 0) { + BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + } + BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + if (player.isInsideVehicle() && player.getVehicle() != null) + player.getVehicle().eject(); + if (Settings.applyBlindEffect) + player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2)); + player.setOp(false); + if (!Settings.isMovementAllowed) { + player.setAllowFlight(true); + player.setFlying(true); + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + player.setFlySpeed(0.0f); + player.setWalkSpeed(0.0f); + } + } + // Player is now logout... Time to fire event ! + Bukkit.getServer().getPluginManager().callEvent(new LogoutEvent(player)); + m.send(player, "logout"); + ConsoleLogger.info(player.getName() + " logged out"); + } + +} diff --git a/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java b/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java new file mode 100644 index 0000000..db6740b --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/quit/AsyncronousQuit.java @@ -0,0 +1,92 @@ +package fr.xephi.authme.process.quit; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.listener.AuthMePlayerListener; +import fr.xephi.authme.settings.Settings; + +public class AsyncronousQuit { + + private boolean isFlying = false; + private boolean isKick = false; + private boolean isOp = false; + private String name; + private boolean needToChange = false; + protected DataSource database; + protected Player player; + protected AuthMe plugin; + + public AsyncronousQuit(Player p, AuthMe plugin, DataSource database, boolean isKick) { + this.player = p; + this.plugin = plugin; + this.database = database; + this.name = p.getName().toLowerCase(); + this.isKick = isKick; + } + + public void process() { + if (player == null) + return; + if (Utils.isNPC(player) || Utils.isUnrestricted(player)) { + return; + } + + String ip = plugin.getIP(player); + + if (PlayerCache.getInstance().isAuthenticated(name)) { + if (Settings.isSaveQuitLocationEnabled && database.isAuthAvailable(name)) { + Location loc = player.getLocation(); + PlayerAuth auth = new PlayerAuth(name, loc.getX(), loc.getY(), loc.getZ(), loc.getWorld().getName(), player.getName()); + database.updateQuitLoc(auth); + } + PlayerAuth auth = new PlayerAuth(name, ip, System.currentTimeMillis(), player.getName()); + database.updateSession(auth); + } + + if (LimboCache.getInstance().hasLimboPlayer(name)) { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (limbo.getGroup() != null && !limbo.getGroup().equals("")) + Utils.addNormal(player, limbo.getGroup()); + needToChange = true; + isOp = limbo.getOperator(); + isFlying = limbo.isFlying(); + if (limbo.getTimeoutTaskId() != null) + limbo.getTimeoutTaskId().cancel(); + if (limbo.getMessageTaskId() != null) + limbo.getMessageTaskId().cancel(); + LimboCache.getInstance().deleteLimboPlayer(name); + } + if (Settings.isSessionsEnabled && !isKick) { + if (Settings.getSessionTimeout != 0) { + BukkitTask task = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() { + + @Override + public void run() { + PlayerCache.getInstance().removePlayer(name); + if (database.isLogged(name)) + database.setUnlogged(name); + plugin.sessions.remove(name); + } + + }, Settings.getSessionTimeout * 20 * 60); + plugin.sessions.put(name, task); + } + } else { + PlayerCache.getInstance().removePlayer(name); + database.setUnlogged(name); + } + + AuthMePlayerListener.gameMode.remove(name); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new ProcessSyncronousPlayerQuit(plugin, player, isOp, isFlying, needToChange)); + } +} diff --git a/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java b/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java new file mode 100644 index 0000000..78ab268 --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/quit/ProcessSyncronousPlayerQuit.java @@ -0,0 +1,40 @@ +package fr.xephi.authme.process.quit; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.settings.Settings; + +public class ProcessSyncronousPlayerQuit implements Runnable { + + protected boolean isFlying; + protected boolean isOp; + protected boolean needToChange; + protected Player player; + protected AuthMe plugin; + + public ProcessSyncronousPlayerQuit(AuthMe plugin, Player player, boolean isOp, boolean isFlying, boolean needToChange) { + this.plugin = plugin; + this.player = player; + this.isOp = isOp; + this.isFlying = isFlying; + this.needToChange = needToChange; + } + + @Override + public void run() { + + if (needToChange) { + player.setOp(isOp); + if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { + player.setAllowFlight(isFlying); + player.setFlying(isFlying); + } + } + try { + player.getVehicle().eject(); + } catch (Exception e) { + } + } +} diff --git a/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java b/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java new file mode 100644 index 0000000..1bba40d --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/register/AsyncronousRegister.java @@ -0,0 +1,160 @@ +package fr.xephi.authme.process.register; + +import java.security.NoSuchAlgorithmException; +import java.util.Date; + +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class AsyncronousRegister { + + private final DataSource database; + private final Messages m = Messages.getInstance(); + private final AuthMe plugin; + protected boolean allowRegister; + protected String email = ""; + protected String name; + protected String password; + protected Player player; + + public AsyncronousRegister(final Player player, final String password, final String email, final AuthMe plugin, final DataSource data) { + this.player = player; + this.password = password; + name = player.getName().toLowerCase(); + this.email = email; + this.plugin = plugin; + this.database = data; + this.allowRegister = true; + } + + public void process() { + preRegister(); + if (!allowRegister) { + return; + } + if (!email.isEmpty() && !email.equals("")) { + if (Settings.getmaxRegPerEmail > 0) { + if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) { + m.send(player, "max_reg"); + return; + } + } + emailRegister(); + return; + } + passwordRegister(); + } + + protected void emailRegister() { + if (Settings.getmaxRegPerEmail > 0) { + if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByEmail(email).size() >= Settings.getmaxRegPerEmail) { + m.send(player, "max_reg"); + return; + } + } + PlayerAuth auth; + try { + final String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); + auth = new PlayerAuth(name, hashnew, getIp(), 0, (int) player.getLocation().getX(), (int) player.getLocation().getY(), (int) player.getLocation().getZ(), + player.getLocation().getWorld().getName(), email, player.getName()); + } catch (final NoSuchAlgorithmException e) { + ConsoleLogger.showError(e.getMessage()); + m.send(player, "error"); + return; + } + if (PasswordSecurity.userSalt.containsKey(name)) { + auth.setSalt(PasswordSecurity.userSalt.get(name)); + } + database.saveAuth(auth); + database.updateEmail(auth); + database.updateSession(auth); + final ProcessSyncronousEmailRegister syncronous = new ProcessSyncronousEmailRegister(player, plugin); + plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous); + } + + protected String getIp() { + return plugin.getIP(player); + } + + protected void passwordRegister() { + PlayerAuth auth; + String hash; + try { + hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name); + } catch (final NoSuchAlgorithmException e) { + ConsoleLogger.showError(e.getMessage()); + m.send(player, "error"); + return; + } + if (Settings.getMySQLColumnSalt.isEmpty() && !PasswordSecurity.userSalt.containsKey(name)) { + auth = new PlayerAuth(name, hash, getIp(), new Date().getTime(), "your@email.com", player.getName()); + } else { + auth = new PlayerAuth(name, hash, PasswordSecurity.userSalt.get(name), getIp(), new Date().getTime(), player.getName()); + } + if (!database.saveAuth(auth)) { + m.send(player, "error"); + return; + } + if (!Settings.forceRegLogin) { + PlayerCache.getInstance().addPlayer(auth); + database.setLogged(name); + } + plugin.otherAccounts.addPlayer(player.getUniqueId()); + final ProcessSyncronousPasswordRegister syncronous = new ProcessSyncronousPasswordRegister(player, plugin); + plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, syncronous); + } + + protected void preRegister() { + final String lowpass = password.toLowerCase(); + if (PlayerCache.getInstance().isAuthenticated(name)) { + m.send(player, "logged_in"); + allowRegister = false; + } + + else if (!Settings.isRegistrationEnabled) { + m.send(player, "reg_disabled"); + allowRegister = false; + } + + else if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") + || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) { + m.send(player, "password_error"); + allowRegister = false; + } + + else if (lowpass.equalsIgnoreCase(player.getName())) { + m.send(player, "password_error_nick"); + allowRegister = false; + } + + else if (password.length() < Settings.getPasswordMinLen || password.length() > Settings.passwordMaxLength) { + m.send(player, "pass_len"); + allowRegister = false; + } + + else if (!Settings.unsafePasswords.isEmpty() && Settings.unsafePasswords.contains(password.toLowerCase())) { + m.send(player, "password_error_unsafe"); + allowRegister = false; + } else if (database.isAuthAvailable(name)) { + m.send(player, "user_regged"); + allowRegister = false; + } + + else if (Settings.getmaxRegPerIp > 0) { + if (!plugin.authmePermissible(player, "authme.allow2accounts") && database.getAllAuthsByIp(getIp()).size() >= Settings.getmaxRegPerIp && !getIp().equalsIgnoreCase("127.0.0.1") + && !getIp().equalsIgnoreCase("localhost")) { + m.send(player, "max_reg"); + allowRegister = false; + } + } + + } +} diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java new file mode 100644 index 0000000..9cb63f0 --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousEmailRegister.java @@ -0,0 +1,57 @@ +package fr.xephi.authme.process.register; + +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; + +public class ProcessSyncronousEmailRegister implements Runnable { + + private Messages m = Messages.getInstance(); + private AuthMe plugin; + protected String name; + protected Player player; + + public ProcessSyncronousEmailRegister(Player player, AuthMe plugin) { + this.player = player; + this.name = player.getName().toLowerCase(); + this.plugin = plugin; + } + + @Override + public void run() { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (!Settings.getRegisteredGroup.isEmpty()) { + Utils.setGroup(player, Utils.GroupType.REGISTERED); + } + m.send(player, "vb_nonActiv"); + int time = Settings.getRegistrationTimeout * 20; + int msgInterval = Settings.getWarnMessageInterval; + + BukkitScheduler sched = plugin.getServer().getScheduler(); + if (time != 0 && limbo != null) { + limbo.getTimeoutTaskId().cancel(); + BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), time); + limbo.setTimeoutTaskId(id); + } + if (limbo != null) { + limbo.getMessageTaskId().cancel(); + BukkitTask nwMsg = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), msgInterval)); + limbo.setMessageTaskId(nwMsg); + } + + player.saveData(); + if (!Settings.noConsoleSpam) + ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player)); + } + +} diff --git a/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java new file mode 100644 index 0000000..2143d74 --- /dev/null +++ b/src/main/java/fr/xephi/authme/process/register/ProcessSyncronousPasswordRegister.java @@ -0,0 +1,159 @@ +package fr.xephi.authme.process.register; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.limbo.LimboCache; +import fr.xephi.authme.cache.limbo.LimboPlayer; +import fr.xephi.authme.events.AuthMeTeleportEvent; +import fr.xephi.authme.events.LoginEvent; +import fr.xephi.authme.events.RegisterTeleportEvent; +import fr.xephi.authme.events.RestoreInventoryEvent; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; +import fr.xephi.authme.task.MessageTask; +import fr.xephi.authme.task.TimeoutTask; + +public class ProcessSyncronousPasswordRegister implements Runnable { + + private Messages m = Messages.getInstance(); + private AuthMe plugin; + protected String name; + protected Player player; + + public ProcessSyncronousPasswordRegister(Player player, AuthMe plugin) { + this.player = player; + this.name = player.getName().toLowerCase(); + this.plugin = plugin; + } + + @Override + public void run() { + LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name); + if (limbo != null) { + player.setGameMode(limbo.getGameMode()); + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + Location loca = plugin.getSpawnLocation(player); + RegisterTeleportEvent tpEvent = new RegisterTeleportEvent(player, loca); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + + if (Settings.protectInventoryBeforeLogInEnabled && plugin.inventoryProtector != null) { + RestoreInventoryEvent event = new RestoreInventoryEvent(player); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + plugin.inventoryProtector.sendInventoryPacket(player); + } + } + + limbo.getTimeoutTaskId().cancel(); + limbo.getMessageTaskId().cancel(); + LimboCache.getInstance().deleteLimboPlayer(name); + } + + if (!Settings.getRegisteredGroup.isEmpty()) { + Utils.setGroup(player, Utils.GroupType.REGISTERED); + } + m.send(player, "registered"); + if (!Settings.getmailAccount.isEmpty()) + m.send(player, "add_email"); + if (player.getGameMode() != GameMode.CREATIVE && !Settings.isMovementAllowed) { + player.setAllowFlight(false); + player.setFlying(false); + } + if (Settings.applyBlindEffect) + player.removePotionEffect(PotionEffectType.BLINDNESS); + if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) { + player.setWalkSpeed(0.2f); + player.setFlySpeed(0.1f); + } + // The LoginEvent now fires (as intended) after everything is processed + plugin.getServer().getPluginManager().callEvent(new LoginEvent(player, true)); + player.saveData(); + + if (!Settings.noConsoleSpam) + ConsoleLogger.info(player.getName() + " registered " + plugin.getIP(player)); + + // Kick Player after Registration is enabled, kick the player + if (Settings.forceRegKick) { + player.kickPlayer(m.send("registered")[0]); + return; + } + + // Request Login after Registration + if (Settings.forceRegLogin) { + forceLogin(player); + return; + } + + // Register is finish and player is logged, display welcome message + if (Settings.useWelcomeMessage) + if (Settings.broadcastWelcomeMessage) { + for (String s : Settings.welcomeMsg) { + plugin.getServer().broadcastMessage(plugin.replaceAllInfos(s, player)); + } + } else { + for (String s : Settings.welcomeMsg) { + player.sendMessage(plugin.replaceAllInfos(s, player)); + } + } + + // Register is now finish , we can force all commands + forceCommands(); + } + + protected void forceCommands() { + for (String command : Settings.forceRegisterCommands) { + try { + player.performCommand(command.replace("%p", player.getName())); + } catch (Exception ignored) { + } + } + for (String command : Settings.forceRegisterCommandsAsConsole) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), command.replace("%p", player.getName())); + } + } + + protected void forceLogin(Player player) { + if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { + Location spawnLoc = plugin.getSpawnLocation(player); + AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawnLoc); + plugin.getServer().getPluginManager().callEvent(tpEvent); + if (!tpEvent.isCancelled()) { + if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) { + tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load(); + } + player.teleport(tpEvent.getTo()); + } + } + if (LimboCache.getInstance().hasLimboPlayer(name)) + LimboCache.getInstance().deleteLimboPlayer(name); + LimboCache.getInstance().addLimboPlayer(player); + int delay = Settings.getRegistrationTimeout * 20; + int interval = Settings.getWarnMessageInterval; + BukkitScheduler sched = plugin.getServer().getScheduler(); + if (delay != 0) { + BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay); + LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id); + } + BukkitTask msgT = sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("login_msg"), interval)); + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(msgT); + if (player.isInsideVehicle() && player.getVehicle() != null) { + player.getVehicle().eject(); + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/HashAlgorithm.java b/src/main/java/fr/xephi/authme/security/HashAlgorithm.java new file mode 100644 index 0000000..ab76d12 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/HashAlgorithm.java @@ -0,0 +1,46 @@ +package fr.xephi.authme.security; + +import org.apache.commons.lang.ObjectUtils.Null; + +public enum HashAlgorithm { + + BCRYPT(fr.xephi.authme.security.crypts.BCRYPT.class), + BCRYPT2Y(fr.xephi.authme.security.crypts.BCRYPT2Y.class), + CRAZYCRYPT1(fr.xephi.authme.security.crypts.CRAZYCRYPT1.class), + CUSTOM(Null.class), + DOUBLEMD5(fr.xephi.authme.security.crypts.DOUBLEMD5.class), + IPB3(fr.xephi.authme.security.crypts.IPB3.class), + JOOMLA(fr.xephi.authme.security.crypts.JOOMLA.class), + MD5(fr.xephi.authme.security.crypts.MD5.class), + MD5VB(fr.xephi.authme.security.crypts.MD5VB.class), + MYBB(fr.xephi.authme.security.crypts.MYBB.class), + PBKDF2(fr.xephi.authme.security.crypts.CryptPBKDF2.class), + PBKDF2DJANGO(fr.xephi.authme.security.crypts.CryptPBKDF2Django.class), + PHPBB(fr.xephi.authme.security.crypts.PHPBB.class), + PHPFUSION(fr.xephi.authme.security.crypts.PHPFUSION.class), + PLAINTEXT(fr.xephi.authme.security.crypts.PLAINTEXT.class), + ROYALAUTH(fr.xephi.authme.security.crypts.ROYALAUTH.class), + SALTED2MD5(fr.xephi.authme.security.crypts.SALTED2MD5.class), + SALTEDSHA512(fr.xephi.authme.security.crypts.SALTEDSHA512.class), + SHA1(fr.xephi.authme.security.crypts.SHA1.class), + SHA256(fr.xephi.authme.security.crypts.SHA256.class), + SHA512(fr.xephi.authme.security.crypts.SHA512.class), + SMF(fr.xephi.authme.security.crypts.SMF.class), + WBB3(fr.xephi.authme.security.crypts.WBB3.class), + WBB4(fr.xephi.authme.security.crypts.WBB4.class), + WHIRLPOOL(fr.xephi.authme.security.crypts.WHIRLPOOL.class), + WORDPRESS(fr.xephi.authme.security.crypts.WORDPRESS.class), + XAUTH(fr.xephi.authme.security.crypts.XAUTH.class), + XENFORO(fr.xephi.authme.security.crypts.XF.class); + + Class classe; + + HashAlgorithm(Class classe) { + this.classe = classe; + } + + public Class getclasse() { + return classe; + } + +} diff --git a/src/main/java/fr/xephi/authme/security/PasswordSecurity.java b/src/main/java/fr/xephi/authme/security/PasswordSecurity.java new file mode 100644 index 0000000..be5b772 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/PasswordSecurity.java @@ -0,0 +1,185 @@ +package fr.xephi.authme.security; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.HashMap; + +import org.bukkit.Bukkit; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.events.PasswordEncryptionEvent; +import fr.xephi.authme.security.crypts.BCRYPT; +import fr.xephi.authme.security.crypts.EncryptionMethod; +import fr.xephi.authme.settings.Settings; + +public class PasswordSecurity { + + public static HashMap userSalt = new HashMap<>(); + private static SecureRandom rnd = new SecureRandom(); + + public static boolean comparePasswordWithHash(final String password, final String hash, final String playerName) throws NoSuchAlgorithmException { + final HashAlgorithm algo = Settings.getPasswordHash; + EncryptionMethod method; + try { + if (algo != HashAlgorithm.CUSTOM) { + method = (EncryptionMethod) algo.getclasse().newInstance(); + } else { + method = null; + } + + final PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); + Bukkit.getPluginManager().callEvent(event); + method = event.getMethod(); + + if (method == null) { + throw new NoSuchAlgorithmException("Unknown hash algorithm"); + } + + if (method.comparePassword(hash, password, playerName)) { + return true; + } + + if (Settings.supportOldPassword) { + if (compareWithAllEncryptionMethod(password, hash, playerName)) { + return true; + } + } + } catch (InstantiationException | IllegalAccessException e) { + throw new NoSuchAlgorithmException("Problem with this hash algorithm"); + } + return false; + } + + public static String createSalt(final int length) throws NoSuchAlgorithmException { + final byte[] msg = new byte[40]; + rnd.nextBytes(msg); + final MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + final byte[] digest = sha1.digest(msg); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)).substring(0, length); + } + + public static String getHash(final HashAlgorithm alg, final String password, final String playerName) throws NoSuchAlgorithmException { + EncryptionMethod method; + try { + if (alg != HashAlgorithm.CUSTOM) { + method = (EncryptionMethod) alg.getclasse().newInstance(); + } else { + method = null; + } + } catch (InstantiationException | IllegalAccessException e) { + throw new NoSuchAlgorithmException("Problem with this hash algorithm"); + } + String salt = ""; + switch (alg) { + case SHA256: + salt = createSalt(16); + break; + case MD5VB: + salt = createSalt(16); + break; + case XAUTH: + salt = createSalt(12); + break; + case MYBB: + salt = createSalt(8); + userSalt.put(playerName, salt); + break; + case IPB3: + salt = createSalt(5); + userSalt.put(playerName, salt); + break; + case PHPFUSION: + salt = createSalt(12); + userSalt.put(playerName, salt); + break; + case SALTED2MD5: + salt = createSalt(Settings.saltLength); + userSalt.put(playerName, salt); + break; + case JOOMLA: + salt = createSalt(32); + userSalt.put(playerName, salt); + break; + case BCRYPT: + salt = BCRYPT.gensalt(Settings.bCryptLog2Rounds); + userSalt.put(playerName, salt); + break; + case WBB3: + salt = createSalt(40); + userSalt.put(playerName, salt); + break; + case WBB4: + salt = BCRYPT.gensalt(8); + userSalt.put(playerName, salt); + break; + case PBKDF2DJANGO: + case PBKDF2: + salt = createSalt(12); + userSalt.put(playerName, salt); + break; + case SMF: + if (method != null) { + return method.getHash(password, null, playerName); + } + case PHPBB: + salt = createSalt(16); + userSalt.put(playerName, salt); + break; + case BCRYPT2Y: + salt = createSalt(16); + userSalt.put(playerName, salt); + break; + case SALTEDSHA512: + salt = createSalt(32); + userSalt.put(playerName, salt); + break; + case MD5: + case SHA1: + case WHIRLPOOL: + case PLAINTEXT: + case XENFORO: + case SHA512: + case ROYALAUTH: + case CRAZYCRYPT1: + case DOUBLEMD5: + case WORDPRESS: + case CUSTOM: + break; + default: + throw new NoSuchAlgorithmException("Unknown hash algorithm"); + } + final PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); + Bukkit.getPluginManager().callEvent(event); + method = event.getMethod(); + if (method == null) { + throw new NoSuchAlgorithmException("Unknown hash algorithm"); + } + return method.getHash(password, salt, playerName); + } + + private static boolean compareWithAllEncryptionMethod(final String password, final String hash, final String playerName) throws NoSuchAlgorithmException { + for (final HashAlgorithm algo : HashAlgorithm.values()) { + if (algo != HashAlgorithm.CUSTOM) { + try { + final EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance(); + if (method.comparePassword(hash, password, playerName)) { + final PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName); + if (nAuth != null) { + nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName)); + nAuth.setSalt(userSalt.containsKey(playerName) ? userSalt.get(playerName) : ""); + AuthMe.getInstance().database.updatePassword(nAuth); + AuthMe.getInstance().database.updateSalt(nAuth); + } + return true; + } + } catch (final Exception ignored) { + } + } + } + return false; + } +} diff --git a/src/main/java/fr/xephi/authme/security/RandomString.java b/src/main/java/fr/xephi/authme/security/RandomString.java new file mode 100644 index 0000000..ae2505d --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/RandomString.java @@ -0,0 +1,38 @@ +package fr.xephi.authme.security; + +import java.util.Calendar; +import java.util.Random; + +/** + * + * @author Xephi59 + */ +public class RandomString { + + private static final char[] chars = new char[36]; + + private final char[] buf; + + private final Random random = new Random(); + + public RandomString(int length) { + if (length < 1) + throw new IllegalArgumentException("length < 1: " + length); + buf = new char[length]; + random.setSeed(Calendar.getInstance().getTimeInMillis()); + } + + static { + for (int idx = 0; idx < 10; ++idx) + chars[idx] = (char) ('0' + idx); + for (int idx = 10; idx < 36; ++idx) + chars[idx] = (char) ('a' + idx - 10); + } + + public String nextString() { + for (int idx = 0; idx < buf.length; ++idx) + buf[idx] = chars[random.nextInt(chars.length)]; + return new String(buf); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java b/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java new file mode 100644 index 0000000..9da997a --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/BCRYPT.java @@ -0,0 +1,619 @@ +// Copyright (c) 2006 Damien Miller +// +// Permission to use, copy, modify, and distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +package fr.xephi.authme.security.crypts; + +import java.io.UnsupportedEncodingException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +/** + * BCrypt implements OpenBSD-style Blowfish password hashing using the scheme + * described in "A Future-Adaptable Password Scheme" by Niels Provos and David + * Mazieres. + *

+ * This password hashing system tries to thwart off-line password cracking using + * a computationally-intensive hashing algorithm, based on Bruce Schneier's + * Blowfish cipher. The work factor of the algorithm is parameterised, so it can + * be increased as computers get faster. + *

+ * Usage is really simple. To hash a password for the first time, call the + * hashpw method with a random salt, like this: + *

+ * + * String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt());
+ *
+ *

+ * To check whether a plaintext password matches one that has been hashed + * previously, use the checkpw method: + *

+ * + * if (BCrypt.checkpw(candidate_password, stored_hash))
+ *     System.out.println("It matches");
+ * else
+ *     System.out.println("It does not match");
+ *
+ *

+ * The gensalt() method takes an optional parameter (log_rounds) that determines + * the computational complexity of the hashing: + *

+ * + * String strong_salt = BCrypt.gensalt(10)
+ * String stronger_salt = BCrypt.gensalt(12)
+ *
+ *

+ * The amount of work increases exponentially (2**log_rounds), so each increment + * is twice as much work. The default log_rounds is 10, and the valid range is 4 + * to 31. + * + * @author Damien Miller + * @version 0.2 + */ +public class BCRYPT implements EncryptionMethod { + + // Table for Base64 encoding + static private final char base64_code[] = { '.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', + 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9' }; + private static final int BCRYPT_SALT_LEN = 16; + + // bcrypt IV: "OrpheanBeholderScryDoubt" + static private final int bf_crypt_ciphertext[] = { 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 }; + + // Blowfish parameters + private static final int BLOWFISH_NUM_ROUNDS = 16; + // BCrypt parameters + private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10; + + // Table for Base64 decoding + static private final byte index_64[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1 }; + + // Initial contents of key schedule + private static final int P_orig[] = { 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, + 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b }; + + private static final int S_orig[] = { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, + 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, + 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, + 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, + 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, + 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, + 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, + 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, + 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, + 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, + 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, + 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, + 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, + 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, + 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, + 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, + 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, + 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, + 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, + 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, + 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, + 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, + 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, + 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, + 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, + 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, + 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, + 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, + 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, + 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, + 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, + 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, + 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, + 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, + 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, + 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, + 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, + 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, + 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, + 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, + 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, + 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, + 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, + 0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, + 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, + 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, + 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, + 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, + 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, + 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, + 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, + 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, + 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, + 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, + 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, + 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, + 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, + 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 }; + + // Expanded Blowfish key + private int P[]; + private int S[]; + + /** + * Check that a plaintext password matches a previously hashed one + * + * @param plaintext + * the plaintext password to verify + * @param hashed + * the previously-hashed password + * @return true if the passwords match, false otherwise + */ + public static boolean checkpw(String plaintext, String hashed) { + return (hashed.compareTo(hashpw(plaintext, hashed)) == 0); + } + + /** + * Check that a text password matches a previously hashed one with the + * specified number of rounds using recursion + * + * @param text + * plaintext or hashed text + * @param hashed + * the previously-hashed password + * @param rounds + * number of rounds to hash the password + * @return + */ + public static boolean checkpw(String text, String hashed, int rounds) { + boolean matched = false; + + if (rounds > 0) { + String hash = hashpw(text, hashed); + + if (rounds > 1) { + matched = checkpw(hash, hashed, rounds - 1); + } else { + matched = hash.compareTo(hashed) == 0; + } + } else { + matched = text.compareTo(hashed) == 0; + } + + return matched; + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method, selecting a + * reasonable default for the number of hashing rounds to apply + * + * @return an encoded salt value + */ + public static String gensalt() { + return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * + * @param log_rounds + * the log2 of the number of rounds of hashing to apply - the + * work factor therefore increases as 2**log_rounds. + * @return an encoded salt value + */ + public static String gensalt(int log_rounds) { + return gensalt(log_rounds, new SecureRandom()); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * + * @param log_rounds + * the log2 of the number of rounds of hashing to apply - the + * work factor therefore increases as 2**log_rounds. + * @param random + * an instance of SecureRandom to use + * @return an encoded salt value + */ + public static String gensalt(int log_rounds, SecureRandom random) { + StringBuffer rs = new StringBuffer(); + byte rnd[] = new byte[BCRYPT_SALT_LEN]; + + random.nextBytes(rnd); + + rs.append("$2a$"); + if (log_rounds < 10) + rs.append("0"); + rs.append(Integer.toString(log_rounds)); + rs.append("$"); + rs.append(encode_base64(rnd, rnd.length)); + return rs.toString(); + } + + public static String getDoubleHash(String text, String salt) { + String hash = hashpw(text, salt); + return hashpw(text, hash); + } + + /** + * Hash a password using the OpenBSD bcrypt scheme + * + * @param password + * the password to hash + * @param salt + * the salt to hash with (perhaps generated using BCrypt.gensalt) + * @return the hashed password + */ + public static String hashpw(String password, String salt) { + BCRYPT B; + String real_salt; + byte passwordb[], saltb[], hashed[]; + char minor = (char) 0; + int rounds, off = 0; + StringBuffer rs = new StringBuffer(); + + if (salt.charAt(0) != '$' || salt.charAt(1) != '2') + throw new IllegalArgumentException("Invalid salt version"); + if (salt.charAt(2) == '$') + off = 3; + else { + minor = salt.charAt(2); + if (minor < 'a' || minor > 'z' || salt.charAt(3) != '$') + throw new IllegalArgumentException("Invalid salt revision"); + off = 4; + } + + // Extract number of rounds + if (salt.charAt(off + 2) > '$') + throw new IllegalArgumentException("Missing salt rounds"); + rounds = Integer.parseInt(salt.substring(off, off + 2)); + + real_salt = salt.substring(off + 3, off + 25); + try { + passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8"); + } catch (UnsupportedEncodingException uee) { + throw new AssertionError("UTF-8 is not supported"); + } + + saltb = decode_base64(real_salt, BCRYPT_SALT_LEN); + + B = new BCRYPT(); + hashed = B.crypt_raw(passwordb, saltb, rounds); + + rs.append("$2"); + if (minor >= 'a') + rs.append(minor); + rs.append("$"); + if (rounds < 10) + rs.append("0"); + rs.append(Integer.toString(rounds)); + rs.append("$"); + rs.append(encode_base64(saltb, saltb.length)); + rs.append(encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1)); + return rs.toString(); + } + + /** + * Look up the 3 bits base64-encoded by the specified character, + * range-checking againt conversion table + * + * @param x + * the base64-encoded value + * @return the decoded value of x + */ + private static byte char64(char x) { + if ((int) x > index_64.length) + return -1; + return index_64[(int) x]; + } + + /** + * Decode a string encoded using bcrypt's base64 scheme to a byte array. + * Note that this is *not* compatible with the standard MIME-base64 + * encoding. + * + * @param s + * the string to decode + * @param maxolen + * the maximum number of bytes to decode + * @return an array containing the decoded bytes + * @throws IllegalArgumentException + * if maxolen is invalid + */ + private static byte[] decode_base64(String s, int maxolen) throws IllegalArgumentException { + StringBuffer rs = new StringBuffer(); + int off = 0, slen = s.length(), olen = 0; + byte ret[]; + byte c1, c2, c3, c4, o; + + if (maxolen <= 0) + throw new IllegalArgumentException("Invalid maxolen"); + + while (off < slen - 1 && olen < maxolen) { + c1 = char64(s.charAt(off++)); + c2 = char64(s.charAt(off++)); + if (c1 == -1 || c2 == -1) + break; + o = (byte) (c1 << 2); + o |= (c2 & 0x30) >> 4; + rs.append((char) o); + if (++olen >= maxolen || off >= slen) + break; + c3 = char64(s.charAt(off++)); + if (c3 == -1) + break; + o = (byte) ((c2 & 0x0f) << 4); + o |= (c3 & 0x3c) >> 2; + rs.append((char) o); + if (++olen >= maxolen || off >= slen) + break; + c4 = char64(s.charAt(off++)); + o = (byte) ((c3 & 0x03) << 6); + o |= c4; + rs.append((char) o); + ++olen; + } + + ret = new byte[olen]; + for (off = 0; off < olen; off++) + ret[off] = (byte) rs.charAt(off); + return ret; + } + + /** + * Encode a byte array using bcrypt's slightly-modified base64 encoding + * scheme. Note that this is *not* compatible with the standard MIME-base64 + * encoding. + * + * @param d + * the byte array to encode + * @param len + * the number of bytes to encode + * @return base64-encoded string + * @throws IllegalArgumentException + * if the length is invalid + */ + private static String encode_base64(byte d[], int len) throws IllegalArgumentException { + int off = 0; + StringBuffer rs = new StringBuffer(); + int c1, c2; + + if (len <= 0 || len > d.length) + throw new IllegalArgumentException("Invalid len"); + + while (off < len) { + c1 = d[off++] & 0xff; + rs.append(base64_code[(c1 >> 2) & 0x3f]); + c1 = (c1 & 0x03) << 4; + if (off >= len) { + rs.append(base64_code[c1 & 0x3f]); + break; + } + c2 = d[off++] & 0xff; + c1 |= (c2 >> 4) & 0x0f; + rs.append(base64_code[c1 & 0x3f]); + c1 = (c2 & 0x0f) << 2; + if (off >= len) { + rs.append(base64_code[c1 & 0x3f]); + break; + } + c2 = d[off++] & 0xff; + c1 |= (c2 >> 6) & 0x03; + rs.append(base64_code[c1 & 0x3f]); + rs.append(base64_code[c2 & 0x3f]); + } + return rs.toString(); + } + + /** + * Cycically extract a word of key material + * + * @param data + * the string to extract the data from + * @param offp + * a "pointer" (as a one-entry array) to the current offset into + * data + * @return the next word of material from data + */ + private static int streamtoword(byte data[], int offp[]) { + int i; + int word = 0; + int off = offp[0]; + + for (i = 0; i < 4; i++) { + word = (word << 8) | (data[off] & 0xff); + off = (off + 1) % data.length; + } + + offp[0] = off; + return word; + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return checkpw(password, hash); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return hashpw(password, salt); + } + + /** + * Perform the central password hashing step in the bcrypt scheme + * + * @param password + * the password to hash + * @param salt + * the binary salt to hash with the password + * @param log_rounds + * the binary logarithm of the number of rounds of hashing to + * apply + * @return an array containing the binary hashed password + */ + private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { + int rounds, i, j; + int cdata[] = (int[]) bf_crypt_ciphertext.clone(); + int clen = cdata.length; + byte ret[]; + + if (log_rounds < 4 || log_rounds > 31) + throw new IllegalArgumentException("Bad number of rounds"); + rounds = 1 << log_rounds; + if (salt.length != BCRYPT_SALT_LEN) + throw new IllegalArgumentException("Bad salt length"); + + init_key(); + ekskey(salt, password); + for (i = 0; i < rounds; i++) { + key(password); + key(salt); + } + + for (i = 0; i < 64; i++) { + for (j = 0; j < (clen >> 1); j++) + encipher(cdata, j << 1); + } + + ret = new byte[clen * 4]; + for (i = 0, j = 0; i < clen; i++) { + ret[j++] = (byte) ((cdata[i] >> 24) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 16) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 8) & 0xff); + ret[j++] = (byte) (cdata[i] & 0xff); + } + return ret; + } + + /** + * Perform the "enhanced key schedule" step described by Provos and Mazieres + * in "A Future-Adaptable Password Scheme" + * http://www.openbsd.org/papers/bcrypt-paper.ps + * + * @param data + * salt information + * @param key + * password information + */ + private void ekskey(byte data[], byte key[]) { + int i; + int koffp[] = { 0 }, doffp[] = { 0 }; + int lr[] = { 0, 0 }; + int plen = P.length, slen = S.length; + + for (i = 0; i < plen; i++) + P[i] = P[i] ^ streamtoword(key, koffp); + + for (i = 0; i < plen; i += 2) { + lr[0] ^= streamtoword(data, doffp); + lr[1] ^= streamtoword(data, doffp); + encipher(lr, 0); + P[i] = lr[0]; + P[i + 1] = lr[1]; + } + + for (i = 0; i < slen; i += 2) { + lr[0] ^= streamtoword(data, doffp); + lr[1] ^= streamtoword(data, doffp); + encipher(lr, 0); + S[i] = lr[0]; + S[i + 1] = lr[1]; + } + } + + /** + * Blowfish encipher a single 64-bit block encoded as two 32-bit halves + * + * @param lr + * an array containing the two 32-bit half blocks + * @param off + * the position in the array of the blocks + */ + private final void encipher(int lr[], int off) { + int i, n, l = lr[off], r = lr[off + 1]; + + l ^= P[0]; + for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) { + // Feistel substitution on left word + n = S[(l >> 24) & 0xff]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[++i]; + + // Feistel substitution on right word + n = S[(r >> 24) & 0xff]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[++i]; + } + lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; + lr[off + 1] = l; + } + + /** + * Initialise the Blowfish key schedule + */ + private void init_key() { + P = (int[]) P_orig.clone(); + S = (int[]) S_orig.clone(); + } + + /** + * Key the Blowfish cipher + * + * @param key + * an array containing the key + */ + private void key(byte key[]) { + int i; + int koffp[] = { 0 }; + int lr[] = { 0, 0 }; + int plen = P.length, slen = S.length; + + for (i = 0; i < plen; i++) + P[i] = P[i] ^ streamtoword(key, koffp); + + for (i = 0; i < plen; i += 2) { + encipher(lr, 0); + P[i] = lr[0]; + P[i + 1] = lr[1]; + } + + for (i = 0; i < slen; i += 2) { + encipher(lr, 0); + S[i] = lr[0]; + S[i + 1] = lr[1]; + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/BCRYPT2Y.java b/src/main/java/fr/xephi/authme/security/crypts/BCRYPT2Y.java new file mode 100644 index 0000000..fb14b81 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/BCRYPT2Y.java @@ -0,0 +1,22 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +public class BCRYPT2Y implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String ok = hash.substring(0, 29); + if (ok.length() != 29) + return false; + return hash.equals(getHash(password, ok, playerName)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + if (salt.length() == 22) + salt = "$2y$10$" + salt; + return (BCRYPT.hashpw(password, salt)); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/CRAZYCRYPT1.java b/src/main/java/fr/xephi/authme/security/crypts/CRAZYCRYPT1.java new file mode 100644 index 0000000..7dbf3c4 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/CRAZYCRYPT1.java @@ -0,0 +1,37 @@ +package fr.xephi.authme.security.crypts; + +import java.nio.charset.Charset; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class CRAZYCRYPT1 implements EncryptionMethod { + + private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + protected final Charset charset = Charset.forName("UTF-8"); + + public static String byteArrayToHexString(final byte... args) { + final char[] chars = new char[args.length * 2]; + for (int i = 0; i < args.length; i++) { + chars[i * 2] = CRYPTCHARS[(args[i] >> 4) & 0xF]; + chars[i * 2 + 1] = CRYPTCHARS[(args[i]) & 0xF]; + } + return new String(chars); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, null, playerName)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + final String text = "ÜÄaeut//&/=I " + password + "7421€547" + name + "__+IÄIH§%NK " + password; + try { + final MessageDigest md = MessageDigest.getInstance("SHA-512"); + md.update(text.getBytes(charset), 0, text.length()); + return byteArrayToHexString(md.digest()); + } catch (final NoSuchAlgorithmException e) { + return null; + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java new file mode 100644 index 0000000..932b35d --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +import fr.xephi.authme.security.pbkdf2.PBKDF2Engine; +import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters; + +public class CryptPBKDF2 implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String[] line = hash.split("\\$"); + String salt = line[2]; + String derivedKey = line[3]; + PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000, derivedKey.getBytes()); + PBKDF2Engine engine = new PBKDF2Engine(params); + return engine.verifyKey(password); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + String result = "pbkdf2_sha256$10000$" + salt + "$"; + PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 10000); + PBKDF2Engine engine = new PBKDF2Engine(params); + + return result + String.valueOf(engine.deriveKey(password, 64)); + } + +} \ No newline at end of file diff --git a/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2Django.java b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2Django.java new file mode 100644 index 0000000..d7aa170 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/CryptPBKDF2Django.java @@ -0,0 +1,31 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +import fr.xephi.authme.security.pbkdf2.PBKDF2Engine; +import fr.xephi.authme.security.pbkdf2.PBKDF2Parameters; + +public class CryptPBKDF2Django implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String[] line = hash.split("\\$"); + String salt = line[2]; + byte[] derivedKey = DatatypeConverter.parseBase64Binary(line[3]); + PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000, derivedKey); + PBKDF2Engine engine = new PBKDF2Engine(params); + return engine.verifyKey(password); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + String result = "pbkdf2_sha256$15000$" + salt + "$"; + PBKDF2Parameters params = new PBKDF2Parameters("HmacSHA256", "ASCII", salt.getBytes(), 15000); + PBKDF2Engine engine = new PBKDF2Engine(params); + + return result + String.valueOf(DatatypeConverter.printBase64Binary(engine.deriveKey(password, 32))); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/DOUBLEMD5.java b/src/main/java/fr/xephi/authme/security/crypts/DOUBLEMD5.java new file mode 100644 index 0000000..f2831a0 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/DOUBLEMD5.java @@ -0,0 +1,27 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class DOUBLEMD5 implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, "", "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getMD5(getMD5(password)); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/EncryptionMethod.java b/src/main/java/fr/xephi/authme/security/crypts/EncryptionMethod.java new file mode 100644 index 0000000..3d9c8f1 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/EncryptionMethod.java @@ -0,0 +1,38 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +/** + *

+ * Public interface for Custom Password encryption method + *

+ *

+ * The getHash function is called when we need to crypt the password (/register + * usually) + *

+ *

+ * The comparePassword is called when we need to match password (/login usually) + *

+ */ +public interface EncryptionMethod { + + /** + * @param hash + * @param password + * @param playerName + * @return true if password match, false else + * @throws NoSuchAlgorithmException + */ + boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException; + + /** + * @param password + * @param salt + * (can be an other data like playerName;salt , playerName, + * etc... for customs methods) + * @return Hashing password + * @throws NoSuchAlgorithmException + */ + String getHash(String password, String salt, String name) throws NoSuchAlgorithmException; + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/IPB3.java b/src/main/java/fr/xephi/authme/security/crypts/IPB3.java new file mode 100644 index 0000000..0e874d6 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/IPB3.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import fr.xephi.authme.AuthMe; + +public class IPB3 implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(getHash(password, salt, playerName)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getMD5(getMD5(salt) + getMD5(password)); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/JOOMLA.java b/src/main/java/fr/xephi/authme/security/crypts/JOOMLA.java new file mode 100644 index 0000000..4135c4a --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/JOOMLA.java @@ -0,0 +1,27 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class JOOMLA implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = hash.split(":")[1]; + return hash.equals(getMD5(password + salt) + ":" + salt); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getMD5(password + salt) + ":" + salt; + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/MD5.java b/src/main/java/fr/xephi/authme/security/crypts/MD5.java new file mode 100644 index 0000000..5d44649 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/MD5.java @@ -0,0 +1,26 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class MD5 implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, "", "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getMD5(password); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/MD5VB.java b/src/main/java/fr/xephi/authme/security/crypts/MD5VB.java new file mode 100644 index 0000000..4fd16b0 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/MD5VB.java @@ -0,0 +1,28 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class MD5VB implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String[] line = hash.split("\\$"); + return hash.equals(getHash(password, line[2], "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return "$MD5vb$" + salt + "$" + getMD5(getMD5(password) + salt); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/MYBB.java b/src/main/java/fr/xephi/authme/security/crypts/MYBB.java new file mode 100644 index 0000000..312f65f --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/MYBB.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import fr.xephi.authme.AuthMe; + +public class MYBB implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(getHash(password, salt, playerName)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getMD5(getMD5(salt) + getMD5(password)); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java b/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java new file mode 100644 index 0000000..56847ed --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/PHPBB.java @@ -0,0 +1,151 @@ +/* + * To change this template, choose Tools | Templates and open the template in + * the editor. + */ +package fr.xephi.authme.security.crypts; + +import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +/** + * @author stefano + */ +public class PHPBB implements EncryptionMethod { + + private String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + public static String md5(String data) { + try { + byte[] bytes = data.getBytes("ISO-8859-1"); + MessageDigest md5er = MessageDigest.getInstance("MD5"); + byte[] hash = md5er.digest(bytes); + return bytes2hex(hash); + } catch (GeneralSecurityException | UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + private static String bytes2hex(byte[] bytes) { + StringBuilder r = new StringBuilder(32); + for (byte b : bytes) { + String x = Integer.toHexString(b & 0xff); + if (x.length() < 2) + r.append("0"); + r.append(x); + } + return r.toString(); + } + + static int hexToInt(char ch) { + if (ch >= '0' && ch <= '9') + return ch - '0'; + ch = Character.toUpperCase(ch); + if (ch >= 'A' && ch <= 'F') + return ch - 'A' + 0xA; + throw new IllegalArgumentException("Not a hex character: " + ch); + } + + static String pack(String hex) { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < hex.length(); i += 2) { + char c1 = hex.charAt(i); + char c2 = hex.charAt(i + 1); + char packed = (char) (hexToInt(c1) * 16 + hexToInt(c2)); + buf.append(packed); + } + return buf.toString(); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return phpbb_check_hash(password, hash); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return phpbb_hash(password, salt); + } + + public boolean phpbb_check_hash(String password, String hash) { + if (hash.length() == 34) + return _hash_crypt_private(password, hash).equals(hash); + else + return md5(password).equals(hash); + } + + public String phpbb_hash(String password, String salt) { + String random_state = salt; + StringBuilder random = new StringBuilder(); + int count = 6; + for (int i = 0; i < count; i += 16) { + random_state = md5(salt + random_state); + random.append(pack(md5(random_state))); + } + String hash = _hash_crypt_private(password, _hash_gensalt_private(random.substring(0, count), itoa64)); + if (hash.length() == 34) { + return hash; + } + return md5(password); + } + + /** + * Encode hash + */ + private String _hash_encode64(String input, int count) { + StringBuilder output = new StringBuilder(); + int i = 0; + do { + int value = input.charAt(i++); + output.append(itoa64.charAt(value & 0x3f)); + if (i < count) + value |= input.charAt(i) << 8; + output.append(itoa64.charAt((value >> 6) & 0x3f)); + if (i++ >= count) + break; + if (i < count) + value |= input.charAt(i) << 16; + output.append(itoa64.charAt((value >> 12) & 0x3f)); + if (i++ >= count) + break; + output.append(itoa64.charAt((value >> 18) & 0x3f)); + } while (i < count); + return output.toString(); + } + + private String _hash_gensalt_private(String input, String itoa64) { + return _hash_gensalt_private(input, itoa64, 6); + } + + private String _hash_gensalt_private(String input, String itoa64, int iteration_count_log2) { + if (iteration_count_log2 < 4 || iteration_count_log2 > 31) { + iteration_count_log2 = 8; + } + String output = "$H$"; + output += itoa64.charAt(Math.min(iteration_count_log2 + 3, 30)); // PHP_VERSION >= 5 ? 5 : 3 + output += _hash_encode64(input, 6); + return output; + } + + String _hash_crypt_private(String password, String setting) { + String output = "*"; + if (!setting.substring(0, 3).equals("$H$")) + return output; + int count_log2 = itoa64.indexOf(setting.charAt(3)); + if (count_log2 < 7 || count_log2 > 30) + return output; + int count = 1 << count_log2; + String salt = setting.substring(4, 12); + if (salt.length() != 8) + return output; + String m1 = md5(salt + password); + String hash = pack(m1); + do { + hash = pack(md5(hash + password)); + } while (--count > 0); + output = setting.substring(0, 12); + output += _hash_encode64(hash, 16); + return output; + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java b/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java new file mode 100644 index 0000000..f2f6903 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/PHPFUSION.java @@ -0,0 +1,56 @@ +package fr.xephi.authme.security.crypts; + +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import fr.xephi.authme.AuthMe; + +public class PHPFUSION implements EncryptionMethod { + + private static String getSHA1(String message) throws NoSuchAlgorithmException { + MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + sha1.update(message.getBytes()); + byte[] digest = sha1.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(getHash(password, salt, "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + String digest = null; + String algo = "HmacSHA256"; + String keyString = getSHA1(salt); + try { + SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo); + Mac mac = Mac.getInstance(algo); + mac.init(key); + byte[] bytes = mac.doFinal(password.getBytes("ASCII")); + StringBuffer hash = new StringBuffer(); + for (int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(0xFF & bytes[i]); + if (hex.length() == 1) { + hash.append('0'); + } + hash.append(hex); + } + digest = hash.toString(); + } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) { + // ingore + } + + return digest; + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/PLAINTEXT.java b/src/main/java/fr/xephi/authme/security/crypts/PLAINTEXT.java new file mode 100644 index 0000000..08b75f0 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/PLAINTEXT.java @@ -0,0 +1,17 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +public class PLAINTEXT implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(password); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return password; + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/ROYALAUTH.java b/src/main/java/fr/xephi/authme/security/crypts/ROYALAUTH.java new file mode 100644 index 0000000..6c00d53 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/ROYALAUTH.java @@ -0,0 +1,30 @@ +package fr.xephi.authme.security.crypts; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class ROYALAUTH implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equalsIgnoreCase(getHash(password, "", "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + for (int i = 0; i < 25; i++) + password = hash(password, salt); + return password; + } + + public String hash(String password, String salt) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-512"); + md.update(password.getBytes()); + byte byteData[] = md.digest(); + StringBuilder sb = new StringBuilder(); + for (byte aByteData : byteData) + sb.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1)); + return sb.toString(); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/SALTED2MD5.java b/src/main/java/fr/xephi/authme/security/crypts/SALTED2MD5.java new file mode 100644 index 0000000..274283c --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/SALTED2MD5.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import fr.xephi.authme.AuthMe; + +public class SALTED2MD5 implements EncryptionMethod { + + private static String getMD5(String message) throws NoSuchAlgorithmException { + MessageDigest md5 = MessageDigest.getInstance("MD5"); + md5.reset(); + md5.update(message.getBytes()); + byte[] digest = md5.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(getMD5(getMD5(password) + salt)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getMD5(getMD5(password) + salt); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/SALTEDSHA512.java b/src/main/java/fr/xephi/authme/security/crypts/SALTEDSHA512.java new file mode 100644 index 0000000..e715adb --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/SALTEDSHA512.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import fr.xephi.authme.AuthMe; + +public class SALTEDSHA512 implements EncryptionMethod { + + private static String getSHA512(String message) throws NoSuchAlgorithmException { + MessageDigest sha512 = MessageDigest.getInstance("SHA-512"); + sha512.reset(); + sha512.update(message.getBytes()); + byte[] digest = sha512.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(getHash(password, salt, "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getSHA512(password + salt); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/SHA1.java b/src/main/java/fr/xephi/authme/security/crypts/SHA1.java new file mode 100644 index 0000000..f3e1026 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/SHA1.java @@ -0,0 +1,27 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class SHA1 implements EncryptionMethod { + + private static String getSHA1(String message) throws NoSuchAlgorithmException { + MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + sha1.update(message.getBytes()); + byte[] digest = sha1.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, "", "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getSHA1(password); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/SHA256.java b/src/main/java/fr/xephi/authme/security/crypts/SHA256.java new file mode 100644 index 0000000..c32c8cf --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/SHA256.java @@ -0,0 +1,28 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class SHA256 implements EncryptionMethod { + + private static String getSHA256(String message) throws NoSuchAlgorithmException { + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + sha256.reset(); + sha256.update(message.getBytes()); + byte[] digest = sha256.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String[] line = hash.split("\\$"); + return hash.equals(getHash(password, line[2], "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return "$SHA$" + salt + "$" + getSHA256(getSHA256(password) + salt); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/SHA512.java b/src/main/java/fr/xephi/authme/security/crypts/SHA512.java new file mode 100644 index 0000000..080fb98 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/SHA512.java @@ -0,0 +1,26 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class SHA512 implements EncryptionMethod { + + private static String getSHA512(String message) throws NoSuchAlgorithmException { + MessageDigest sha512 = MessageDigest.getInstance("SHA-512"); + sha512.reset(); + sha512.update(message.getBytes()); + byte[] digest = sha512.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, "", "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getSHA512(password); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/SMF.java b/src/main/java/fr/xephi/authme/security/crypts/SMF.java new file mode 100644 index 0000000..49f4abb --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/SMF.java @@ -0,0 +1,26 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class SMF implements EncryptionMethod { + + private static String getSHA1(String message) throws NoSuchAlgorithmException { + MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + sha1.update(message.getBytes()); + byte[] digest = sha1.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, null, playerName)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getSHA1(name.toLowerCase() + password); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/WBB3.java b/src/main/java/fr/xephi/authme/security/crypts/WBB3.java new file mode 100644 index 0000000..e8a5404 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/WBB3.java @@ -0,0 +1,29 @@ +package fr.xephi.authme.security.crypts; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import fr.xephi.authme.AuthMe; + +public class WBB3 implements EncryptionMethod { + + private static String getSHA1(String message) throws NoSuchAlgorithmException { + MessageDigest sha1 = MessageDigest.getInstance("SHA1"); + sha1.reset(); + sha1.update(message.getBytes()); + byte[] digest = sha1.digest(); + return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(getHash(password, salt, "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getSHA1(salt.concat(getSHA1(salt.concat(getSHA1(password))))); + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/WBB4.java b/src/main/java/fr/xephi/authme/security/crypts/WBB4.java new file mode 100644 index 0000000..30ed93d --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/WBB4.java @@ -0,0 +1,17 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +public class WBB4 implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + return BCRYPT.checkpw(password, hash, 2); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return BCRYPT.getDoubleHash(password, salt); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/WHIRLPOOL.java b/src/main/java/fr/xephi/authme/security/crypts/WHIRLPOOL.java new file mode 100644 index 0000000..80287bd --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/WHIRLPOOL.java @@ -0,0 +1,408 @@ +package fr.xephi.authme.security.crypts; + +/** + * The Whirlpool hashing function. + * + *

+ * References + * + *

+ * The Whirlpool algorithm was developed by Paulo S. L. M. Barreto and Vincent Rijmen. + * + * See P.S.L.M. Barreto, V. Rijmen, ``The Whirlpool hashing function,'' First + * NESSIE workshop, 2000 (tweaked version, 2003), + * + * + * @author Paulo S.L.M. Barreto + * @author Vincent Rijmen. + * + * @version 3.0 (2003.03.12) + * + * ==================================================================== + * ========= + * + * Differences from version 2.1: + * + * - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2, + * 9). + * + * ==================================================================== + * ========= + * + * Differences from version 2.0: + * + * - Generation of ISO/IEC 10118-3 test vectors. - Bug fix: nonzero + * carry was ignored when tallying the data length (this bug apparently + * only manifested itself when feeding data in pieces rather than in a + * single chunk at once). + * + * Differences from version 1.0: + * + * - Original S-box replaced by the tweaked, hardware-efficient + * version. + * + * ==================================================================== + * ========= + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +public class WHIRLPOOL implements EncryptionMethod { + + /** + * The message digest size (in bits) + */ + public static final int DIGESTBITS = 512; + + /** + * The message digest size (in bytes) + */ + public static final int DIGESTBYTES = DIGESTBITS >>> 3; + + /** + * The number of rounds of the internal dedicated block cipher. + */ + private static long[][] C = new long[8][256]; + + private static final int R = 10; + + private static long[] rc = new long[R + 1]; + /** + * The substitution box. + */ + private static final String sbox = "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152" + "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57" + "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85" + + "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8" + "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333" + "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0" + + "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE" + "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d" + "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF" + + "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A" + "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c" + "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04" + + "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB" + "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9" + "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1" + + "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886"; + + /** + * Global number of hashed bits (256-bit counter). + */ + protected byte[] bitLength = new byte[32]; + + protected long[] block = new long[8]; + + /** + * Buffer of data to hash. + */ + protected byte[] buffer = new byte[64]; + + /** + * Current number of bits on the buffer. + */ + protected int bufferBits = 0; + + /** + * Current (possibly incomplete) byte slot on the buffer. + */ + protected int bufferPos = 0; + + /** + * The hashing state. + */ + protected long[] hash = new long[8]; + protected long[] K = new long[8]; + protected long[] L = new long[8]; + protected long[] state = new long[8]; + + public WHIRLPOOL() { + } + + static { + for (int x = 0; x < 256; x++) { + final char c = sbox.charAt(x / 2); + final long v1 = ((x & 1) == 0) ? c >>> 8 : c & 0xff; + long v2 = v1 << 1; + if (v2 >= 0x100L) { + v2 ^= 0x11dL; + } + long v4 = v2 << 1; + if (v4 >= 0x100L) { + v4 ^= 0x11dL; + } + final long v5 = v4 ^ v1; + long v8 = v4 << 1; + if (v8 >= 0x100L) { + v8 ^= 0x11dL; + } + final long v9 = v8 ^ v1; + /* + * build the circulant table C[0][x] = S[x].[1, 1, 4, 1, 8, 5, 2, + * 9]: + */ + C[0][x] = (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) | (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9); + /* + * build the remaining circulant tables C[t][x] = C[0][x] rotr t + */ + for (int t = 1; t < 8; t++) { + C[t][x] = (C[t - 1][x] >>> 8) | ((C[t - 1][x] << 56)); + } + } + /* + * build the round constants: + */ + rc[0] = 0L; /* + * not used (assigment kept only to properly initialize all + * variables) + */ + for (int r = 1; r <= R; r++) { + final int i = 8 * (r - 1); + rc[r] = (C[0][i] & 0xff00000000000000L) ^ (C[1][i + 1] & 0x00ff000000000000L) ^ (C[2][i + 2] & 0x0000ff0000000000L) ^ (C[3][i + 3] & 0x000000ff00000000L) + ^ (C[4][i + 4] & 0x00000000ff000000L) ^ (C[5][i + 5] & 0x0000000000ff0000L) ^ (C[6][i + 6] & 0x000000000000ff00L) ^ (C[7][i + 7] & 0x00000000000000ffL); + } + } + + protected static String display(final byte[] array) { + final char[] val = new char[2 * array.length]; + final String hex = "0123456789ABCDEF"; + for (int i = 0; i < array.length; i++) { + final int b = array[i] & 0xff; + val[2 * i] = hex.charAt(b >>> 4); + val[2 * i + 1] = hex.charAt(b & 15); + } + return String.valueOf(val); + } + + @Override + public boolean comparePassword(final String hash, final String password, final String playerName) throws NoSuchAlgorithmException { + return hash.equals(getHash(password, "", "")); + } + + @Override + public String getHash(final String password, final String salt, final String name) throws NoSuchAlgorithmException { + final byte[] digest = new byte[DIGESTBYTES]; + NESSIEinit(); + NESSIEadd(password); + NESSIEfinalize(digest); + return display(digest); + } + + /** + * Delivers input data to the hashing algorithm. + * + * @param source + * plaintext data to hash. + * @param sourceBits + * how many bits of plaintext to process. + * + * This method maintains the invariant: bufferBits < 512 + */ + public void NESSIEadd(final byte[] source, long sourceBits) { + /* + * sourcePos | +-------+-------+------- ||||||||||||||||||||| source + * +-------+-------+------- + * +-------+-------+-------+-------+-------+------- + * |||||||||||||||||||||| buffer + * +-------+-------+-------+-------+-------+------- | bufferPos + */ + int sourcePos = 0; // index of leftmost source byte containing data (1 + // to 8 bits). + final int sourceGap = (8 - ((int) sourceBits & 7)) & 7; // space on + // source[sourcePos]. + final int bufferRem = bufferBits & 7; // occupied bits on buffer[bufferPos]. + int b; + // tally the length of the added data: + long value = sourceBits; + for (int i = 31, carry = 0; i >= 0; i--) { + carry += (bitLength[i] & 0xff) + ((int) value & 0xff); + bitLength[i] = (byte) carry; + carry >>>= 8; + value >>>= 8; + } + // process data in chunks of 8 bits: + while (sourceBits > 8) { // at least source[sourcePos] and + // source[sourcePos+1] contain data. + // take a byte from the source: + b = ((source[sourcePos] << sourceGap) & 0xff) | ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap)); + if (b < 0 || b >= 256) { + throw new RuntimeException("LOGIC ERROR"); + } + // process this byte: + buffer[bufferPos++] |= b >>> bufferRem; + bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos; + if (bufferBits == 512) { + // process data block: + processBuffer(); + // reset buffer: + bufferBits = bufferPos = 0; + } + buffer[bufferPos] = (byte) ((b << (8 - bufferRem)) & 0xff); + bufferBits += bufferRem; + // proceed to remaining data: + sourceBits -= 8; + sourcePos++; + } + // now 0 <= sourceBits <= 8; + // furthermore, all data (if any is left) is in source[sourcePos]. + if (sourceBits > 0) { + b = (source[sourcePos] << sourceGap) & 0xff; // bits are + // left-justified on b. + // process the remaining bits: + buffer[bufferPos] |= b >>> bufferRem; + } else { + b = 0; + } + if (bufferRem + sourceBits < 8) { + // all remaining data fits on buffer[bufferPos], and there still + // remains some space. + bufferBits += sourceBits; + } else { + // buffer[bufferPos] is full: + bufferPos++; + bufferBits += 8 - bufferRem; // bufferBits = 8*bufferPos; + sourceBits -= 8 - bufferRem; + // now 0 <= sourceBits < 8; furthermore, all data is in + // source[sourcePos]. + if (bufferBits == 512) { + // process data block: + processBuffer(); + // reset buffer: + bufferBits = bufferPos = 0; + } + buffer[bufferPos] = (byte) ((b << (8 - bufferRem)) & 0xff); + bufferBits += (int) sourceBits; + } + } + + /** + * Delivers string input data to the hashing algorithm. + * + * @param source + * plaintext data to hash (ASCII text string). + * + * This method maintains the invariant: bufferBits < 512 + */ + public void NESSIEadd(final String source) { + if (source.length() > 0) { + final byte[] data = new byte[source.length()]; + for (int i = 0; i < source.length(); i++) { + data[i] = (byte) source.charAt(i); + } + NESSIEadd(data, 8 * data.length); + } + } + + /** + * Get the hash value from the hashing state. + * + * This method uses the invariant: bufferBits < 512 + */ + public void NESSIEfinalize(final byte[] digest) { + // append a '1'-bit: + buffer[bufferPos] |= 0x80 >>> (bufferBits & 7); + bufferPos++; // all remaining bits on the current byte are set to zero. + // pad with zero bits to complete 512N + 256 bits: + if (bufferPos > 32) { + while (bufferPos < 64) { + buffer[bufferPos++] = 0; + } + // process data block: + processBuffer(); + // reset buffer: + bufferPos = 0; + } + while (bufferPos < 32) { + buffer[bufferPos++] = 0; + } + // append bit length of hashed data: + System.arraycopy(bitLength, 0, buffer, 32, 32); + // process data block: + processBuffer(); + // return the completed message digest: + for (int i = 0, j = 0; i < 8; i++, j += 8) { + final long h = hash[i]; + digest[j] = (byte) (h >>> 56); + digest[j + 1] = (byte) (h >>> 48); + digest[j + 2] = (byte) (h >>> 40); + digest[j + 3] = (byte) (h >>> 32); + digest[j + 4] = (byte) (h >>> 24); + digest[j + 5] = (byte) (h >>> 16); + digest[j + 6] = (byte) (h >>> 8); + digest[j + 7] = (byte) (h); + } + } + + /** + * Initialize the hashing state. + */ + public void NESSIEinit() { + Arrays.fill(bitLength, (byte) 0); + bufferBits = bufferPos = 0; + buffer[0] = 0; + Arrays.fill(hash, 0L); + } + + /** + * The core Whirlpool transform. + */ + protected void processBuffer() { + /* + * map the buffer to a block: + */ + for (int i = 0, j = 0; i < 8; i++, j += 8) { + block[i] = (((long) buffer[j]) << 56) ^ ((buffer[j + 1] & 0xffL) << 48) ^ ((buffer[j + 2] & 0xffL) << 40) ^ ((buffer[j + 3] & 0xffL) << 32) ^ ((buffer[j + 4] & 0xffL) << 24) + ^ ((buffer[j + 5] & 0xffL) << 16) ^ ((buffer[j + 6] & 0xffL) << 8) ^ ((buffer[j + 7] & 0xffL)); + } + /* + * compute and apply K^0 to the cipher state: + */ + for (int i = 0; i < 8; i++) { + state[i] = block[i] ^ (K[i] = hash[i]); + } + /* + * iterate over all rounds: + */ + for (int r = 1; r <= R; r++) { + /* + * compute K^r from K^{r-1}: + */ + for (int i = 0; i < 8; i++) { + L[i] = 0L; + for (int t = 0, s = 56; t < 8; t++, s -= 8) { + L[i] ^= C[t][(int) (K[(i - t) & 7] >>> s) & 0xff]; + } + } + for (int i = 0; i < 8; i++) { + K[i] = L[i]; + } + K[0] ^= rc[r]; + /* + * apply the r-th round transformation: + */ + for (int i = 0; i < 8; i++) { + L[i] = K[i]; + for (int t = 0, s = 56; t < 8; t++, s -= 8) { + L[i] ^= C[t][(int) (state[(i - t) & 7] >>> s) & 0xff]; + } + } + for (int i = 0; i < 8; i++) { + state[i] = L[i]; + } + } + /* + * apply the Miyaguchi-Preneel compression function: + */ + for (int i = 0; i < 8; i++) { + hash[i] ^= state[i] ^ block[i]; + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java b/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java new file mode 100644 index 0000000..1c0a786 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/WORDPRESS.java @@ -0,0 +1,115 @@ +package fr.xephi.authme.security.crypts; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Arrays; + +public class WORDPRESS implements EncryptionMethod { + + private static final String itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + private SecureRandom randomGen = new SecureRandom(); + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String comparedHash = crypt(password, hash); + return comparedHash.equals(hash); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + byte random[] = new byte[6]; + this.randomGen.nextBytes(random); + return crypt(password, gensaltPrivate(stringToUtf8(new String(random)))); + } + + private String crypt(String password, String setting) { + String output = "*0"; + if (((setting.length() < 2) ? setting : setting.substring(0, 2)).equalsIgnoreCase(output)) { + output = "*1"; + } + String id = (setting.length() < 3) ? setting : setting.substring(0, 3); + if (!(id.equals("$P$") || id.equals("$H$"))) { + return output; + } + int countLog2 = itoa64.indexOf(setting.charAt(3)); + if (countLog2 < 7 || countLog2 > 30) { + return output; + } + int count = 1 << countLog2; + String salt = setting.substring(4, 4 + 8); + if (salt.length() != 8) { + return output; + } + MessageDigest md; + try { + md = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return output; + } + byte[] pass = stringToUtf8(password); + byte[] hash = md.digest(stringToUtf8(salt + password)); + do { + byte[] t = new byte[hash.length + pass.length]; + System.arraycopy(hash, 0, t, 0, hash.length); + System.arraycopy(pass, 0, t, hash.length, pass.length); + hash = md.digest(t); + } while (--count > 0); + output = setting.substring(0, 12); + output += encode64(hash, 16); + return output; + } + + private String encode64(byte[] src, int count) { + int i, value; + StringBuilder output = new StringBuilder(); + i = 0; + + if (src.length < count) { + byte[] t = new byte[count]; + System.arraycopy(src, 0, t, 0, src.length); + Arrays.fill(t, src.length, count - 1, (byte) 0); + } + + do { + value = src[i] + (src[i] < 0 ? 256 : 0); + ++i; + output.append(itoa64.charAt(value & 63)); + if (i < count) { + value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 8; + } + output.append(itoa64.charAt((value >> 6) & 63)); + if (i++ >= count) { + break; + } + if (i < count) { + value |= (src[i] + (src[i] < 0 ? 256 : 0)) << 16; + } + output.append(itoa64.charAt((value >> 12) & 63)); + if (i++ >= count) { + break; + } + output.append(itoa64.charAt((value >> 18) & 63)); + } while (i < count); + return output.toString(); + } + + private String gensaltPrivate(byte[] input) { + String output = "$P$"; + int iterationCountLog2 = 8; + output += itoa64.charAt(Math.min(iterationCountLog2 + 5, 30)); + output += encode64(input, 6); + return output; + } + + private byte[] stringToUtf8(String string) { + try { + return string.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException("This system doesn't support UTF-8!", e); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/XAUTH.java b/src/main/java/fr/xephi/authme/security/crypts/XAUTH.java new file mode 100644 index 0000000..0c63171 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/XAUTH.java @@ -0,0 +1,30 @@ +package fr.xephi.authme.security.crypts; + +import java.security.NoSuchAlgorithmException; + +public class XAUTH implements EncryptionMethod { + + public static String getWhirlpool(String message) { + WHIRLPOOL w = new WHIRLPOOL(); + byte[] digest = new byte[WHIRLPOOL.DIGESTBYTES]; + w.NESSIEinit(); + w.NESSIEadd(message); + w.NESSIEfinalize(digest); + return WHIRLPOOL.display(digest); + } + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length()); + String salt = hash.substring(saltPos, saltPos + 12); + return hash.equals(getHash(password, salt, "")); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + String hash = getWhirlpool(salt + password).toLowerCase(); + int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length()); + return hash.substring(0, saltPos) + salt + hash.substring(saltPos); + } + +} diff --git a/src/main/java/fr/xephi/authme/security/crypts/XF.java b/src/main/java/fr/xephi/authme/security/crypts/XF.java new file mode 100644 index 0000000..6728925 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/crypts/XF.java @@ -0,0 +1,52 @@ +package fr.xephi.authme.security.crypts; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import fr.xephi.authme.AuthMe; + +public class XF implements EncryptionMethod { + + @Override + public boolean comparePassword(String hash, String password, String playerName) throws NoSuchAlgorithmException { + String salt = AuthMe.getInstance().database.getAuth(playerName).getSalt(); + return hash.equals(regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", salt)); + } + + @Override + public String getHash(String password, String salt, String name) throws NoSuchAlgorithmException { + return getSHA256(getSHA256(password) + regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", salt)); + } + + public String getSHA256(String password) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(password.getBytes()); + byte byteData[] = md.digest(); + StringBuffer sb = new StringBuffer(); + for (byte element : byteData) { + sb.append(Integer.toString((element & 0xff) + 0x100, 16).substring(1)); + } + StringBuffer hexString = new StringBuffer(); + for (byte element : byteData) { + String hex = Integer.toHexString(0xff & element); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + return hexString.toString(); + } + + public String regmatch(String pattern, String line) { + List allMatches = new ArrayList<>(); + Matcher m = Pattern.compile(pattern).matcher(line); + while (m.find()) { + allMatches.add(m.group(1)); + } + return allMatches.get(0); + } +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/BinTools.java b/src/main/java/fr/xephi/authme/security/pbkdf2/BinTools.java new file mode 100644 index 0000000..2a4fc81 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/BinTools.java @@ -0,0 +1,121 @@ +package fr.xephi.authme.security.pbkdf2; + +/** + *

+ * Free auxiliary functions. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public class BinTools { + + public static final String hex = "0123456789ABCDEF"; + + /** + * Simple binary-to-hexadecimal conversion. + * + * @param b + * Input bytes. May be null. + * @return Hexadecimal representation of b. Uppercase A-F, two characters + * per byte. Empty string on null input. + */ + public static String bin2hex(final byte[] b) { + if (b == null) { + return ""; + } + StringBuffer sb = new StringBuffer(2 * b.length); + for (int i = 0; i < b.length; i++) { + int v = (256 + b[i]) % 256; + sb.append(hex.charAt((v / 16) & 15)); + sb.append(hex.charAt((v % 16) & 15)); + } + return sb.toString(); + } + + /** + * Convert hex digit to numerical value. + * + * @param c + * 0-9, a-f, A-F allowd. + * @return 0-15 + * @throws IllegalArgumentException + * on non-hex character + */ + public static int hex2bin(char c) { + if (c >= '0' && c <= '9') { + return (c - '0'); + } + if (c >= 'A' && c <= 'F') { + return (c - 'A' + 10); + } + if (c >= 'a' && c <= 'f') { + return (c - 'a' + 10); + } + throw new IllegalArgumentException("Input string may only contain hex digits, but found '" + c + "'"); + } + + /** + * Convert hex string to array of bytes. + * + * @param s + * String containing hexadecimal digits. May be null + * . On odd length leading zero will be assumed. + * @return Array on bytes, non-null. + * @throws IllegalArgumentException + * when string contains non-hex character + */ + public static byte[] hex2bin(final String s) { + String m = s; + if (s == null) { + // Allow empty input string. + m = ""; + } else if (s.length() % 2 != 0) { + // Assume leading zero for odd string length + m = "0" + s; + } + byte r[] = new byte[m.length() / 2]; + for (int i = 0, n = 0; i < m.length(); n++) { + char h = m.charAt(i++); + char l = m.charAt(i++); + r[n] = (byte) (hex2bin(h) * 16 + hex2bin(l)); + } + return r; + } + + public static void main(String[] args) { + byte b[] = new byte[256]; + byte bb = 0; + for (int i = 0; i < 256; i++) { + b[i] = bb++; + } + String s = bin2hex(b); + byte c[] = hex2bin(s); + String t = bin2hex(c); + if (!s.equals(t)) { + throw new AssertionError("Mismatch"); + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java b/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java new file mode 100644 index 0000000..d7f3ebe --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/MacBasedPRF.java @@ -0,0 +1,94 @@ +package fr.xephi.authme.security.pbkdf2; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * Default PRF implementation based on standard javax.crypt.Mac mechanisms. + * + *
+ *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public class MacBasedPRF implements PRF { + + protected int hLen; + + protected Mac mac; + + protected String macAlgorithm; + + /** + * Create Mac-based Pseudo Random Function. + * + * @param macAlgorithm + * Mac algorithm to use, i.e. HMacSHA1 or HMacMD5. + */ + public MacBasedPRF(String macAlgorithm) { + this.macAlgorithm = macAlgorithm; + try { + mac = Mac.getInstance(macAlgorithm); + hLen = mac.getMacLength(); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } + + public MacBasedPRF(String macAlgorithm, String provider) { + this.macAlgorithm = macAlgorithm; + try { + mac = Mac.getInstance(macAlgorithm, provider); + hLen = mac.getMacLength(); + } catch (NoSuchAlgorithmException | NoSuchProviderException e) { + throw new RuntimeException(e); + } + } + + public byte[] doFinal(byte[] M) { + byte[] r = mac.doFinal(M); + return r; + } + + public int getHLen() { + return hLen; + } + + public void init(byte[] P) { + try { + mac.init(new SecretKeySpec(P, macAlgorithm)); + } catch (InvalidKeyException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2.java b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2.java new file mode 100644 index 0000000..7c19368 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2.java @@ -0,0 +1,99 @@ +package fr.xephi.authme.security.pbkdf2; + +/** + *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public interface PBKDF2 { + + /** + * Convert String-based input to internal byte array, then invoke PBKDF2. + * Desired key length defaults to Pseudo Random Function block size. + * + * @param inputPassword + * Candidate password to compute the derived key for. + * @return internal byte array + */ + public abstract byte[] deriveKey(String inputPassword); + + /** + * Convert String-based input to internal byte array, then invoke PBKDF2. + * + * @param inputPassword + * Candidate password to compute the derived key for. + * @param dkLen + * Specify desired key length + * @return internal byte array + */ + public abstract byte[] deriveKey(String inputPassword, int dkLen); + + /** + * Allow reading of configured parameters. + * + * @return Currently set parameters. + */ + public abstract PBKDF2Parameters getParameters(); + + /** + * Get currently set Pseudo Random Function. + * + * @return Currently set Pseudo Random Function + */ + public abstract PRF getPseudoRandomFunction(); + + /** + * Allow setting of configured parameters. + * + * @param parameters + */ + public abstract void setParameters(PBKDF2Parameters parameters); + + /** + * Set the Pseudo Random Function to use. Note that deriveKeys/getPRF does + * init this object using the supplied candidate password. If this is + * undesired, one has to override getPRF. + * + * @param prf + * Pseudo Random Function to set. + */ + public abstract void setPseudoRandomFunction(PRF prf); + + /** + * Convert String-based input to internal byte arrays, then invoke PBKDF2 + * and verify result against the reference data that is supplied in the + * PBKDF2Parameters. + * + * @param inputPassword + * Candidate password to compute the derived key for. + * @return true password match; false incorrect + * password + */ + public abstract boolean verifyKey(String inputPassword); +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Engine.java b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Engine.java new file mode 100644 index 0000000..4fd51c9 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Engine.java @@ -0,0 +1,355 @@ +package fr.xephi.authme.security.pbkdf2; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +/** + *

+ * Request for Comments: 2898 PKCS #5: Password-Based Cryptography Specification + *

+ * Version 2.0 + * + *

+ * PBKDF2 (P, S, c, dkLen) + * + *

+ * Options: + *

    + *
  • PRF underlying pseudorandom function (hLen denotes the length in octets + * of the pseudorandom function output). PRF is pluggable.
  • + *
+ * + *

+ * Input: + *

    + *
  • P password, an octet string
  • + *
  • S salt, an octet string
  • + *
  • c iteration count, a positive integer
  • + *
  • dkLen intended length in octets of the derived key, a positive integer, + * at most (2^32 - 1) * hLen
  • + *
+ * + *

+ * Output: + *

    + *
  • DK derived key, a dkLen-octet string
  • + *
+ * + *
+ *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see + * http://www. + * gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @see RFC 2898 + * @author Matthias Gärtner + * @version 1.0 + */ +public class PBKDF2Engine implements PBKDF2 { + + protected PBKDF2Parameters parameters; + + protected PRF prf; + + /** + * Constructor for PBKDF2 implementation object. PBKDF2 parameters must be + * passed later. + */ + public PBKDF2Engine() { + this.parameters = null; + prf = null; + } + + /** + * Constructor for PBKDF2 implementation object. PBKDF2 parameters are + * passed so that this implementation knows iteration count, method to use + * and String encoding. + * + * @param parameters + * Data holder for iteration count, method to use et cetera. + */ + public PBKDF2Engine(PBKDF2Parameters parameters) { + this.parameters = parameters; + prf = null; + } + + /** + * Constructor for PBKDF2 implementation object. PBKDF2 parameters are + * passed so that this implementation knows iteration count, method to use + * and String encoding. + * + * @param parameters + * Data holder for iteration count, method to use et cetera. + * @param prf + * Supply customer Pseudo Random Function. + */ + public PBKDF2Engine(PBKDF2Parameters parameters, PRF prf) { + this.parameters = parameters; + this.prf = prf; + } + + /** + * Convenience client function. Convert supplied password with random 8-byte + * salt and 1000 iterations using HMacSHA1. Assume that password is in + * ISO-8559-1 encoding. Output result as + * "Salt:iteration-count:PBKDF2" with binary data in hexadecimal + * encoding. + * + * Example: Password "password" (without the quotes) leads to + * 48290A0B96C426C3:1000:973899B1D4AFEB3ED371060D0797E0EE0142BD04 + * + * @param args + * Supply the password as argument. + * @throws IOException + * @throws NoSuchAlgorithmException + */ + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { + String password = "password"; + String candidate = null; + PBKDF2Formatter formatter = new PBKDF2HexFormatter(); + + if (args.length >= 1) { + password = args[0]; + } + if (args.length >= 2) { + candidate = args[1]; + } + if (candidate == null) { + // Creation mode + SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); + byte[] salt = new byte[8]; + sr.nextBytes(salt); + int iterations = 1000; + PBKDF2Parameters p = new PBKDF2Parameters("HmacSHA1", "ISO-8859-1", salt, iterations); + PBKDF2Engine e = new PBKDF2Engine(p); + p.setDerivedKey(e.deriveKey(password)); + candidate = formatter.toString(p); + } else { + // Verification mode + PBKDF2Parameters p = new PBKDF2Parameters(); + p.setHashAlgorithm("HmacSHA1"); + p.setHashCharset("ISO-8859-1"); + if (formatter.fromString(p, candidate)) { + throw new IllegalArgumentException("Candidate data does not have correct format (\"" + candidate + "\")"); + } + PBKDF2Engine e = new PBKDF2Engine(p); + boolean verifyOK = e.verifyKey(password); + System.exit(verifyOK ? 0 : 1); + } + } + + public byte[] deriveKey(String inputPassword) { + return deriveKey(inputPassword, 0); + } + + public byte[] deriveKey(String inputPassword, int dkLen) { + byte[] r = null; + byte P[] = null; + String charset = parameters.getHashCharset(); + if (inputPassword == null) { + inputPassword = ""; + } + try { + if (charset == null) { + P = inputPassword.getBytes(); + } else { + P = inputPassword.getBytes(charset); + } + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + assertPRF(P); + if (dkLen == 0) { + dkLen = prf.getHLen(); + } + r = PBKDF2(prf, parameters.getSalt(), parameters.getIterationCount(), dkLen); + return r; + } + + public PBKDF2Parameters getParameters() { + return parameters; + } + + public PRF getPseudoRandomFunction() { + return prf; + } + + public void setParameters(PBKDF2Parameters parameters) { + this.parameters = parameters; + } + + public void setPseudoRandomFunction(PRF prf) { + this.prf = prf; + } + + public boolean verifyKey(String inputPassword) { + byte[] referenceKey = getParameters().getDerivedKey(); + if (referenceKey == null || referenceKey.length == 0) { + return false; + } + byte[] inputKey = deriveKey(inputPassword, referenceKey.length); + + if (inputKey == null || inputKey.length != referenceKey.length) { + return false; + } + for (int i = 0; i < inputKey.length; i++) { + if (inputKey[i] != referenceKey[i]) { + return false; + } + } + return true; + } + + /** + * Function F. + * + * @see RFC 2898 5.2 Step + * 3. + * @param dest + * Destination byte buffer + * @param offset + * Offset into destination byte buffer + * @param prf + * Pseudo Random Function + * @param S + * Salt as array of bytes + * @param c + * Iteration count + * @param blockIndex + */ + protected void _F(byte[] dest, int offset, PRF prf, byte[] S, int c, int blockIndex) { + int hLen = prf.getHLen(); + byte U_r[] = new byte[hLen]; + + // U0 = S || INT (i); + byte U_i[] = new byte[S.length + 4]; + System.arraycopy(S, 0, U_i, 0, S.length); + INT(U_i, S.length, blockIndex); + + for (int i = 0; i < c; i++) { + U_i = prf.doFinal(U_i); + xor(U_r, U_i); + } + System.arraycopy(U_r, 0, dest, offset, hLen); + } + + /** + * Factory method. Default implementation is (H)MAC-based. To be overridden + * in derived classes. + * + * @param P + * User-supplied candidate password as array of bytes. + */ + protected void assertPRF(byte[] P) { + if (prf == null) { + prf = new MacBasedPRF(parameters.getHashAlgorithm()); + } + prf.init(P); + } + + /** + * Integer division with ceiling function. + * + * @see RFC 2898 5.2 Step + * 2. + * @param a + * @param b + * @return ceil(a/b) + */ + protected int ceil(int a, int b) { + int m = 0; + if (a % b > 0) { + m = 1; + } + return a / b + m; + } + + /** + * Four-octet encoding of the integer i, most significant octet first. + * + * @see RFC 2898 5.2 Step + * 3. + * @param dest + * @param offset + * @param i + */ + protected void INT(byte[] dest, int offset, int i) { + dest[offset + 0] = (byte) (i / (256 * 256 * 256)); + dest[offset + 1] = (byte) (i / (256 * 256)); + dest[offset + 2] = (byte) (i / (256)); + dest[offset + 3] = (byte) (i); + } + + /** + * Core Password Based Key Derivation Function 2. + * + * @see RFC 2898 5.2 + * @param prf + * Pseudo Random Function (i.e. HmacSHA1) + * @param S + * Salt as array of bytes. null means no salt. + * @param c + * Iteration count (see RFC 2898 4.2) + * @param dkLen + * desired length of derived key. + * @return internal byte array + */ + protected byte[] PBKDF2(PRF prf, byte[] S, int c, int dkLen) { + if (S == null) { + S = new byte[0]; + } + int hLen = prf.getHLen(); + int l = ceil(dkLen, hLen); + int r = dkLen - (l - 1) * hLen; + byte T[] = new byte[l * hLen]; + int ti_offset = 0; + for (int i = 1; i <= l; i++) { + _F(T, ti_offset, prf, S, c, i); + ti_offset += hLen; + } + if (r < hLen) { + // Incomplete last block + byte DK[] = new byte[dkLen]; + System.arraycopy(T, 0, DK, 0, dkLen); + return DK; + } + return T; + } + + /** + * Block-Xor. Xor source bytes into destination byte buffer. Destination + * buffer must be same length or less than source buffer. + * + * @param dest + * @param src + */ + protected void xor(byte[] dest, byte[] src) { + for (int i = 0; i < dest.length; i++) { + dest[i] ^= src[i]; + } + } +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Formatter.java b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Formatter.java new file mode 100644 index 0000000..943a90a --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Formatter.java @@ -0,0 +1,55 @@ +package fr.xephi.authme.security.pbkdf2; + +/** + *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public interface PBKDF2Formatter { + + /** + * Convert String to parameters. Depending on actual implementation, it may + * be required to set further fields externally. + * + * @param s + * String representation of parameters to decode. + * @return false syntax OK, true some syntax + * issue. + */ + public abstract boolean fromString(PBKDF2Parameters p, String s); + + /** + * Convert parameters to String. + * + * @param p + * Parameters object to output. + * @return String representation + */ + public abstract String toString(PBKDF2Parameters p); +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2HexFormatter.java b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2HexFormatter.java new file mode 100644 index 0000000..05af16d --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2HexFormatter.java @@ -0,0 +1,60 @@ +package fr.xephi.authme.security.pbkdf2; + +/** + *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public class PBKDF2HexFormatter implements PBKDF2Formatter { + + public boolean fromString(PBKDF2Parameters p, String s) { + if (p == null || s == null) { + return true; + } + + String[] p123 = s.split(":"); + if (p123 == null || p123.length != 3) { + return true; + } + + byte salt[] = BinTools.hex2bin(p123[0]); + int iterationCount = Integer.parseInt(p123[1]); + byte bDK[] = BinTools.hex2bin(p123[2]); + + p.setSalt(salt); + p.setIterationCount(iterationCount); + p.setDerivedKey(bDK); + return false; + } + + public String toString(PBKDF2Parameters p) { + String s = BinTools.bin2hex(p.getSalt()) + ":" + String.valueOf(p.getIterationCount()) + ":" + BinTools.bin2hex(p.getDerivedKey()); + return s; + } +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Parameters.java b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Parameters.java new file mode 100644 index 0000000..741b594 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/PBKDF2Parameters.java @@ -0,0 +1,149 @@ +package fr.xephi.authme.security.pbkdf2; + +/** + *

+ * Parameter data holder for PBKDF2 configuration. + *

+ * + *
+ *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public class PBKDF2Parameters { + + /** + * The derived key is actually only a convenience to store a reference + * derived key. It is not used during computation. + */ + protected byte[] derivedKey; + + protected String hashAlgorithm; + + protected String hashCharset; + + protected int iterationCount; + + protected byte[] salt; + + /** + * Constructor. Defaults to null for byte arrays, UTF-8 as + * character set and 1000 for iteration count. + * + */ + public PBKDF2Parameters() { + this.hashAlgorithm = null; + this.hashCharset = "UTF-8"; + this.salt = null; + this.iterationCount = 1000; + this.derivedKey = null; + } + + /** + * Constructor. + * + * @param hashAlgorithm + * for example HMacSHA1 or HMacMD5 + * @param hashCharset + * for example UTF-8 + * @param salt + * Salt as byte array, may be null (not recommended) + * @param iterationCount + * Number of iterations to execute. Recommended value 1000. + */ + public PBKDF2Parameters(String hashAlgorithm, String hashCharset, byte[] salt, int iterationCount) { + this.hashAlgorithm = hashAlgorithm; + this.hashCharset = hashCharset; + this.salt = salt; + this.iterationCount = iterationCount; + this.derivedKey = null; + } + + /** + * Constructor. + * + * @param hashAlgorithm + * for example HMacSHA1 or HMacMD5 + * @param hashCharset + * for example UTF-8 + * @param salt + * Salt as byte array, may be null (not recommended) + * @param iterationCount + * Number of iterations to execute. Recommended value 1000. + * @param derivedKey + * Convenience data holder, not used during computation. + */ + public PBKDF2Parameters(String hashAlgorithm, String hashCharset, byte[] salt, int iterationCount, byte[] derivedKey) { + this.hashAlgorithm = hashAlgorithm; + this.hashCharset = hashCharset; + this.salt = salt; + this.iterationCount = iterationCount; + this.derivedKey = derivedKey; + } + + public byte[] getDerivedKey() { + return derivedKey; + } + + public String getHashAlgorithm() { + return hashAlgorithm; + } + + public String getHashCharset() { + return hashCharset; + } + + public int getIterationCount() { + return iterationCount; + } + + public byte[] getSalt() { + return salt; + } + + public void setDerivedKey(byte[] derivedKey) { + this.derivedKey = derivedKey; + } + + public void setHashAlgorithm(String hashAlgorithm) { + this.hashAlgorithm = hashAlgorithm; + } + + public void setHashCharset(String hashCharset) { + this.hashCharset = hashCharset; + } + + public void setIterationCount(int iterationCount) { + this.iterationCount = iterationCount; + } + + public void setSalt(byte[] salt) { + this.salt = salt; + } +} diff --git a/src/main/java/fr/xephi/authme/security/pbkdf2/PRF.java b/src/main/java/fr/xephi/authme/security/pbkdf2/PRF.java new file mode 100644 index 0000000..1d98442 --- /dev/null +++ b/src/main/java/fr/xephi/authme/security/pbkdf2/PRF.java @@ -0,0 +1,61 @@ +package fr.xephi.authme.security.pbkdf2; + +/** + *

+ * A free Java implementation of Password Based Key Derivation Function 2 as + * defined by RFC 2898. Copyright (c) 2007 Matthias Gärtner + *

+ *

+ * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + *

+ *

+ * This library 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 Lesser General Public License for more + * details. + *

+ *

+ * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *

+ *

+ * For Details, see http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + *

+ * + * @author Matthias Gärtner + * @version 1.0 + */ +public interface PRF { + + /** + * Pseudo Random Function + * + * @param M + * Input data/message etc. Together with any data supplied during + * initilization. + * @return Random bytes of hLen length. + */ + public byte[] doFinal(byte[] M); + + /** + * Query block size of underlying algorithm/mechanism. + * + * @return block size + */ + public int getHLen(); + + /** + * Initialize this instance with the user-supplied password. + * + * @param P + * The password supplied as array of bytes. It is the caller's + * task to convert String passwords to bytes as appropriate. + */ + public void init(byte[] P); +} diff --git a/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java b/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java new file mode 100644 index 0000000..815fdd3 --- /dev/null +++ b/src/main/java/fr/xephi/authme/settings/CustomConfiguration.java @@ -0,0 +1,80 @@ +package fr.xephi.authme.settings; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; + +public class CustomConfiguration extends YamlConfiguration { + + private File configFile; + + public CustomConfiguration(File file) { + this.configFile = file; + load(); + } + + public File getConfigFile() { + return configFile; + } + + public void load() { + try { + super.load(configFile); + } catch (FileNotFoundException e) { + ConsoleLogger.showError("Could not find " + configFile.getName() + ", creating new one..."); + reLoad(); + } catch (IOException e) { + ConsoleLogger.showError("Could not load " + configFile.getName()); + } catch (InvalidConfigurationException e) { + ConsoleLogger.showError(configFile.getName() + " is no valid configuration file"); + } + } + + public boolean loadResource(File file) { + if (!file.exists()) { + try { + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { + return false; + } + int i = file.getPath().indexOf("AuthMe"); + if (i > -1) { + String path = file.getPath().substring(i + 6).replace('\\', '/'); + InputStream is = AuthMe.class.getResourceAsStream(path); + Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return true; + } + } catch (Exception e) { + ConsoleLogger.writeStackTrace(e); + ConsoleLogger.showError("Failed to load config from JAR"); + } + } + return false; + } + + public boolean reLoad() { + boolean out = true; + if (!configFile.exists()) { + out = loadResource(configFile); + } + if (out) + load(); + return out; + } + + public void save() { + try { + super.save(configFile); + } catch (IOException ex) { + ConsoleLogger.showError("Could not save config to " + configFile.getName()); + } + } +} diff --git a/src/main/java/fr/xephi/authme/settings/Messages.java b/src/main/java/fr/xephi/authme/settings/Messages.java new file mode 100644 index 0000000..e21fe4c --- /dev/null +++ b/src/main/java/fr/xephi/authme/settings/Messages.java @@ -0,0 +1,68 @@ +package fr.xephi.authme.settings; + +import java.io.File; + +import org.bukkit.command.CommandSender; + +import fr.xephi.authme.ConsoleLogger; + +public class Messages extends CustomConfiguration { + + private static Messages singleton = null; + private String lang = "en"; + + public Messages(File file, String lang) { + super(file); + load(); + singleton = this; + this.lang = lang; + } + + public static Messages getInstance() { + if (singleton == null) { + singleton = new Messages(Settings.messageFile, Settings.messagesLanguage); + } + return singleton; + } + + public void reloadMessages() { + singleton = new Messages(Settings.messageFile, Settings.messagesLanguage); + } + + public void send(CommandSender sender, String msg) { + if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) + singleton.reloadMessages(); + String loc = (String) singleton.get(msg); + if (loc == null) { + loc = "Error with Translation files, please contact the admin for verify or update translation"; + ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + getConfigFile() + " !"); + } + for (String l : loc.split("&n")) { + sender.sendMessage(l.replace("&", "\u00a7")); + } + } + + public String[] send(String msg) { + if (!Settings.messagesLanguage.equalsIgnoreCase(singleton.lang)) { + singleton.reloadMessages(); + } + String s = (String) singleton.get(msg); + if (s == null) { + ConsoleLogger.showError("Error with the " + msg + " translation, verify in your " + getConfigFile() + " !"); + String[] loc = new String[1]; + loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files"; + return (loc); + } + int i = s.split("&n").length; + String[] loc = new String[i]; + int a; + for (a = 0; a < i; a++) { + loc[a] = ((String) this.get(msg)).split("&n")[a].replace("&", "\u00a7"); + } + if (loc.length == 0) { + loc[0] = "Error with " + msg + " translation; Please contact the admin for verify or update translation files"; + } + return loc; + } + +} diff --git a/src/main/java/fr/xephi/authme/settings/OtherAccounts.java b/src/main/java/fr/xephi/authme/settings/OtherAccounts.java new file mode 100644 index 0000000..7f0d749 --- /dev/null +++ b/src/main/java/fr/xephi/authme/settings/OtherAccounts.java @@ -0,0 +1,69 @@ +package fr.xephi.authme.settings; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +/** + * + * @author Xephi59 + */ +public class OtherAccounts extends CustomConfiguration { + + private static OtherAccounts others = null; + + public OtherAccounts() { + super(new File("." + File.separator + "plugins" + File.separator + "AuthMe" + File.separator + "otheraccounts.yml")); + others = this; + load(); + save(); + } + + public static OtherAccounts getInstance() { + if (others == null) { + others = new OtherAccounts(); + } + return others; + } + + public void addPlayer(UUID uuid) { + try { + Player player = Bukkit.getPlayer(uuid); + if (player == null) + return; + if (!this.getStringList(uuid.toString()).contains(player.getName())) { + this.getStringList(uuid.toString()).add(player.getName()); + save(); + } + } catch (NoSuchMethodError | Exception e) { + // ignore + } + } + + public void clear(UUID uuid) { + set(uuid.toString(), new ArrayList()); + save(); + } + + public List getAllPlayersByUUID(UUID uuid) { + return this.getStringList(uuid.toString()); + } + + public void removePlayer(UUID uuid) { + try { + Player player = Bukkit.getPlayer(uuid); + if (player == null) + return; + if (this.getStringList(uuid.toString()).contains(player.getName())) { + this.getStringList(uuid.toString()).remove(player.getName()); + save(); + } + } catch (NoSuchMethodError | Exception e) { + // ignore + } + } +} diff --git a/src/main/java/fr/xephi/authme/settings/Settings.java b/src/main/java/fr/xephi/authme/settings/Settings.java new file mode 100644 index 0000000..60637d3 --- /dev/null +++ b/src/main/java/fr/xephi/authme/settings/Settings.java @@ -0,0 +1,635 @@ +package fr.xephi.authme.settings; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.bukkit.configuration.file.YamlConfiguration; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.datasource.DataSource.DataSourceType; +import fr.xephi.authme.security.HashAlgorithm; + +public final class Settings extends YamlConfiguration { + + public static List allowCommands; + // This is not an option! + public static boolean antiBotInAction = false; + public static final File APLUGIN_FOLDER = AuthMe.getInstance().getDataFolder(); + public static final File AUTH_FILE = new File(APLUGIN_FOLDER, "auths.db"); + + public static final File CACHE_FOLDER = new File(APLUGIN_FOLDER, "cache"); + + public static List countries; + public static List countriesBlacklist; + public static List emailBlacklist; + public static List emailWhitelist; + public static List forceCommands; + public static List forceCommandsAsConsole; + + public static List forceRegisterCommands; + public static List forceRegisterCommandsAsConsole; + public static DataSourceType getDataSource; + public static List getForcedWorlds; + public static List getJoinPermissions; + public static List getMySQLOtherUsernameColumn; + public static String getNickRegex, getUnloggedinGroup, getMySQLHost, getMySQLPort, getMySQLUsername, getMySQLPassword, getMySQLDatabase, getMySQLTablename, getMySQLColumnName, + getMySQLColumnPassword, getMySQLColumnIp, getMySQLColumnLastLogin, getMySQLColumnSalt, getMySQLColumnGroup, getMySQLColumnEmail, unRegisteredGroup, backupWindowsPath, getRegisteredGroup, + messagesLanguage, getMySQLlastlocX, getMySQLlastlocY, getMySQLlastlocZ, rakamakUsers, rakamakUsersIp, getmailAccount, getmailPassword, getmailSMTP, getMySQLColumnId, getmailSenderName, + getMailSubject, getMailText, getMySQLlastlocWorld, defaultWorld, getPhpbbPrefix, getWordPressPrefix, getMySQLColumnLogged, spawnPriority, crazyloginFileName, getPassRegex, + getMySQLColumnRealName; + public static HashAlgorithm getPasswordHash; + public static List getRestrictedIp; + public static List getUnrestrictedName; + public static int getWarnMessageInterval, getSessionTimeout, getRegistrationTimeout, getMaxNickLength, getMinNickLength, getPasswordMinLen, getMovementRadius, getmaxRegPerIp, getNonActivatedGroup, + passwordMaxLength, getRecoveryPassLength, getMailPort, maxLoginTry, captchaLength, saltLength, getmaxRegPerEmail, bCryptLog2Rounds, getPhpbbGroup, antiBotSensibility, antiBotDuration, + delayRecall, getMaxLoginPerIp, getMaxJoinPerIp, getMySQLMaxConnections; + public static boolean isPermissionCheckEnabled, isRegistrationEnabled, isForcedRegistrationEnabled, isTeleportToSpawnEnabled, isSessionsEnabled, isChatAllowed, isAllowRestrictedIp, + isMovementAllowed, isKickNonRegisteredEnabled, isForceSingleSessionEnabled, isForceSpawnLocOnJoinEnabled, isSaveQuitLocationEnabled, isForceSurvivalModeEnabled, isResetInventoryIfCreative, + isCachingEnabled, isKickOnWrongPasswordEnabled, getEnablePasswordVerifier, protectInventoryBeforeLogInEnabled, isBackupActivated, isBackupOnStart, isBackupOnStop, isStopEnabled, + reloadSupport, rakamakUseIp, noConsoleSpam, removePassword, displayOtherAccounts, useCaptcha, emailRegistration, multiverse, bungee, banUnsafeIp, doubleEmailCheck, sessionExpireOnIpChange, + disableSocialSpy, forceOnlyAfterLogin, useEssentialsMotd, usePurge, purgePlayerDat, purgeEssentialsFile, supportOldPassword, purgeLimitedCreative, purgeAntiXray, purgePermissions, + enableProtection, enableAntiBot, recallEmail, useWelcomeMessage, broadcastWelcomeMessage, forceRegKick, forceRegLogin, checkVeryGames, delayJoinMessage, noTeleport, applyBlindEffect, + customAttributes, generateImage, isRemoveSpeedEnabled; + public static final File LOG_FILE = new File(APLUGIN_FOLDER, "authme.log"); + public static File messageFile; + public static final File MODULE_FOLDER = new File(APLUGIN_FOLDER, "modules"); + public static int purgeDelay = 60; + public static final File SETTINGS_FILE = new File(APLUGIN_FOLDER, "config.yml"); + public static List unsafePasswords; + public static boolean useLogging = false; + + public static List welcomeMsg; + + private static Settings instance; + + private static AuthMe plugin; + + protected static YamlConfiguration configFile; + + public Settings(final AuthMe pl) { + instance = this; + plugin = pl; + configFile = (YamlConfiguration) plugin.getConfig(); + } + + public static String checkLang(final String lang) { + if (new File(APLUGIN_FOLDER, "messages" + File.separator + "messages_" + lang + ".yml").exists()) { + ConsoleLogger.info("Set Language to: " + lang); + return lang; + } + if (AuthMe.class.getResourceAsStream("/messages/messages_" + lang + ".yml") != null) { + ConsoleLogger.info("Set Language to: " + lang); + return lang; + } + ConsoleLogger.info("Language file not found for " + lang + ", set to default language: en !"); + return "en"; + } + + /** + * Config option for setting and check restricted user by username;ip , + * return false if ip and name doesnt amtch with player that join the + * server, so player has a restricted access + */ + public static boolean getRestrictedIp(final String name, final String ip) { + + final Iterator iter = getRestrictedIp.iterator(); + boolean trueonce = false; + boolean namefound = false; + while (iter.hasNext()) { + final String[] args = iter.next().split(";"); + final String testname = args[0]; + final String testip = args[1]; + if (testname.equalsIgnoreCase(name)) { + namefound = true; + if (testip.equalsIgnoreCase(ip)) { + trueonce = true; + } + } + } + return !namefound || trueonce; + } + + public static boolean isEmailCorrect(final String email) { + if (!email.contains("@")) { + return false; + } + if (email.equalsIgnoreCase("your@email.com")) { + return false; + } + final String emailDomain = email.split("@")[1]; + boolean correct = true; + if (emailWhitelist != null && !emailWhitelist.isEmpty()) { + for (final String domain : emailWhitelist) { + if (!domain.equalsIgnoreCase(emailDomain)) { + correct = false; + } else { + correct = true; + break; + } + } + return correct; + } + if (emailBlacklist != null && !emailBlacklist.isEmpty()) { + for (final String domain : emailBlacklist) { + if (domain.equalsIgnoreCase(emailDomain)) { + correct = false; + break; + } + } + } + return correct; + } + + public static void loadVariables() { + messagesLanguage = checkLang(configFile.getString("settings.messagesLanguage", "en").toLowerCase()); + isPermissionCheckEnabled = configFile.getBoolean("permission.EnablePermissionCheck", false); + isForcedRegistrationEnabled = configFile.getBoolean("settings.registration.force", true); + isRegistrationEnabled = configFile.getBoolean("settings.registration.enabled", true); + isTeleportToSpawnEnabled = configFile.getBoolean("settings.restrictions.teleportUnAuthedToSpawn", false); + getWarnMessageInterval = configFile.getInt("settings.registration.messageInterval", 5); + isSessionsEnabled = configFile.getBoolean("settings.sessions.enabled", false); + getSessionTimeout = configFile.getInt("settings.sessions.timeout", 10); + getRegistrationTimeout = configFile.getInt("settings.restrictions.timeout", 30); + isChatAllowed = configFile.getBoolean("settings.restrictions.allowChat", false); + getMaxNickLength = configFile.getInt("settings.restrictions.maxNicknameLength", 20); + getMinNickLength = configFile.getInt("settings.restrictions.minNicknameLength", 3); + getPasswordMinLen = configFile.getInt("settings.security.minPasswordLength", 4); + getNickRegex = configFile.getString("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_?]*"); + isAllowRestrictedIp = configFile.getBoolean("settings.restrictions.AllowRestrictedUser", false); + getRestrictedIp = configFile.getStringList("settings.restrictions.AllowedRestrictedUser"); + isMovementAllowed = configFile.getBoolean("settings.restrictions.allowMovement", false); + isRemoveSpeedEnabled = configFile.getBoolean("settings.restrictions.removeSpeed", true); + getMovementRadius = configFile.getInt("settings.restrictions.allowedMovementRadius", 100); + getJoinPermissions = configFile.getStringList("GroupOptions.Permissions.PermissionsOnJoin"); + isKickOnWrongPasswordEnabled = configFile.getBoolean("settings.restrictions.kickOnWrongPassword", false); + isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered", false); + isForceSingleSessionEnabled = configFile.getBoolean("settings.restrictions.ForceSingleSession", true); + isForceSpawnLocOnJoinEnabled = configFile.getBoolean("settings.restrictions.ForceSpawnLocOnJoinEnabled", false); + isSaveQuitLocationEnabled = configFile.getBoolean("settings.restrictions.SaveQuitLocation", false); + isForceSurvivalModeEnabled = configFile.getBoolean("settings.GameMode.ForceSurvivalMode", false); + isResetInventoryIfCreative = configFile.getBoolean("settings.GameMode.ResetInventoryIfCreative", false); + getmaxRegPerIp = configFile.getInt("settings.restrictions.maxRegPerIp", 1); + getPasswordHash = getPasswordHash(); + getUnloggedinGroup = configFile.getString("settings.security.unLoggedinGroup", "unLoggedInGroup"); + getDataSource = getDataSource(); + isCachingEnabled = configFile.getBoolean("DataSource.caching", true); + getMySQLHost = configFile.getString("DataSource.mySQLHost", "127.0.0.1"); + getMySQLPort = configFile.getString("DataSource.mySQLPort", "3306"); + getMySQLMaxConnections = configFile.getInt("DataSource.mySQLMaxConections", 25); + getMySQLUsername = configFile.getString("DataSource.mySQLUsername", "authme"); + getMySQLPassword = configFile.getString("DataSource.mySQLPassword", "12345"); + getMySQLDatabase = configFile.getString("DataSource.mySQLDatabase", "authme"); + getMySQLTablename = configFile.getString("DataSource.mySQLTablename", "authme"); + getMySQLColumnEmail = configFile.getString("DataSource.mySQLColumnEmail", "email"); + getMySQLColumnName = configFile.getString("DataSource.mySQLColumnName", "username"); + getMySQLColumnPassword = configFile.getString("DataSource.mySQLColumnPassword", "password"); + getMySQLColumnIp = configFile.getString("DataSource.mySQLColumnIp", "ip"); + getMySQLColumnLastLogin = configFile.getString("DataSource.mySQLColumnLastLogin", "lastlogin"); + getMySQLColumnSalt = configFile.getString("ExternalBoardOptions.mySQLColumnSalt"); + getMySQLColumnGroup = configFile.getString("ExternalBoardOptions.mySQLColumnGroup", ""); + getMySQLlastlocX = configFile.getString("DataSource.mySQLlastlocX", "x"); + getMySQLlastlocY = configFile.getString("DataSource.mySQLlastlocY", "y"); + getMySQLlastlocZ = configFile.getString("DataSource.mySQLlastlocZ", "z"); + getMySQLlastlocWorld = configFile.getString("DataSource.mySQLlastlocWorld", "world"); + getMySQLColumnRealName = configFile.getString("DataSource.mySQLRealName", "realname"); + getNonActivatedGroup = configFile.getInt("ExternalBoardOptions.nonActivedUserGroup", -1); + unRegisteredGroup = configFile.getString("GroupOptions.UnregisteredPlayerGroup", ""); + getUnrestrictedName = configFile.getStringList("settings.unrestrictions.UnrestrictedName"); + getRegisteredGroup = configFile.getString("GroupOptions.RegisteredPlayerGroup", ""); + getEnablePasswordVerifier = configFile.getBoolean("settings.restrictions.enablePasswordVerifier", true); + protectInventoryBeforeLogInEnabled = configFile.getBoolean("settings.restrictions.ProtectInventoryBeforeLogIn", true); + passwordMaxLength = configFile.getInt("settings.security.passwordMaxLength", 20); + isBackupActivated = configFile.getBoolean("BackupSystem.ActivateBackup", false); + isBackupOnStart = configFile.getBoolean("BackupSystem.OnServerStart", false); + isBackupOnStop = configFile.getBoolean("BackupSystem.OnServeStop", false); + backupWindowsPath = configFile.getString("BackupSystem.MysqlWindowsPath", "C:\\Program Files\\MySQL\\MySQL Server 5.1\\"); + isStopEnabled = configFile.getBoolean("Security.SQLProblem.stopServer", true); + reloadSupport = configFile.getBoolean("Security.ReloadCommand.useReloadCommandSupport", true); + allowCommands = configFile.getStringList("settings.restrictions.allowCommands"); + if (configFile.contains("allowCommands")) { + if (!allowCommands.contains("/login")) { + allowCommands.add("/login"); + } + if (!allowCommands.contains("/register")) { + allowCommands.add("/register"); + } + if (!allowCommands.contains("/l")) { + allowCommands.add("/l"); + } + if (!allowCommands.contains("/reg")) { + allowCommands.add("/reg"); + } + if (!allowCommands.contains("/email")) { + allowCommands.add("/email"); + } + if (!allowCommands.contains("/captcha")) { + allowCommands.add("/captcha"); + } + } + rakamakUsers = configFile.getString("Converter.Rakamak.fileName", "users.rak"); + rakamakUsersIp = configFile.getString("Converter.Rakamak.ipFileName", "UsersIp.rak"); + rakamakUseIp = configFile.getBoolean("Converter.Rakamak.useIp", false); + noConsoleSpam = configFile.getBoolean("Security.console.noConsoleSpam", false); + removePassword = configFile.getBoolean("Security.console.removePassword", true); + getmailAccount = configFile.getString("Email.mailAccount", ""); + getmailPassword = configFile.getString("Email.mailPassword", ""); + getmailSMTP = configFile.getString("Email.mailSMTP", "smtp.gmail.com"); + getMailPort = configFile.getInt("Email.mailPort", 465); + getRecoveryPassLength = configFile.getInt("Email.RecoveryPasswordLength", 8); + getMySQLOtherUsernameColumn = configFile.getStringList("ExternalBoardOptions.mySQLOtherUsernameColumns"); + displayOtherAccounts = configFile.getBoolean("settings.restrictions.displayOtherAccounts", true); + getMySQLColumnId = configFile.getString("DataSource.mySQLColumnId", "id"); + getmailSenderName = configFile.getString("Email.mailSenderName", ""); + useCaptcha = configFile.getBoolean("Security.captcha.useCaptcha", false); + maxLoginTry = configFile.getInt("Security.captcha.maxLoginTry", 5); + captchaLength = configFile.getInt("Security.captcha.captchaLength", 5); + getMailSubject = configFile.getString("Email.mailSubject", "Your new AuthMe Password"); + getMailText = configFile.getString("Email.mailText", + "Dear ,

This is your new AuthMe password for the server

:



Do not forget to change password after login!
/changepassword newPassword"); + emailRegistration = configFile.getBoolean("settings.registration.enableEmailRegistrationSystem", false); + saltLength = configFile.getInt("settings.security.doubleMD5SaltLength", 8); + getmaxRegPerEmail = configFile.getInt("Email.maxRegPerEmail", 1); + multiverse = configFile.getBoolean("Hooks.multiverse", true); + bungee = configFile.getBoolean("Hooks.bungeecord", false); + getForcedWorlds = configFile.getStringList("settings.restrictions.ForceSpawnOnTheseWorlds"); + banUnsafeIp = configFile.getBoolean("settings.restrictions.banUnsafedIP", false); + doubleEmailCheck = configFile.getBoolean("settings.registration.doubleEmailCheck", false); + sessionExpireOnIpChange = configFile.getBoolean("settings.sessions.sessionExpireOnIpChange", true); + useLogging = configFile.getBoolean("Security.console.logConsole", false); + disableSocialSpy = configFile.getBoolean("Hooks.disableSocialSpy", true); + bCryptLog2Rounds = configFile.getInt("ExternalBoardOptions.bCryptLog2Round", 10); + forceOnlyAfterLogin = configFile.getBoolean("settings.GameMode.ForceOnlyAfterLogin", false); + useEssentialsMotd = configFile.getBoolean("Hooks.useEssentialsMotd", false); + usePurge = configFile.getBoolean("Purge.useAutoPurge", false); + purgeDelay = configFile.getInt("Purge.daysBeforeRemovePlayer", 60); + purgePlayerDat = configFile.getBoolean("Purge.removePlayerDat", false); + purgeEssentialsFile = configFile.getBoolean("Purge.removeEssentialsFile", false); + defaultWorld = configFile.getString("Purge.defaultWorld", "world"); + getPhpbbPrefix = configFile.getString("ExternalBoardOptions.phpbbTablePrefix", "phpbb_"); + getPhpbbGroup = configFile.getInt("ExternalBoardOptions.phpbbActivatedGroupId", 2); + supportOldPassword = configFile.getBoolean("settings.security.supportOldPasswordHash", false); + getWordPressPrefix = configFile.getString("ExternalBoardOptions.wordpressTablePrefix", "wp_"); + purgeLimitedCreative = configFile.getBoolean("Purge.removeLimitedCreativesInventories", false); + purgeAntiXray = configFile.getBoolean("Purge.removeAntiXRayFile", false); + purgePermissions = configFile.getBoolean("Purge.removePermissions", false); + enableProtection = configFile.getBoolean("Protection.enableProtection", false); + countries = configFile.getStringList("Protection.countries"); + enableAntiBot = configFile.getBoolean("Protection.enableAntiBot", false); + antiBotSensibility = configFile.getInt("Protection.antiBotSensibility", 5); + antiBotDuration = configFile.getInt("Protection.antiBotDuration", 10); + forceCommands = configFile.getStringList("settings.forceCommands"); + forceCommandsAsConsole = configFile.getStringList("settings.forceCommandsAsConsole"); + recallEmail = configFile.getBoolean("Email.recallPlayers", false); + delayRecall = configFile.getInt("Email.delayRecall", 5); + useWelcomeMessage = configFile.getBoolean("settings.useWelcomeMessage", true); + unsafePasswords = configFile.getStringList("settings.security.unsafePasswords"); + countriesBlacklist = configFile.getStringList("Protection.countriesBlacklist"); + broadcastWelcomeMessage = configFile.getBoolean("settings.broadcastWelcomeMessage", false); + forceRegKick = configFile.getBoolean("settings.registration.forceKickAfterRegister", false); + forceRegLogin = configFile.getBoolean("settings.registration.forceLoginAfterRegister", false); + getMySQLColumnLogged = configFile.getString("DataSource.mySQLColumnLogged", "isLogged"); + spawnPriority = configFile.getString("settings.restrictions.spawnPriority", "authme,essentials,multiverse,default"); + getMaxLoginPerIp = configFile.getInt("settings.restrictions.maxLoginPerIp", 0); + getMaxJoinPerIp = configFile.getInt("settings.restrictions.maxJoinPerIp", 0); + checkVeryGames = configFile.getBoolean("VeryGames.enableIpCheck", false); + delayJoinMessage = configFile.getBoolean("settings.delayJoinMessage", false); + noTeleport = configFile.getBoolean("settings.restrictions.noTeleport", false); + crazyloginFileName = configFile.getString("Converter.CrazyLogin.fileName", "accounts.db"); + getPassRegex = configFile.getString("settings.restrictions.allowedPasswordCharacters", "[\\x21-\\x7E]*"); + applyBlindEffect = configFile.getBoolean("settings.applyBlindEffect", false); + emailBlacklist = configFile.getStringList("Email.emailBlacklisted"); + emailWhitelist = configFile.getStringList("Email.emailWhitelisted"); + forceRegisterCommands = configFile.getStringList("settings.forceRegisterCommands"); + forceRegisterCommandsAsConsole = configFile.getStringList("settings.forceRegisterCommandsAsConsole"); + customAttributes = configFile.getBoolean("Hooks.customAttributes"); + generateImage = configFile.getBoolean("Email.generateImage", true); + + // Load the welcome message + getWelcomeMessage(); + + } + + public static void reload() throws Exception { + plugin.getLogger().info("Loading Configuration File..."); + final boolean exist = SETTINGS_FILE.exists(); + if (!exist) { + plugin.saveDefaultConfig(); + } + instance.load(SETTINGS_FILE); + if (exist) { + instance.mergeConfig(); + } + loadVariables(); + if (exist) { + instance.saveDefaults(); + } + messageFile = new File(APLUGIN_FOLDER, "messages" + File.separator + "messages_" + messagesLanguage + ".yml"); + } + + /** + * Saves the configuration to disk + * + * @return True if saved successfully + */ + public static boolean save() { + try { + instance.save(SETTINGS_FILE); + return true; + } catch (final Exception ex) { + return false; + } + } + + public static void setValue(final String key, final Object value) { + instance.set(key, value); + save(); + } + + public static void switchAntiBotMod(final boolean mode) { + if (mode) { + isKickNonRegisteredEnabled = true; + antiBotInAction = true; + } else { + isKickNonRegisteredEnabled = configFile.getBoolean("settings.restrictions.kickNonRegistered", false); + antiBotInAction = false; + } + } + + private static DataSourceType getDataSource() { + final String key = "DataSource.backend"; + try { + return DataSource.DataSourceType.valueOf(configFile.getString(key, "sqlite").toUpperCase()); + } catch (final IllegalArgumentException ex) { + ConsoleLogger.showError("Unknown database backend; defaulting to sqlite database"); + return DataSource.DataSourceType.SQLITE; + } + } + + private static HashAlgorithm getPasswordHash() { + final String key = "settings.security.passwordHash"; + try { + return HashAlgorithm.valueOf(configFile.getString(key, "SHA256").toUpperCase()); + } catch (final IllegalArgumentException ex) { + ConsoleLogger.showError("Unknown Hash Algorithm; defaulting to SHA256"); + return HashAlgorithm.SHA256; + } + } + + private static void getWelcomeMessage() { + final AuthMe plugin = AuthMe.getInstance(); + welcomeMsg = new ArrayList<>(); + if (!useWelcomeMessage) { + return; + } + if (!(new File(plugin.getDataFolder() + File.separator + "welcome.txt").exists())) { + try { + final FileWriter fw = new FileWriter(plugin.getDataFolder() + File.separator + "welcome.txt", true); + final BufferedWriter w = new BufferedWriter(fw); + w.write("Welcome {PLAYER} on {SERVER} server"); + w.newLine(); + w.write("This server use AuthMe protection!"); + w.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + try { + final FileReader fr = new FileReader(plugin.getDataFolder() + File.separator + "welcome.txt"); + final BufferedReader br = new BufferedReader(fr); + String line; + while ((line = br.readLine()) != null) { + welcomeMsg.add(line); + } + br.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + + public void mergeConfig() { + boolean changes = false; + if (contains("Xenoforo.predefinedSalt")) { + set("Xenoforo.predefinedSalt", null); + changes = true; + } + if (configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA1") + || configFile.getString("settings.security.passwordHash", "SHA256").toUpperCase().equals("XFSHA256")) { + set("settings.security.passwordHash", "XENFORO"); + changes = true; + } + if (!contains("Protection.enableProtection")) { + set("Protection.enableProtection", false); + changes = true; + } + if (!contains("settings.restrictions.removeSpeed")) { + set("settings.restrictions.removeSpeed", true); + changes = true; + } + if (!contains("DataSource.mySQLMaxConections")) { + set("DataSource.mySQLMaxConections", 25); + changes = true; + } + if (!contains("Protection.countries")) { + countries = new ArrayList<>(); + countries.add("US"); + countries.add("GB"); + set("Protection.countries", countries); + changes = true; + } + if (!contains("Protection.enableAntiBot")) { + set("Protection.enableAntiBot", false); + changes = true; + } + if (!contains("Protection.antiBotSensibility")) { + set("Protection.antiBotSensibility", 5); + changes = true; + } + if (!contains("Protection.antiBotDuration")) { + set("Protection.antiBotDuration", 10); + changes = true; + } + if (!contains("settings.forceCommands")) { + set("settings.forceCommands", new ArrayList()); + changes = true; + } + if (!contains("settings.forceCommandsAsConsole")) { + set("settings.forceCommandsAsConsole", new ArrayList()); + changes = true; + } + if (!contains("Email.recallPlayers")) { + set("Email.recallPlayers", false); + changes = true; + } + if (!contains("Email.delayRecall")) { + set("Email.delayRecall", 5); + changes = true; + } + if (!contains("settings.useWelcomeMessage")) { + set("settings.useWelcomeMessage", true); + changes = true; + } + if (!contains("settings.security.unsafePasswords")) { + final List str = new ArrayList<>(); + str.add("123456"); + str.add("password"); + set("settings.security.unsafePasswords", str); + changes = true; + } + if (!contains("Protection.countriesBlacklist")) { + countriesBlacklist = new ArrayList<>(); + countriesBlacklist.add("A1"); + set("Protection.countriesBlacklist", countriesBlacklist); + changes = true; + } + if (!contains("settings.broadcastWelcomeMessage")) { + set("settings.broadcastWelcomeMessage", false); + changes = true; + } + if (!contains("settings.registration.forceKickAfterRegister")) { + set("settings.registration.forceKickAfterRegister", false); + changes = true; + } + if (!contains("settings.registration.forceLoginAfterRegister")) { + set("settings.registration.forceLoginAfterRegister", false); + changes = true; + } + if (!contains("DataSource.mySQLColumnLogged")) { + set("DataSource.mySQLColumnLogged", "isLogged"); + changes = true; + } + if (!contains("settings.restrictions.spawnPriority")) { + set("settings.restrictions.spawnPriority", "authme,essentials,multiverse,default"); + changes = true; + } + if (!contains("settings.restrictions.maxLoginPerIp")) { + set("settings.restrictions.maxLoginPerIp", 0); + changes = true; + } + if (!contains("settings.restrictions.maxJoinPerIp")) { + set("settings.restrictions.maxJoinPerIp", 0); + changes = true; + } + if (!contains("VeryGames.enableIpCheck")) { + set("VeryGames.enableIpCheck", false); + changes = true; + } + if (getString("settings.restrictions.allowedNicknameCharacters").equals("[a-zA-Z0-9_?]*")) { + set("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_]*"); + changes = true; + } + if (!contains("settings.delayJoinMessage")) { + set("settings.delayJoinMessage", false); + changes = true; + } + if (!contains("settings.restrictions.noTeleport")) { + set("settings.restrictions.noTeleport", false); + changes = true; + } + if (contains("Converter.Rakamak.newPasswordHash")) { + set("Converter.Rakamak.newPasswordHash", null); + changes = true; + } + if (!contains("Converter.CrazyLogin.fileName")) { + set("Converter.CrazyLogin.fileName", "accounts.db"); + changes = true; + } + if (!contains("settings.restrictions.allowedPasswordCharacters")) { + set("settings.restrictions.allowedPasswordCharacters", "[\\x21-\\x7E]*"); + changes = true; + } + if (!contains("settings.applyBlindEffect")) { + set("settings.applyBlindEffect", false); + changes = true; + } + if (!contains("Email.emailBlacklisted")) { + set("Email.emailBlacklisted", new ArrayList()); + changes = true; + } + if (contains("Performances.useMultiThreading")) { + set("Performances.useMultiThreading", null); + changes = true; + } + if (contains("Performances")) { + set("Performances", null); + changes = true; + } + if (contains("Passpartu.enablePasspartu")) { + set("Passpartu.enablePasspartu", null); + changes = true; + } + if (contains("Passpartu")) { + set("Passpartu", null); + changes = true; + } + if (!contains("Email.emailWhitelisted")) { + set("Email.emailWhitelisted", new ArrayList()); + changes = true; + } + if (!contains("settings.forceRegisterCommands")) { + set("settings.forceRegisterCommands", new ArrayList()); + changes = true; + } + if (!contains("settings.forceRegisterCommandsAsConsole")) { + set("settings.forceRegisterCommandsAsConsole", new ArrayList()); + changes = true; + } + if (!contains("Hooks.customAttributes")) { + set("Hooks.customAttributes", false); + changes = true; + } + if (!contains("Purge.removePermissions")) { + set("Purge.removePermissions", false); + changes = true; + } + if (contains("Hooks.notifications")) { + set("Hooks.notifications", null); + changes = true; + } + if (contains("Hooks.chestshop")) { + set("Hooks.chestshop", null); + changes = true; + } + if (contains("Hooks.legacyChestshop")) { + set("Hooks.legacyChestshop", null); + changes = true; + } + if (!contains("Email.generateImage")) { + set("Email.generateImage", true); + changes = true; + } + if (!contains("DataSource.mySQLRealName")) { + set("DataSource.mySQLRealName", "realname"); + changes = true; + } + + if (changes) { + plugin.getLogger().warning("Merged new Config Options - I'm not an error, please don't report me"); + plugin.getLogger().warning("Please check your config.yml file for new configs!"); + } + } + + /** + * Saves current configuration (plus defaults) to disk. + *

+ * If defaults and configuration are empty, saves blank file. + * + * @return True if saved successfully + */ + public final boolean saveDefaults() { + options().copyDefaults(true); + options().copyHeader(true); + final boolean success = save(); + options().copyDefaults(false); + options().copyHeader(false); + return success; + } +} diff --git a/src/main/java/fr/xephi/authme/settings/Spawn.java b/src/main/java/fr/xephi/authme/settings/Spawn.java new file mode 100644 index 0000000..1ef8df7 --- /dev/null +++ b/src/main/java/fr/xephi/authme/settings/Spawn.java @@ -0,0 +1,111 @@ +package fr.xephi.authme.settings; + +import java.io.File; + +import org.bukkit.Bukkit; +import org.bukkit.Location; + +/** + * + * @author Xephi59 + */ +public class Spawn extends CustomConfiguration { + + private static Spawn spawn; + + public Spawn() { + super(new File("." + File.separator + "plugins" + File.separator + "AuthMe" + File.separator + "spawn.yml")); + spawn = this; + load(); + save(); + saveDefault(); + } + + public static Spawn getInstance() { + if (spawn == null) { + spawn = new Spawn(); + } + return spawn; + } + + public Location getFirstSpawn() { + try { + if (this.getString("firstspawn.world").isEmpty() || this.getString("firstspawn.world").equals("")) + return null; + Location location = new Location(Bukkit.getWorld(this.getString("firstspawn.world")), this.getDouble("firstspawn.x"), this.getDouble("firstspawn.y"), this.getDouble("firstspawn.z"), + Float.parseFloat(this.getString("firstspawn.yaw")), Float.parseFloat(this.getString("firstspawn.pitch"))); + return location; + } catch (NullPointerException | NumberFormatException npe) { + return null; + } + } + + @Deprecated + public Location getLocation() { + return getSpawn(); + } + + public Location getSpawn() { + try { + if (this.getString("spawn.world").isEmpty() || this.getString("spawn.world").equals("")) + return null; + Location location = new Location(Bukkit.getWorld(this.getString("spawn.world")), this.getDouble("spawn.x"), this.getDouble("spawn.y"), this.getDouble("spawn.z"), + Float.parseFloat(this.getString("spawn.yaw")), Float.parseFloat(this.getString("spawn.pitch"))); + return location; + } catch (NullPointerException | NumberFormatException npe) { + return null; + } + } + + public boolean setFirstSpawn(Location location) { + try { + set("firstspawn.world", location.getWorld().getName()); + set("firstspawn.x", location.getX()); + set("firstspawn.y", location.getY()); + set("firstspawn.z", location.getZ()); + set("firstspawn.yaw", location.getYaw()); + set("firstspawn.pitch", location.getPitch()); + save(); + return true; + } catch (NullPointerException npe) { + return false; + } + } + + public boolean setSpawn(Location location) { + try { + set("spawn.world", location.getWorld().getName()); + set("spawn.x", location.getX()); + set("spawn.y", location.getY()); + set("spawn.z", location.getZ()); + set("spawn.yaw", location.getYaw()); + set("spawn.pitch", location.getPitch()); + save(); + return true; + } catch (NullPointerException npe) { + return false; + } + } + + private void saveDefault() { + if (!contains("spawn")) { + set("spawn.world", ""); + set("spawn.x", ""); + set("spawn.y", ""); + set("spawn.z", ""); + set("spawn.yaw", ""); + set("spawn.pitch", ""); + save(); + } + if (!contains("firstspawn")) { + set("firstspawn.world", ""); + set("firstspawn.x", ""); + set("firstspawn.y", ""); + set("firstspawn.z", ""); + set("firstspawn.yaw", ""); + set("firstspawn.pitch", ""); + save(); + } + } + +} diff --git a/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java b/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java new file mode 100644 index 0000000..ee77357 --- /dev/null +++ b/src/main/java/fr/xephi/authme/task/ChangePasswordTask.java @@ -0,0 +1,59 @@ +package fr.xephi.authme.task; + +import java.security.NoSuchAlgorithmException; + +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.cache.auth.PlayerAuth; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.security.PasswordSecurity; +import fr.xephi.authme.settings.Messages; +import fr.xephi.authme.settings.Settings; + +public class ChangePasswordTask implements Runnable { + + private final String newPassword; + private final String oldPassword; + private final Player player; + private final AuthMe plugin; + + public ChangePasswordTask(AuthMe plugin, Player player, String oldPassword, String newPassword) { + this.plugin = plugin; + this.player = player; + this.oldPassword = oldPassword; + this.newPassword = newPassword; + } + + @Override + public void run() { + Messages m = Messages.getInstance(); + try { + String name = player.getName().toLowerCase(); + String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, newPassword, name); + PlayerAuth auth = PlayerCache.getInstance().getAuth(name); + if (PasswordSecurity.comparePasswordWithHash(oldPassword, auth.getHash(), player.getName())) { + auth.setHash(hashnew); + if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null) { + auth.setSalt(PasswordSecurity.userSalt.get(name)); + } else { + auth.setSalt(""); + } + if (!plugin.database.updatePassword(auth)) { + m.send(player, "error"); + return; + } + plugin.database.updateSalt(auth); + PlayerCache.getInstance().updatePlayer(auth); + m.send(player, "pwd_changed"); + ConsoleLogger.info(player.getName() + " changed his password"); + } else { + m.send(player, "wrong_pwd"); + } + } catch (NoSuchAlgorithmException ex) { + ConsoleLogger.showError(ex.getMessage()); + m.send(player, "error"); + } + } +} diff --git a/src/main/java/fr/xephi/authme/task/MessageTask.java b/src/main/java/fr/xephi/authme/task/MessageTask.java new file mode 100644 index 0000000..36aa309 --- /dev/null +++ b/src/main/java/fr/xephi/authme/task/MessageTask.java @@ -0,0 +1,43 @@ +package fr.xephi.authme.task; + +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.Utils; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.cache.limbo.LimboCache; + +public class MessageTask implements Runnable { + + private int interval; + private String[] msg; + private String name; + private AuthMe plugin; + + public MessageTask(AuthMe plugin, String name, String[] strings, int interval) { + this.plugin = plugin; + this.name = name; + this.msg = strings; + this.interval = interval; + } + + @Override + public void run() { + if (PlayerCache.getInstance().isAuthenticated(name)) + return; + + for (Player player : Utils.getOnlinePlayers()) { + if (player.getName().toLowerCase().equals(name)) { + for (String ms : msg) { + player.sendMessage(ms); + } + BukkitTask late = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, this, interval * 20); + if (LimboCache.getInstance().hasLimboPlayer(name)) { + LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(late); + } + return; + } + } + } +} diff --git a/src/main/java/fr/xephi/authme/task/TimeoutTask.java b/src/main/java/fr/xephi/authme/task/TimeoutTask.java new file mode 100644 index 0000000..811a36d --- /dev/null +++ b/src/main/java/fr/xephi/authme/task/TimeoutTask.java @@ -0,0 +1,41 @@ +package fr.xephi.authme.task; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import fr.xephi.authme.AuthMe; +import fr.xephi.authme.cache.auth.PlayerCache; +import fr.xephi.authme.settings.Messages; + +public class TimeoutTask implements Runnable { + + private Messages m = Messages.getInstance(); + private String name; + private Player player; + private AuthMe plugin; + + public TimeoutTask(AuthMe plugin, String name, Player player) { + this.plugin = plugin; + this.name = name; + this.player = player; + } + + public String getName() { + return name; + } + + @Override + public void run() { + if (PlayerCache.getInstance().isAuthenticated(name)) + return; + + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + + @Override + public void run() { + if (player.isOnline()) + player.kickPlayer(m.send("timeout")[0]); + } + }); + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml new file mode 100644 index 0000000..c10c977 --- /dev/null +++ b/src/main/resources/config.yml @@ -0,0 +1,399 @@ +DataSource: + # What type of database do you want to use? + # Can be set to: sqlite, sqlitehikari, mysql + # (sqlitehikari should be more fast than normal sqlite but it's an experimental feature!) + backend: sqlite + # Enable database caching + caching: true + # Database location + mySQLHost: 127.0.0.1 + # Database Port + mySQLPort: '3306' + # MySql Max Connections + mySQLMaxConections: 25 + # Username about Database Connection Infos + mySQLUsername: authme + # Password about Database Connection Infos + mySQLPassword: '12345' + # Database Name, use with converters or as SQLITE database name + mySQLDatabase: authme + # Table of the database + mySQLTablename: authme + # Column of IDs to sort data + mySQLColumnId: id + # Column for storing or checking players nickname + mySQLColumnName: username + # Column for storing players passwords + mySQLColumnPassword: password + # Column for storing players emails + mySQLColumnEmail: email + # Column for Saving if a player is logged in or not + mySQLColumnLogged: isLogged + # Column for storing players IPs + mySQLColumnIp: ip + # Column for storing players lastlogins + mySQLColumnLastLogin: lastlogin + # Column for SaveQuitLocation - X + mySQLlastlocX: x + # Column for SaveQuitLocation - Y + mySQLlastlocY: y + # Column for SaveQuitLocation - Z + mySQLlastlocZ: z + # Column for SaveQuitLocation - World name + mySQLlastlocWorld: world + # Column for RealName + mySQLRealName: realname +settings: + sessions: + # Do you want to enable the session feature? + # If enabled, when a player authenticates successfully, + # his IP and his nickname is saved. + # The next time the player joins the server, if his IP + # is the same of the last time, and the timeout time + # hasn't expired, he will not need to authenticate. + enabled: false + # After how many minutes a session should expire? + # 0 for unlimited time (Very dangerous, use it at your own risk!) + # Consider that session will end only after the timeout time, and + # if the player's ip has changed but the timeout hasn't expired, + # player will be kicked out of sever due to invalidSession! + timeout: 10 + # Should the session expire if the player try to login with an + # another IP Address? + sessionExpireOnIpChange: true + restrictions: + # Can not authenticated players chat and see the chat log? + # Care that this feature blocks also all the commands not + # listed in the list below. + allowChat: false + # Commands allowed when a player is not authenticated + allowCommands: + - /login + - /register + - /l + - /reg + - /email + - /captcha + # Max number of allowed registrations per IP (default: 1) + maxRegPerIp: 1 + # Max allowed username length + maxNicknameLength: 16 + # When this setting is enabled, online players can't be kicked out + # due to "Logged in from another Location" + # This setting will prevent potetial security exploits. + ForceSingleSession: true + # If enabled, every player will be teleported to the world spawnpoint + # after successful authentication. + # The quit location of the player will be overwritten. + # This is different from "teleportUnAuthedToSpawn" that teleport player + # back to his quit location after the authentication. + ForceSpawnLocOnJoinEnabled: false + # This option will save the quit location of the players. + SaveQuitLocation: false + # To activate the restricted user feature you need + # to enable this option and configure the + # AllowedRestrctedUser field. + AllowRestrictedUser: false + # The restricted user feature will kick players listed below + # if they dont match of the defined ip address. + # Example: + # AllowedRestrictedUser: + # - playername;127.0.0.1 + AllowedRestrictedUser: + - playername;127.0.0.1 + # Should unregistered players be kicked immediatly? + kickNonRegistered: false + # Should players be kicked on wrong password? + kickOnWrongPassword: false + # Should not logged in players be teleported to the spawn? + # After the authentication they will be teleported back to + # their normal position. + teleportUnAuthedToSpawn: false + # Minimum allowed nick length + minNicknameLength: 4 + # Can unregistered players walk around? + allowMovement: false + # Should not authenticated players have speed = 0? + # This will reset the fly/walk speed to default value after the login. + removeSpeed: true + # After how many time players who fail to login or register + # should be kicked? Set to 0 to disable. + timeout: 30 + # Regex sintax of allowed characters in the player name. + allowedNicknameCharacters: '[a-zA-Z0-9_]*' + # How far can unregistered players walk? Set to 0 + # for unlimited radius + allowedMovementRadius: 100 + # Enable double check of password when you register + # when it's true, registration require that kind of command: + # /register + enablePasswordVerifier: true + # Should we protect the player inventory before logging in? + ProtectInventoryBeforeLogIn: true + # Should we display all other accounts from a player when he joins? + # permission: /authme.admin.accounts + displayOtherAccounts: true + # WorldNames where we need to force the spawn location for ForceSpawnLocOnJoinEnabled + ForceSpawnOnTheseWorlds: + - world + - world_nether + - world_the_end + # Ban ip when the ip is not the ip registered in database + banUnsafedIP: false + # Spawn Priority, Values : authme, essentials, multiverse, default + spawnPriority: authme,essentials,multiverse,default + # Maximum Login authorized by IP + maxLoginPerIp: 0 + # Maximum Join authorized by IP + maxJoinPerIp: 0 + # AuthMe will NEVER teleport players ! + noTeleport: false + # Regex sintax for allowed Chars in passwords. + allowedPasswordCharacters: '[\x21-\x7E]*' + GameMode: + # ForceSurvivalMode to player when join ? + ForceSurvivalMode: false + # if player join with CreativeMode and ForceSurvivalMode: true + # inventory will be wipped + ResetInventoryIfCreative: false + # Do we need to force the survival mode ONLY after /login process ? + ForceOnlyAfterLogin: false + security: + # minimum Length of password + minPasswordLength: 5 + # this is very important options, + # every time player join the server, + # if they are registered, AuthMe will switch him + # to unLoggedInGroup, this + # should prevent all major exploit. + # So you can set up on your Permission Plugin + # this special group with 0 permissions, or permissions to chat, + # or permission to + # send private message or all other perms that you want, + # the better way is to set up + # this group with few permissions, + # so if player try to exploit some account, + # they can + # do anything except what you set in perm Group. + # After a correct logged-in player will be + # moved to his correct permissions group! + # Pay attention group name is case sensitive, + # so Admin is different from admin, + # otherwise your group will be wiped, + # and player join in default group []! + # Example unLoggedinGroup: NotLogged + unLoggedinGroup: unLoggedinGroup + # possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, + # PLAINTEXT ( unhashed password), + # MYBB, IPB3, PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512, + # DOUBLEMD5, PBKDF2, PBKDF2DJANGO, WORDPRESS, ROYALAUTH, CUSTOM(for developpers only) + passwordHash: SHA256 + # salt length for the SALTED2MD5 MD5(MD5(password)+salt) + doubleMD5SaltLength: 8 + # If password checking return false , do we need to check with all + # other password algorithm to check an old password ? + # AuthMe will update the password to the new passwordHash ! + supportOldPasswordHash: false + # Cancel unsafe passwords for being used, put them on lowercase! + #unsafePasswords: + #- '123456' + #- 'password' + unsafePasswords: + - '123456' + - 'password' + - 'qwerty' + - '12345' + - '54321' + registration: + # enable registration on the server? + enabled: true + # Send every X seconds a message to a player to + # remind him that he has to login/register + messageInterval: 5 + # Only registered and logged in players can play. + # See restrictions for exceptions + force: true + # Does we replace password registration by an Email registration method ? + enableEmailRegistrationSystem: false + # Enable double check of email when you register + # when it's true, registration require that kind of command: + # /register + doubleEmailCheck: false + # Do we force kicking player after a successful registration ? + # Do not use with login feature below + forceKickAfterRegister: false + # Does AuthMe need to enforce a /login after a successful registration ? + forceLoginAfterRegister: false + unrestrictions: + # below you can list all your account name, that + # AuthMe will ignore for registration or login, configure it + # at your own risk!! Remember that if you are going to add + # nickname with [], you have to delimit name with ' '. + # this option add compatibility with BuildCraft and some + # other mods. + # It is CaseSensitive! + UnrestrictedName: [] + # Message language, available : en, de, br, cz, pl, fr, ru, hu, sk, es, zhtw, fi, zhcn, lt, it, ko, pt + messagesLanguage: en + # Force these commands after /login, without any '/', use %p for replace with player name + forceCommands: [] + # Force these commands after /login as a server console, without any '/', use %p for replace with player name + forceCommandsAsConsole: [] + # Force these commands after /register, without any '/', use %p for replace with player name + forceRegisterCommands: [] + # Force these commands after /register as a server console, without any '/', use %p for replace with player name + forceRegisterCommandsAsConsole: [] + # Do we need to display the welcome message (welcome.txt) after a register or a login? + # You can use colors in this welcome.txt + some replaced strings : + # {PLAYER} : player name, {ONLINE} : display number of online players, {MAXPLAYERS} : display server slots, + # {IP} : player ip, {LOGINS} : number of players logged, {WORLD} : player current world, {SERVER} : server name + # {VERSION} : get current bukkit version, {COUNTRY} : player country + useWelcomeMessage: true + # Do we need to broadcast the welcome message to all server or only to the player? set true for server or false for player + broadcastWelcomeMessage: false + # Do we need to delay the X has joined the game after /login ? + delayJoinMessage: false + # Do we need to add potion effect Blinding before login/register ? + applyBlindEffect: false +ExternalBoardOptions: + # MySQL column for the salt , needed for some forum/cms support + mySQLColumnSalt: '' + # MySQL column for the group, needed for some forum/cms support + mySQLColumnGroup: '' + # -1 mean disabled. If u want that only + # activated player can login in your server + # u can put in this options the group number + # of unactivated user, needed for some forum/cms support + nonActivedUserGroup: -1 + # Other MySQL columns where we need to put the Username (case sensitive) + mySQLOtherUsernameColumns: [] + # How much Log to Round needed in BCrypt(do not change it if you do not know what's your doing) + bCryptLog2Round: 10 + # phpBB prefix defined during phpbb installation process + phpbbTablePrefix: 'phpbb_' + # phpBB activated group id , 2 is default registered group defined by phpbb + phpbbActivatedGroupId: 2 + # WordPress prefix defined during WordPress installation process + wordpressTablePrefix: 'wp_' +permission: + # Take care with this options, if you dont want + # to use Vault and Group Switching of + # AuthMe for unloggedIn players put true + # below, default is false. + EnablePermissionCheck: false +BackupSystem: + # Enable or Disable Automatic Backup + ActivateBackup: false + # set Backup at every start of Server + OnServerStart: false + # set Backup at every stop of Server + OnServerStop: true + # Windows only mysql installation Path + MysqlWindowsPath: 'C:\\Program Files\\MySQL\\MySQL Server 5.1\\' +Security: + SQLProblem: + # Stop the server if we can't contact the sql database + # Take care with this, if you set that to false, + # AuthMe automatically disable and the server is not protected! + stopServer: true + ReloadCommand: + # /reload support + useReloadCommandSupport: true + console: + # Remove spam console + noConsoleSpam: false + # Replace passwords in the console when player type a command like /login + removePassword: true + captcha: + # Player need to put a captcha when he fails too lot the password + useCaptcha: false + # Max allowed tries before request a captcha + maxLoginTry: 5 + # Captcha length + captchaLength: 5 +Converter: + Rakamak: + # Rakamak file name + fileName: users.rak + # Rakamak use ip ? + useIP: false + # IP file name for rakamak + ipFileName: UsersIp.rak + CrazyLogin: + # CrazyLogin database file + fileName: accounts.db +Email: + # Email SMTP server host + mailSMTP: smtp.gmail.com + # Email SMTP server port + mailPort: 465 + # Email account that send the mail + mailAccount: '' + # Email account password + mailPassword: '' + # Custom SenderName, that replace the mailAccount name in the email + mailSenderName: '' + # Random password length + RecoveryPasswordLength: 8 + # Email subject of password get + mailSubject: 'Your new AuthMe Password' + # Email text here + mailText: 'Dear ,

This is your new AuthMe password for the server

:



Do not forget to change password after login!
/changepassword newPassword' + # Like maxRegPerIp but with email + maxRegPerEmail: 1 + # Recall players to add an email ? + recallPlayers: false + # Delay in minute for the recall scheduler + delayRecall: 5 + # Blacklist these domains for emails + emailBlacklisted: + - 10minutemail.com + # WhiteList only these domains for emails + emailWhitelisted: [] +Hooks: + # Do we need to hook with multiverse for spawn checking? + multiverse: true + # Do we need to hook with BungeeCord for get the real Player ip ? + bungeecord: false + # Do we need to disable Essentials SocialSpy on join ? + disableSocialSpy: true + # Do we need to force /motd Essentials command on join ? + useEssentialsMotd: false + # Do we need to cache custom Attributes ? + customAttributes: false +Purge: + # On Enable , does AuthMe need to purge automatically old accounts unused ? + useAutoPurge: false + # Number of Days an account become Unused + daysBeforeRemovePlayer: 60 + # Do we need to remove the player.dat file during purge process ? + removePlayerDat: false + # Do we need to remove the Essentials/users/player.yml file during purge process ? + removeEssentialsFile: false + # World where are players.dat stores + defaultWorld: 'world' + # Do we need to remove LimitedCreative/inventories/player.yml , player_creative.yml files during purge process ? + removeLimitedCreativesInventories: false + # Do we need to remove the AntiXRayData/PlayerData/player file during purge process ? + removeAntiXRayFile: false + # Do we need to remove permissions ? + removePermissions: false +Protection: + # Enable some servers protection ( country based login, antibot ) + enableProtection: false + # Countries allowed to join the server and register, see http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/ for countries' codes + countries: + - US + - GB + # Countries blacklisted automatically ( without any needed to enable protection ) + countriesBlacklist: + - A1 + # Do we need to enable automatic antibot system? + enableAntiBot: false + # Max number of player allowed to login in 5 secs before enable AntiBot system automatically + antiBotSensibility: 5 + # Duration in minutes of the antibot automatic system + antiBotDuration: 10 +VeryGames: + # These features are only available on VeryGames Server Provider + enableIpCheck: false diff --git a/src/main/resources/messages/messages_bg.yml b/src/main/resources/messages/messages_bg.yml new file mode 100644 index 0000000..81a7e70 --- /dev/null +++ b/src/main/resources/messages/messages_bg.yml @@ -0,0 +1,58 @@ +unknown_user: '&fПотребителя не е в БД' +unsafe_spawn: '&fТвоята локация когато излезе не беше безопасна, телепортиран си на Spawn!' +not_logged_in: '&cНе си влязъл!' +reg_voluntarily: '&fМоже да се регистрираш с тази команда: + "/register парола парола"' +usage_log: '&cКоманда: /login парола' +wrong_pwd: '&cГрешна парола!' +unregistered: '&cУспешно от-регистриран!' +reg_disabled: '&cРегистрациите са изключени!' +valid_session: '&aСесията продължена!' +login: '&cВход успешен!' +vb_nonActiv: '&fТвоята регистрация не е активирана, моля провери своя Имейл!' +user_regged: '&cПотребителското име е заето!' +usage_reg: '&cКоманда: /register парола парола' +max_reg: '&fТи достигна максималния брой регистрации!' +no_perm: '&cНямаш Достъп!' +error: '&fПолучи се грешка; Моля свържете се с админ' +login_msg: '&cМоля влез с "/login парола"' +reg_msg: '&cМоля регистрирай се с "/register парола парола"' +reg_email_msg: '&cМоля регистрирай се с "/register <имейл> <имейл>"' +usage_unreg: '&cКоманда: /unregister парола' +pwd_changed: '&cПаролата е променена!' +user_unknown: '&cПотребителя не е регистриран' +password_error: '&fПаролата не съвпада' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +invalid_session: '&fSession Dataes doesnt corrispond Plaese wait the end of session' +reg_only: '&fСамо за регистрирани! Моля посети http://example.com за регистрация' +logged_in: '&cВече сте влязъл!' +logout: '&cУспешен изход от регистрацията!' +same_nick: '&fПотребител с този никнейм е в игра' +registered: '&cУспешно премахната регистрация!' +pass_len: '&cВашета парола не е достатъчно дълга или къса.' +reload: '&fКонфигурацията презаредена!' +timeout: '&fВремето изтече, опитай отново!' +usage_changepassword: '&fКоманда: /changepassword СтараПарола НоваПарола' +name_len: '&cТвоя никнейм е твърде малък или голям' +regex: '&cТвоя никнейм съдържа забранени знацхи. Позволените са: REG_EX' +add_email: '&cМоля добави своя имейл с : /email add имейл имейл' +recovery_email: '&cЗабравихте своята парола? Моля използвай /email recovery <имейл>' +usage_captcha: '&cYou need to type a captcha, please type: /captcha <код>' +wrong_captcha: '&cГрешен код, използвай : /captcha THE_CAPTCHA' +valid_captcha: '&cТвоя код е валиден!' +kick_forvip: '&cVIP влезе докато сървъра е пълен, ти беше изгонен!' +kick_fullserver: '&cСървъра е пълен, Съжеляваме!' +usage_email_add: '&fКоманда: /email add ' +usage_email_change: '&fКоманда: /email change <СтарИмейл> <НовИмейл> ' +usage_email_recovery: '&fКоманда: /email recovery <имейл>' +new_email_invalid: '[AuthMe] Новия имейл е грешен!' +old_email_invalid: '[AuthMe] Стария имейл е грешен!' +email_invalid: '[AuthMe] Грешен имейл' +email_added: '[AuthMe] Имейла добавен !' +email_confirm: '[AuthMe] Потвърди своя имейл !' +email_changed: '[AuthMe] Имейла е сменен !' +email_send: '[AuthMe] Изпраен е имейл !' +country_banned: Твоята държава е забранена в този сървър! +antibot_auto_enabled: '[AuthMe] AntiBotMod автоматично включен, открита е потенциална атака!' +antibot_auto_disabled: '[AuthMe] AntiBotMod автоматично изключване след %m Минути.' diff --git a/src/main/resources/messages/messages_br.yml b/src/main/resources/messages/messages_br.yml new file mode 100644 index 0000000..20243c6 --- /dev/null +++ b/src/main/resources/messages/messages_br.yml @@ -0,0 +1,58 @@ +unknown_user: '&fNao esta no banco de dados' +unsafe_spawn: '&fA sua localização na saída não é segura, você será tele-portado para a Spawn' +not_logged_in: '&cVocê nao esta autenticado!' +reg_voluntarily: '&fVocê pode registrar o seu nickname no servidor com o comando "/register password ConfirmePassword"' +usage_log: '&cUse: /login password' +wrong_pwd: '&cPassword incorreta' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +unregistered: '&cRegistro eliminado com sucesso!' +reg_disabled: '&cRegistro de novos utilizadores desativado' +valid_session: '&cSessão válida' +login: '&cAutenticado com sucesso!' +vb_nonActiv: '&fA sua conta ainda nao foi ativada, verifique o seu email, onde irá receber instruções de como ativa-la.' +user_regged: '&cNome de usuario já registrado' +usage_reg: '&cUse: /register password ConfirmPassword' +max_reg: '&fVocê atingiu o numero máximo de registros permitidos' +no_perm: '&cSem Permissões' +error: '&fOcorreu um erro; Por favor contacte um admin' +login_msg: '&cIdentifique-se (logue) com "/login password"' +reg_msg: '&cPor favor registre-se com "/register password confirmePassword"' +reg_email_msg: '&cPor favor registre-se com "/register ""' +usage_unreg: '&cUse: /unregister password' +pwd_changed: '&cPassword alterada!' +user_unknown: '&cUsername não registrado' +password_error: '&fAs passwords não coincidem' +invalid_session: '&fDados de sessão não correspondem. Por favor aguarde o fim da sessão' +reg_only: '&fApenas jogadores registrados! Visite http://example.com para se registrar' +logged_in: '&cJá se encontra autenticado(logado)!' +logout: '&cSaida com sucesso' +same_nick: '&fO mesmo nickname já se encontra a jogar no servidor' +registered: '&cRegistrado com sucesso!' +pass_len: '&fPassword ou muito curto, ou muito longo.' +reload: '&fConfiguração e base de dados foram recarregadas' +timeout: '&fExcedeu o tempo para autenticação' +usage_changepassword: '&fUse: /changepassword PasswordAntiga PasswordNova' +name_len: '&cO seu nickname é muito curto, ou muito longo.' +regex: '&cO seu nickname contém caracteres não permitidos. Permitido: REG_EX' +add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail' +recovery_email: '&cPerdeu/esqueceu a sua password(senha)? Para a recupera-la escreva /email recovery ' +usage_captcha: '&cVocê precisa digitar um captcha, escreva: /captcha ' +wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA' +valid_captcha: '&cO seu captcha é válido!' +kick_forvip: '&cUm jogador VIP entrou no servidor cheio!' +kick_fullserver: '&cO servidor está actualmente cheio, tente mais tarde :/ !' +usage_email_add: '&fUse: /email add ' +usage_email_change: '&fUse: /email change ' +usage_email_recovery: '&fUse: /email recovery ' +new_email_invalid: '[AuthMe] Novo email invalido!' +old_email_invalid: '[AuthMe] Antigo email invalido!' +email_invalid: '[AuthMe] Email Invalido' +email_added: '[AuthMe] Email adicionado!' +email_confirm: '[AuthMe] Confirme o seu email!' +email_changed: '[AuthMe] Email modificado!' +email_send: '[AuthMe] Recuperação de email enviada!' +email_exists: '[AuthMe] Um email já existe na sua conta. Você pode mudalo usando o comando abaixo.' +country_banned: 'O seu pais é banido desse servidor' +antibot_auto_enabled: '[AuthMe] AntiBotMod ativado automaticamente devido a um aumento anormal de tentativas de ligação!' +antibot_auto_disabled: '[AuthMe] AntiBotMod desactivado automaticamente após %m minutos, esperamos que a invasão tenha parado' diff --git a/src/main/resources/messages/messages_cz.yml b/src/main/resources/messages/messages_cz.yml new file mode 100644 index 0000000..7492503 --- /dev/null +++ b/src/main/resources/messages/messages_cz.yml @@ -0,0 +1,57 @@ +unknown_user: '&cHrac neni registrovan.' +not_logged_in: '&cNeprihlasen!' +reg_voluntarily: '&cRegistruj se prikazem "/register heslo heslo".' +usage_log: '&cPouzij: "/login TvojeHeslo".' +wrong_pwd: '&cSpatne heslo.' +unregistered: '&cUspesne odregistrovan!' +reg_disabled: '&cRegistrace je zakazana!' +valid_session: '&cAutomaticke znovuprihlaseni.' +login: '&cUspesne prihlaseni!' +user_regged: '&cUzivatelske jmeno je jiz registrovano.' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +usage_reg: '&cPouzij: "/register heslo heslo".' +no_perm: '&cNemas opravneni.' +error: '&cVyskytla se chyba - kontaktujte administratora ...' +login_msg: '&cProsim prihlas se "/login TvojeHeslo".' +reg_msg: '&cProsim zaregistruj se "/register heslo heslo".' +reg_email_msg: '&cProsim registruj se pomoci "/register "' +usage_unreg: '&cPouzij: "/unregister TvojeHeslo".' +pwd_changed: '&cHeslo zmeneno!' +user_unknown: '&cUzivatelske jmeno neni registrovano.' +reg_only: '&cServer je pouze pro registrovane! Navstivte http://bit.ly/zyEzzS.' +logged_in: '&cJiz jsi prihlasen!' +logout: '&cOdhlaseni bylo uspesne.' +same_nick: '&cUzivatel s timto jmenem jiz hraje.' +registered: '&cRegistrace byla uspesna!' +reload: '&cZnovu nacteni nastaveni AuthMe probehlo uspesne.' +timeout: '&cCas pro prihlaseni vyprsel!' +unsafe_spawn: '&cTvoje pozice pri odpojeni byla nebezpecna, teleportuji na spawn!' +invalid_session: '&cChybna data pri cteni pockejte do vyprseni.' +max_reg: '&cJiz jsi prekrocil(a) limit pro pocet uctu z jedne IP.' +password_error: '&cHesla se neshoduji!' +pass_len: '&cTvoje heslo nedosahuje minimalni delky (4).' +vb_nonActiv: '&cTvuj ucet neni aktivovany, zkontrolujte si svuj E-mail.' +usage_changepassword: '&cPouzij: "/changepassword stareHeslo noveHeslo".' +name_len: '&cTvuj nick je prilis kratky, nebo prilis dlouhy' +regex: '&cTvuj nick obsahuje nepovolene znaky. Pripustne znaky jsou: REG_EX' +add_email: '&cPridej prosim svuj email pomoci : /email add TvujEmail TvujEmail' +recovery_email: '&cZapomel jsi heslo? Zadej: /email recovery ' +usage_captcha: '&cPouzij: /captcha ' +wrong_captcha: '&cSpatne opsana Captcha, pouzij prosim: /captcha CAPTCHA_TEXT' +valid_captcha: '&cZadana captcha je v poradku!' +kick_forvip: '&cVIP Hrac se pripojil na plny server!' +kick_fullserver: '&cServer je plne obsazen, zkus to pozdeji prosim!' +usage_email_add: '&fPouzij: /email add ' +usage_email_change: '&fPouzij: /email change ' +usage_email_recovery: '&fPouzij: /email recovery ' +new_email_invalid: '[AuthMe] Novy email je chybne zadan!' +old_email_invalid: '[AuthMe] Stary email je chybne zadan!' +email_invalid: '[AuthMe] Nespravny email' +email_added: '[AuthMe] Email pridan!' +email_confirm: '[AuthMe] Potvrd prosim svuj email!' +email_changed: '[AuthMe] Email zmenen!' +email_send: '[AuthMe] Email pro obnoveni hesla odeslan!' +country_banned: 'Vase zeme je na tomto serveru zakazana' +antibot_auto_enabled: '[AuthMe] AntiBotMod automaticky spusten z duvodu masivnich pripojeni!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automaticky ukoncen po %m minutach, doufejme v konec invaze' diff --git a/src/main/resources/messages/messages_de.yml b/src/main/resources/messages/messages_de.yml new file mode 100644 index 0000000..fa08601 --- /dev/null +++ b/src/main/resources/messages/messages_de.yml @@ -0,0 +1,58 @@ +unknown_user: '&cBenutzer ist nicht in der Datenbank' +unsafe_spawn: '&cDeine Logoutposition war unsicher, du wurdest zum Spawn teleportiert' +not_logged_in: '&cNicht eingeloggt!' +reg_voluntarily: 'Du kannst dich mit folgendem Befehl registrieren "/register "' +usage_log: '&cBenutze: /login ' +wrong_pwd: '&cFalsches Passwort' +unregistered: '&cBenutzerkonto erfolgreich gelöscht!' +reg_disabled: '&cRegistrierungen sind deaktiviert' +valid_session: '&2Erfolgreich eingeloggt!' +login: '&2Erfolgreich eingeloggt!' +vb_nonActiv: '&cDein Account wurde noch nicht aktiviert. Bitte prüfe Deine E-Mails!' +user_regged: '&cBenutzername ist schon vergeben' +usage_reg: '&cBenutze: /register ' +max_reg: '&cDu hast die maximale Anzahl an Accounts erreicht' +no_perm: '&4Du hast keine Rechte, um diese Aktion auszuführen!' +error: '&4Ein Fehler ist aufgetreten. Bitte kontaktiere einen Administrator' +login_msg: '&cBitte logge Dich ein mit "/login "' +reg_msg: '&3Bitte registriere Dich mit "/register "' +reg_email_msg: '&3Bitte registriere Dich mit "/register "' +usage_unreg: '&cBenutze: /unregister ' +pwd_changed: '&2Passwort geändert!' +user_unknown: '&cBenutzername nicht registriert!' +password_error: '&cPasswörter stimmen nicht überein!' +password_error_nick: '&cDu kannst nicht deinen Namen als Passwort nutzen!' +password_error_unsafe: '&cDu kannst nicht unsichere Passwörter nutzen!' +invalid_session: '&cUngültige Session. Bitte starte das Spiel neu oder warte, bis die Session abgelaufen ist' +reg_only: '&4Nur für registrierte Spieler! Bitte besuche http://example.com zum registrieren' +logged_in: '&cBereits eingeloggt!' +logout: '&2Erfolgreich ausgeloggt' +same_nick: '&4Jemand mit diesem Namen spielt bereits auf dem Server!' +registered: '&2Erfolgreich registriert!' +pass_len: '&cDein Passwort ist zu kurz oder zu lang!' +reload: '&2Konfiguration und Datenbank wurden erfolgreich neu geladen' +timeout: '&4Zeitüberschreitung beim Login' +usage_changepassword: '&cBenutze: /changepassword ' +name_len: '&4Dein Nickname ist zu kurz oder zu lang' +regex: '&4Dein Nickname enthält nicht erlaubte Zeichen. Zulässige Zeichen: REG_EX' +add_email: '&3Bitte hinterlege Deine E-Mail Adresse: /email add ' +recovery_email: '&3Passwort vergessen? Nutze "/email recovery " für ein neues Passwort' +usage_captcha: '&3Um dich einzuloggen, tippe dieses Captcha so ein: /captcha ' +wrong_captcha: '&cFalsches Captcha, bitte nutze: /captcha THE_CAPTCHA' +valid_captcha: '&2Das Captcha ist korrekt!' +kick_forvip: '&3Ein VIP Spieler hat den vollen Server betreten!' +kick_fullserver: '&4Der Server ist momentan voll, Sorry!' +usage_email_add: '&cBenutze: /email add ' +usage_email_change: '&cBenutze: /email change ' +usage_email_recovery: '&cBenutze: /email recovery ' +new_email_invalid: '&cDie neue Email ist ungültig!' +old_email_invalid: '&cDie alte Email ist ungültig!' +email_invalid: '&cUngültige Email' +email_added: '&2Email hinzugefügt!' +email_confirm: '&cBitte bestätige deine Email!' +email_changed: '&2Email aktualisiert!' +email_send: '&2Wiederherstellungs-Email wurde gesendet!' +email_exists: '&cEine Wiederherstellungs-Email wurde bereits versandt! Nutze folgenden Befehl um eine neue Email zu versenden:' +country_banned: '&4Dein Land ist gesperrt' +antibot_auto_enabled: '&4[AntiBotService] AntiBotMod wurde aufgrund hoher Netzauslastung automatisch aktiviert!' +antibot_auto_disabled: '&2[AntiBotService] AntiBotMod wurde nach %m Minuten deaktiviert, hoffentlich ist die Invasion vorbei' diff --git a/src/main/resources/messages/messages_en.yml b/src/main/resources/messages/messages_en.yml new file mode 100644 index 0000000..16218f3 --- /dev/null +++ b/src/main/resources/messages/messages_en.yml @@ -0,0 +1,58 @@ +unknown_user: '&cCan''t find the requested user in the database!' +unsafe_spawn: '&cYour quit location was unsafe, you have been teleported to the world''s spawnpoint.' +not_logged_in: '&cYou''re not logged in!' +reg_voluntarily: 'You can register yourself to the server with the command "/register "' +usage_log: '&cUsage: /login ' +wrong_pwd: '&cWrong password!' +unregistered: '&cSuccessfully unregistered!' +reg_disabled: '&cIn-game registration is disabled!' +valid_session: '&2Logged-in due to Session Reconnection.' +login: '&2Successful login!' +vb_nonActiv: '&cYour account isn''t activated yet, please check your emails!' +user_regged: '&cYou already have registered this username!' +usage_reg: '&cUsage: /register ' +max_reg: '&cYou have exceeded the maximum number of registrations for your connection!' +no_perm: '&4You don''t have the permission to perform this action!' +error: '&4An unexpected error occurred, please contact an Administrator!' +login_msg: '&cPlease, login with the command "/login "' +reg_msg: '&3Please, register to the server with the command "/register "' +reg_email_msg: '&3Please, register to the server with the command "/register "' +usage_unreg: '&cUsage: /unregister ' +pwd_changed: '&2Password changed successfully!' +user_unknown: '&cThis user isn''t registered!' +password_error: '&cPasswords didn''t match, check them again!' +password_error_nick: '&cYou can''t use your name as password, please choose another one...' +password_error_unsafe: '&cThe chosen password isn''t safe, please choose another one...' +invalid_session: '&cYour IP has been changed and your session data has expired!' +reg_only: '&4Only registered users can join the server! Please visit http://example.com to register yourself!' +logged_in: '&cYou''re already logged in!' +logout: '&2Logged-out successfully!' +same_nick: '&4The same username is already playing on the server!' +registered: '&2Successfully registered!' +pass_len: '&cYour password is too short or too long! Please try with another one!' +reload: '&2Configuration and database have been reloaded correctly!' +timeout: '&4Login timeout exceeded, you have been kicked from the server, please try again!' +usage_changepassword: '&cUsage: /changepassword ' +name_len: '&4Your username is either too short or too long!' +regex: '&4Your username contains illegal characters. Allowed chars: REG_EX' +add_email: '&3Please add your email to your account with the command "/email add "' +recovery_email: '&3Forgot your password? Please use the command "/email recovery "' +usage_captcha: '&3To login you have to solve a captcha code, please use the command "/captcha "' +wrong_captcha: '&cWrong Captcha, please type "/captcha THE_CAPTCHA" into the chat!' +valid_captcha: '&2Captcha code solved correctly!' +kick_forvip: '&3A VIP Player has joined the server when it was full!' +kick_fullserver: '&4The server is full, try again later!' +usage_email_add: '&cUsage: /email add ' +usage_email_change: '&cUsage: /email change ' +usage_email_recovery: '&cUsage: /email recovery ' +new_email_invalid: '&cInvalid New Email, try again!' +old_email_invalid: '&cInvalid Old Email, try again!' +email_invalid: '&cInvalid Email address, try again!' +email_added: '&2Email address successfully added to your account!' +email_confirm: '&cPlease confirm your email address!' +email_changed: '&2Email address changed correctly!' +email_send: '&2Recovery email sent correctly! Check your email inbox!' +email_exists: '&cA recovery email was already sent! You can discart it and send a new one using the command below:' +country_banned: '&4Your country is banned from this server!' +antibot_auto_enabled: '&4[AntiBotService] AntiBot enabled due to the huge number of connections!' +antibot_auto_disabled: '&2[AntiBotService] AntiBot disabled disabled after %m minutes!' diff --git a/src/main/resources/messages/messages_es.yml b/src/main/resources/messages/messages_es.yml new file mode 100644 index 0000000..e91e310 --- /dev/null +++ b/src/main/resources/messages/messages_es.yml @@ -0,0 +1,58 @@ +# This file must be in ANSI if win, or UTF-8 if linux. +unknown_user: '&fEl usuario no está en la base de datos' +unsafe_spawn: '&fTu lugar de desconexión es inseguro, teletransportándote al punto inicial del mundo' +not_logged_in: '&c¡No has iniciado sesión!' +reg_voluntarily: '&fRegístrate con: "/register Contraseña ConfirmarContraseña"' +usage_log: '&cUso: /login contraseña' +wrong_pwd: '&cContraseña incorrecta' +unregistered: '&c¡Cuenta eliminada del registro!' +reg_disabled: '&cEl registro está desactivado' +valid_session: '&cInicio de sesión' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +login: '&c¡Sesión iniciada!' +vb_nonActiv: '&fTu cuenta no está activada aún, ¡revisa tu correo!' +user_regged: '&cUsuario ya registrado' +usage_reg: '&cUso: /register Contraseña ConfirmarContraseña' +max_reg: '&fHas excedido la cantidad máxima de registros para tu cuenta' +no_perm: '&cNo tienes permiso' +error: '&fHa ocurrido un error. Por favor contacta al administrador.' +login_msg: '&cInicia sesión con "/login contraseña"' +reg_msg: '&cPor favor, regístrate con "/register Contraseña ConfirmarContraseña"' +reg_email_msg: '&cPlease register with "/register "' +usage_unreg: '&cUso: /unregister contraseña' +pwd_changed: '&c¡Contraseña cambiada!' +user_unknown: '&cUsuario no registrado' +password_error: '&fLas contraseñas no son iguales' +invalid_session: '&fLos datos de sesión no corresponden. Por favor espera a terminar la sesión.' +reg_only: '&f¡Sólo para jugadores registrados! Por favor visita http://www.example.com/ para registrarte' +logged_in: '&c¡Ya has iniciado sesión!' +logout: '&cDesconectado correctamente.' +same_nick: '&fYa hay un usuario con ese nick conectado (posible error)' +registered: '&c¡Registrado correctamente!' +pass_len: '&fTu contraseña es muy larga o muy corta' +reload: '&fLa configuración y la base de datos han sido recargados' +timeout: '&fTiempo de espera para inicio de sesión excedido' +usage_changepassword: '&fUso: /changepw contraseñaaActual contraseñaNueva' +name_len: '&cTu nombre de usuario es muy largo o muy corto' +regex: '&cTu usuario tiene carácteres no admitidos, los cuales son: REG_EX' +add_email: '&cPor favor agrega tu e-mail con: /email add tuEmail confirmarEmail' +recovery_email: '&c¿Olvidaste tu contraseña? Por favor usa /email recovery ' +usage_captcha: '&cUso: /captcha ' +wrong_captcha: '&cCaptcha incorrecto, please use : /captcha EL_CAPTCHA' +valid_captcha: '&c¡ Captcha ingresado correctamente !' +kick_forvip: '&cUn jugador VIP ha ingresado al servidor lleno!' +kick_fullserver: '&cEl servidor está lleno, lo sentimos!' +usage_email_add: '&fUso: /email add ' +usage_email_change: '&fUso: /email change ' +usage_email_recovery: '&fUso: /email recovery ' +new_email_invalid: '[AuthMe] Nuevo email inválido!' +old_email_invalid: '[AuthMe] Email anterior inválido!' +email_invalid: '[AuthMe] Email inválido' +email_added: '[AuthMe] Email agregado !' +email_confirm: '[AuthMe] Confirma tu Email !' +email_changed: '[AuthMe] Email cambiado !' +email_send: '[AuthMe] Correo de recuperación enviado !' +country_banned: 'Tu país ha sido baneado de este servidor!' +antibot_auto_enabled: '[AuthMe] AntiBotMod activado automáticamente debido a conexiones masivas!' +antibot_auto_disabled: '[AuthMe] AntiBotMod desactivado automáticamente luego de %m minutos. Esperamos que haya terminado' diff --git a/src/main/resources/messages/messages_eu.yml b/src/main/resources/messages/messages_eu.yml new file mode 100644 index 0000000..44d961d --- /dev/null +++ b/src/main/resources/messages/messages_eu.yml @@ -0,0 +1,58 @@ +unknown_user: '&fErabiltzailea ez dago datu basean' +unsafe_spawn: '&fSpawn-era telegarraiatu zara' +not_logged_in: '&cSaioa hasi gabe!' +reg_voluntarily: '&fZure erabiltzailea erregistratu dezakezu:"/register pasahitza pasahitza"' +usage_log: '&cErabili: /login pasahitza' +wrong_pwd: '&cPasahitz okerra' +unregistered: '&cZure erregistroa ezabatu duzu!' +reg_disabled: '&cErregistroa desgaitua' +valid_session: '&cSession login' +login: '&cOngi etorri!' +vb_nonActiv: '&fZure kontua aktibatu gabe dago, konfirmatu zure emaila!' +user_regged: '&cErabiltzailea dagoeneko erregistratua' +usage_reg: '&cErabili: /register pasahitza pasahitza' +max_reg: '&fKontuko 2 erabiltzaile bakarrik izan ditzakezu' +no_perm: '&cBaimenik ez' +error: '&fErrorea; Mesedez jarri kontaktuan administratzaile batekin' +login_msg: '&cMesedez erabili "/login pasahitza" saioa hasteko' +reg_msg: '&cMesedez erabili "/register pasahitza pasahitza" erregistratzeko' +reg_email_msg: '&cMesdez erabili "/register " erregistratzeko' +usage_unreg: '&cErabili: /unregister password' +pwd_changed: '&cPasahitza aldatu duzu!' +user_unknown: '&cErabiltzailea ez dago erregistratuta' +password_error: '&fPasahitzak ez datoz bat' +password_error_nick: '&fYou can''t use your name as password, please choose another one' +password_error_unsafe: '&fThe chosen password is not safe, please choose another one' +invalid_session: '&fSession Dataes doesnt corrispond Plaese wait the end of session' +reg_only: '&fErregistratuako erabiltzaileak bakarrik! Mesedez bisitatu http://example.com erregistratzeko' +logged_in: '&cDagoeneko saioa hasita!' +logout: '&cAtera zara' +same_nick: '&fZure izen berdina duen erabiltzaile bat zerbitzarian jolasten dago' +registered: '&cOndo erregistratu zara!' +pass_len: '&fZure pasahitza motzegia edo luzeegia da' +reload: '&fConfiguration and database has been reloaded' +timeout: '&fDenbora gehiegi egon zara saioa hasi gabe' +usage_changepassword: '&fErabili: /changepassword pasahitzZaharra pasahitzBerria' +name_len: '&cZure erabiltzaile izena motzegia edo luzeegia da' +regex: '&cZure erabiltzaileak karaktere debekatuak ditu. Karaktere onartuak: REG_EX' +add_email: '&cMesedez gehitu zure emaila : /email add yourEmail confirmEmail' +recovery_email: '&cPasahitza ahaztu duzu? Erabili /email recovery ' +usage_captcha: '&cYou need to type a captcha, please type: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' +kick_forvip: '&cVIP erabiltzaile bat sartu da zerbitzaria beteta zegoenean!' +kick_fullserver: '&cZerbitzaria beteta dago, Barkatu!' +usage_email_add: '&fErabili: /email add ' +usage_email_change: '&fErabili: /email change ' +usage_email_recovery: '&fErabili: /email recovery ' +new_email_invalid: '[AuthMe] Email okerra!' +old_email_invalid: '[AuthMe] Email zaharra okerra!' +email_invalid: '[AuthMe] Email okerrea' +email_added: '[AuthMe] Emaila gehitu duzu !' +email_confirm: '[AuthMe] Konfirmatu zure emaila !' +email_changed: '[AuthMe] Emaila aldatua!' +email_send: '[AuthMe] Berreskuratze emaila bidalita !' +email_exists: '[AuthMe] An email already exists on your account. You can change it using the command below' +country_banned: '[AuthMe]Zure herrialdea blokeatuta dago zerbitzari honetan' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes,hope invasion stopped' diff --git a/src/main/resources/messages/messages_fi.yml b/src/main/resources/messages/messages_fi.yml new file mode 100644 index 0000000..be3779c --- /dev/null +++ b/src/main/resources/messages/messages_fi.yml @@ -0,0 +1,57 @@ +unknown_user: '&fKäyttäjä ei ole tietokannassa!' +unsafe_spawn: '&fHengenvaarallinen poistumispaikka! Siirsimme sinut spawnille!' +not_logged_in: '&cEt ole kirjautunut sisään!' +reg_voluntarily: '&fNyt voit rekisteröidä pelaajasi palvelimellemme: "/register salasana salasana"' +usage_log: '&cKäyttötapa: /login salasana' +wrong_pwd: '&cVäärä salasana' +unregistered: '&cPelaajatili poistettu onnistuneesti!' +reg_disabled: '&cRekisteröinti on suljettu!' +valid_session: '&cIstunto jatkettu!' +login: '&cKirjauduit onnistuneesti' +vb_nonActiv: '&fKäyttäjäsi ei ole vahvistettu!' +user_regged: '&cPelaaja on jo rekisteröity' +usage_reg: '&cKäyttötapa: /register salasana salasana' +max_reg: '&fSinulla ei ole oikeuksia tehdä enempää pelaajatilejä!' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +no_perm: '&cEi oikeuksia' +error: '&fVirhe: Ota yhteys palveluntarjoojaan!' +login_msg: '&cKirjaudu palvelimmelle komennolla "/login salasana"' +reg_msg: '&cRekisteröidy palvelimellemme komennolla "/register salasana salasana"' +reg_email_msg: '&cRekisteröi sähköpostisi komennolla "/register "' +usage_unreg: '&cKäyttötapa: /unregister password' +pwd_changed: '&cSalasana vaihdettu!!' +user_unknown: '&cSalasanat eivät täsmää' +password_error: '&fSalasanat ei täsmää' +invalid_session: '&fIstunto ei täsmää! Ole hyvä ja odota istunnon loppuun' +reg_only: '&fMene sivustolle: http://example.com rekisteröityäksesi!' +logged_in: '&cOlet jo kirjautunut!' +logout: '&cKirjauduit ulos palvelimelta.' +same_nick: '&COlet jo palvelimella! &COdota käyttäjän aikakatkaisua tai ota yhteyttä palveluntarjoojaan.' +registered: '&cRekisteröidyit onnistuneesti!' +pass_len: '&fSalasanasi on liian pitkä tai lyhyt.' +reload: '&fAsetukset uudelleenladattu' +timeout: '&fKirjautumisaika meni umpeen.' +usage_changepassword: '&fKäyttötapa: /changepassword vanhaSalasana uusiSalasana' +name_len: '&cPelaajanimesi on liian lyhyt tai pitkä' +regex: '&cPelaajanimesi sisältää luvattomia merkkejä. Hyväksytyt merkit: REG_EX' +add_email: '&cLisää sähköpostisi: /email add sähköpostisi sähköpostisiUudelleen' +recovery_email: '&cUnohtuiko salasana? Käytä komentoa: /email recovery ' +usage_captcha: '&cKäyttötapa: /captcha ' +wrong_captcha: '&cVäärä varmistus, käytä : /captcha CAPTCHA' +valid_captcha: '&cSinun varmistus onnistui.!' +kick_forvip: '&cVIP pelaaja liittyi täyteen palvelimeen!' +kick_fullserver: '&cPalvelin on täynnä, Yritä pian uudelleen!' +usage_email_add: '&fKäyttötapa: /email add ' +usage_email_change: '&fKäyttötapa: /email change ' +usage_email_recovery: '&fKäyttötapa: /email recovery ' +new_email_invalid: '[AuthMe] Uusi sähköposti on väärä!' +old_email_invalid: '[AuthMe] Vanha sähköposti on väärä!' +email_invalid: '[AuthMe] Väärä sähköposti' +email_added: '[AuthMe] Sähköposti lisätty!' +email_confirm: '[AuthMe] Vahvistuta sähköposti!' +email_changed: '[AuthMe] Sähköposti vaihdettu!' +email_send: '[AuthMe] Palautus sähköposti lähetetty!' +country_banned: 'Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped' diff --git a/src/main/resources/messages/messages_fr.yml b/src/main/resources/messages/messages_fr.yml new file mode 100644 index 0000000..51a2a53 --- /dev/null +++ b/src/main/resources/messages/messages_fr.yml @@ -0,0 +1,58 @@ +# Traduction par: André +unknown_user: '&fUtilisateur non enregistré' +unsafe_spawn: '&fTéléportation dans un endroit sûr' +not_logged_in: '&cNon connecté!' +reg_voluntarily: '&fVous venez d''arriver? faites un "/register motdepasse confirmermotdepasse"' +usage_log: '&cUtilisez: /login motdepasse' +wrong_pwd: '&cMauvais MotdePasse' +unregistered: '&cCe compte a été supprimé!' +reg_disabled: '&cL''enregistrement est désactivé' +valid_session: '&cVous êtes authentifié' +login: '&cConnection effectuée!' +vb_nonActiv: '&fCe compte n''est pas actif, consultez vos emails!' +user_regged: '&cCe nom est deja utilisé..' +usage_reg: '&cUtilisez la commande /register motdepasse confirmermotdepasse' +max_reg: '&fLimite d''enregistrement atteinte pour ce compte' +no_perm: '&cVous n''avez pas la permission' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +error: '&fUne erreur est apparue, veuillez contacter un administrateur' +login_msg: '&cPour vous connecter, utilisez: /login motdepasse' +reg_msg: '&cPour vous inscrire, utilisez "/register motdepasse confirmermotdepasse"' +reg_email_msg: '&cPour vous inscrire, utilisez "/register "' +usage_unreg: '&cPour supprimer ce compte, utilisez: /unregister password' +pwd_changed: '&cMotdePasse changé avec succès!' +user_unknown: '&c Ce compte n''est pas enregistré' +password_error: '&fCe mot de passe est incorrect' +invalid_session: '&fSession invalide, relancez le jeu ou attendez la fin de la session' +reg_only: '&fSeul les joueurs enregistré sont admis!' +logged_in: '&cVous êtes déjà connecté!' +logout: '&cVous avez été déconnecté!' +same_nick: '&fUne personne ayant ce même pseudo joue déjà..' +registered: '&cEnregistrement réussi avec succès!' +pass_len: '&fVotre mot de passe n''est pas assez long..' +reload: '&fConfiguration et BDD relancé avec succès' +timeout: '&fVous avez été expulsé car vous êtes trop lent pour vous enregistrer !' +usage_changepassword: '&fPour changer de mot de passe, utilisez: /changepassword ancienmdp nouveaumdp' +name_len: '&cVotre pseudo est trop long ou trop court' +regex: '&cCaractères autorisés: REG_EX' +add_email: '&cMerci d''ajouter votre email : /email add yourEmail confirmEmail' +recovery_email: '&cVous avez oublié votre MotdePasse? Utilisez /email recovery ' +usage_captcha: '&cTrop de tentatives de connexion échouées, utilisez: /captcha ' +wrong_captcha: '&cCaptcha incorrect, écrivez de nouveau : /captcha THE_CAPTCHA' +valid_captcha: '&cLe Captcha est valide, merci!' +kick_forvip: '&cUn joueur VIP a rejoint le serveur plein!' +kick_fullserver: '&cLe serveur est actuellement plein, désolé!' +usage_email_add: '&fUsage: /email add ' +usage_email_change: '&fUsage: /email change ' +usage_email_recovery: '&fUsage: /email recovery ' +new_email_invalid: '[AuthMe] Nouvel email invalide!' +old_email_invalid: '[AuthMe] Ancien email invalide!' +email_invalid: '[AuthMe] Email invalide' +email_added: '[AuthMe] Email ajouté !' +email_confirm: '[AuthMe] Confirmez votre email !' +email_changed: '[AuthMe] Email changé !' +email_send: '[AuthMe] Email de récupération envoyé!' +country_banned: 'Votre pays est banni de ce serveur' +antibot_auto_enabled: '[AuthMe] AntiBotMod a été activé automatiquement à cause de nombreuses connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod a été désactivé automatiquement après %m Minutes, espérons que l''invasion soit arrêtée!' diff --git a/src/main/resources/messages/messages_gl.yml b/src/main/resources/messages/messages_gl.yml new file mode 100644 index 0000000..2ead031 --- /dev/null +++ b/src/main/resources/messages/messages_gl.yml @@ -0,0 +1,59 @@ +unknown_user: '&fO usuario non está na base de datos' +unsafe_spawn: '&fA localización dende a que saíches era insegura, teletransportándote ao spawn do mundo' +not_logged_in: '&cNon te identificaches!' +reg_voluntarily: '&fPodes rexistrar o teu nome no servidor co comando + "/register "' +usage_log: '&cUso: /login ' +wrong_pwd: '&cContrasinal equivocado' +unregistered: '&cFeito! Xa non estás rexistrado!' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +reg_disabled: '&cO rexistro está deshabilitado' +valid_session: '&cIdentificado mediante a sesión' +login: '&cIdentificación con éxito!' +vb_nonActiv: '&fA túa conta aínda non está activada, comproba a túa bandexa de correo!!' +user_regged: '&cEse nome de usuario xa está rexistrado' +usage_reg: '&cUso: /register contrasinal confirmarContrasinal' +max_reg: '&fExcediches o máximo de rexistros para a túa Conta' +no_perm: '&cNon tes o permiso' +error: '&fOcurriu un erro; contacta cun administrador' +login_msg: '&cPor favor, identifícate con "/login "' +reg_msg: '&cPor favor, rexístrate con "/register "' +reg_email_msg: '&cPor favor, rexístrate con "/register "' +usage_unreg: '&cUso: /unregister ' +pwd_changed: '&cCambiouse o contrasinal!' +user_unknown: '&cEse nome de usuario non está rexistrado' +password_error: '&fO contrasinal non coincide' +invalid_session: '&fOs datos de sesión non corresponden, por favor, espere a que remate a sesión' +reg_only: '&fSó xogadores rexistrados! Por favor, visita http://example.com para rexistrarte' +logged_in: '&cXa estás identificado!' +logout: '&cSesión pechada con éxito' +same_nick: '&fXa está xogando alguén co mesmo nome' +registered: '&cRexistrado con éxito!' +pass_len: '&fO teu contrasinal non alcanza a lonxitude mínima ou excede a lonxitude máxima' +reload: '&fRecargáronse a configuración e a base de datos' +timeout: '&fRematou o tempo da autentificación' +usage_changepassword: '&fUso: /changepassword ' +name_len: '&cO teu nome é demasiado curto ou demasiado longo' +regex: '&cO teu nome contén caracteres ilegais. Caracteres permitidos: REG_EX' +add_email: '&cPor favor, engade o teu correo electrónico con: /email add ' +recovery_email: '&cOlvidaches o contrasinal? Por favor, usa /email recovery ' +usage_captcha: '&cNecesitas escribir un captcha, por favor escribe: /captcha ' +wrong_captcha: '&cCaptcha equivocado, por favor usa: /captcha THE_CAPTCHA' +valid_captcha: '&cO teu captcha é válido !' +kick_forvip: '&cUn xogador VIP uniuse ao servidor cheo!' +kick_fullserver: '&cO servidor está actualmente cheo, sentímolo!' +usage_email_add: '&fUso: /email add ' +usage_email_change: '&fUso: /email change ' +usage_email_recovery: '&fUso: /email recovery ' +new_email_invalid: '[AuthMe] O novo correo non é válido!' +old_email_invalid: '[AuthMe] O correo vello non é válido!' +email_invalid: '[AuthMe] Correo non válido' +email_added: '[AuthMe] Correo engadido!' +email_confirm: '[AuthMe] Confirma o teu correo!' +email_changed: '[AuthMe] Cambiouse o correo!' +email_send: '[AuthMe] Enviouse o correo de confirmación!' +country_banned: 'O teu país está bloqueado neste servidor' +antibot_auto_enabled: '[AuthMe] AntiBotMod conectouse automáticamente debido a conexións masivas!' +antibot_auto_disabled: '[AuthMe] AntiBotMod desactivouse automáticamente despois de %m minutos, + esperemos que a invasión se detivera' diff --git a/src/main/resources/messages/messages_hu.yml b/src/main/resources/messages/messages_hu.yml new file mode 100644 index 0000000..68fde4d --- /dev/null +++ b/src/main/resources/messages/messages_hu.yml @@ -0,0 +1,57 @@ +reg_only: Csak regisztrált játékosoknak! Jelentkezni a yndicraft@freemail.hu e-mail címen lehet +usage_unreg: '&cHasználat: /unregister jelszó' +registered: '&aSikeres regisztráció. Üdvözöllek!' +user_regged: '&cJátékosnév már regisztrálva' +login_msg: '&cKérlek jelentkezz be: "/login jelszó"' +not_logged_in: '&cNem vagy bejelentkezve!' +logout: '&cSikeresen kijelentkeztél' +usage_log: '&cBejelentkezés: /login jelszó' +unknown_user: User is not in database +reg_voluntarily: Regisztrálhatod beceneved a szerveren a következö parancsal "/register jelszó jelszó" +reg_disabled: '&cRegisztráció letiltva' +no_perm: '&cNincs engedélyed' +usage_reg: '&cHasználat: /register jelszó jelszóújra' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +unregistered: '&cRegisztráció sikeresen törölve!' +same_nick: Ezen a játékosnéven már játszanak +valid_session: '&cSession login' +pwd_changed: '&cJelszó cserélve!' +reload: Beálítások és adatbázis újratöltve! +timeout: Bejelentkezési idötúllépés +error: Hiba lépett fel; Lépj kapcsolatba a tulajjal' +logged_in: '&cMár be vagy jelentkezve!' +login: '&aSikeresen Beléptél! Üdvözöllek!!!' +wrong_pwd: '&4Hibás jelszó' +user_unknown: '&cJátékosnév nem regisztrált' +reg_msg: '&cKérlek Regisztrálj: "/register jelszó jelszóújra"' +reg_email_msg: '&cPlease register with "/register "' +unsafe_spawn: A kilépési helyzeted nem biztonságos, teleportálás a kezdö Spawnra. +max_reg: Csak egy karakterrel Registrálhatsz!!! +password_error: A jelszó nem illik össze +invalid_session: Session Dataes doesnt corrispond Plaese wait the end of session +pass_len: A jelszavad nem éri el a minimális hosszat +vb_nonActiv: Your Account isent Activated yet check your Emails! +usage_changepassword: 'használat: /changepassword régiJelszó újJelszó' +name_len: '&cYour nickname is too Short or too long' +regex: '&cYour nickname contains illegal characters. Allowed chars: REG_EX' +add_email: '&cPlease add your email with : /email add yourEmail confirmEmail' +recovery_email: '&cForgot your password? Please use /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' +kick_forvip: '&cA VIP Player join the full server!' +kick_fullserver: '&cThe server is actually full, Sorry!' +usage_email_add: '&fUsage: /email add ' +usage_email_change: '&fUsage: /email change ' +usage_email_recovery: '&fUsage: /email recovery ' +new_email_invalid: '[AuthMe] New email invalid!' +old_email_invalid: '[AuthMe] Old email invalid!' +email_invalid: '[AuthMe] Invalid Email' +email_added: '[AuthMe] Email Added !' +email_confirm: '[AuthMe] Confirm your Email !' +email_changed: '[AuthMe] Email Change !' +email_send: '[AuthMe] Recovery Email Send !' +country_banned: 'Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped' diff --git a/src/main/resources/messages/messages_id.yml b/src/main/resources/messages/messages_id.yml new file mode 100644 index 0000000..2b183f3 --- /dev/null +++ b/src/main/resources/messages/messages_id.yml @@ -0,0 +1,58 @@ +unknown_user: '&cTidak dapat menemukan user yg diminta di database!' +unsafe_spawn: '&cLokasi quit kamu tidak aman, kamu telah diteleport ke titik spawn world.' +not_logged_in: '&cKamu belum login!' +reg_voluntarily: 'Kamu bisa register menggunakan command "/register "' +usage_log: '&cUsage: /login ' +wrong_pwd: '&cPassword salah!' +unregistered: '&cUnregister berhasil!' +reg_disabled: '&cRegister dalam game tidak diaktifkan!' +valid_session: '&2Otomatis login, karena sesi masih terhubung.' +login: '&2Login berhasil!' +vb_nonActiv: '&cAkunmu belum diaktifkan, silahkan periksa email kamu!' +user_regged: '&cKamu telah mendaftarkan username ini!' +usage_reg: '&cUsage: /register ' +max_reg: '&Kamu telah mencapai batas maksimum pendaftaran di server ini!' +no_perm: '&4Kamu tidak mempunyai izin melakukan ini!' +error: '&4Terjadi kesalahan tak dikenal, silahkan hubungi Administrator!' +login_msg: '&cSilahkan login menggunakan command "/login "' +reg_msg: '&3Silahkan mendaftar ke server menggunakan command "/register "' +reg_email_msg: '&3Silahkan mendaftar ke server menggunakan command "/register "' +usage_unreg: '&cUsage: /unregister ' +pwd_changed: '&2Berhasil mengubah password!' +user_unknown: '&cUser ini belum terdaftar!' +password_error: '&cPassword tidak cocok, silahkan periksa dan ulangi kembali!' +password_error_nick: '&cKamu tidak bisa menggunakan namamu sebagai password, silahkan coba yg lain...' +password_error_unsafe: '&cPassword yg kamu pilih tidak aman, silahkan coba yg lain...' +invalid_session: '&cIP kamu telah berubah, dan sesi kamu telah berakhir!' +reg_only: '&4Hanya pengguna terdaftar yg bisa bergabung! Silahkan kunjungi http://example.com untuk mendaftar!' +logged_in: '&cKamu telah login!' +logout: '&2Berhasil logout!' +same_nick: '&4Username yg sama telah bermain di server ini!' +registered: '&2Register berhasil!' +pass_len: '&cPassword kamu terlalu panjang/pendek! Silahkan pilih yg lain!' +reload: '&2Konfigurasi dan database telah dimuat ulang!' +timeout: '&4Jangka waktu login telah habis, kamu di keluarkan dari server. Silahkan coba lagi!' +usage_changepassword: '&cUsage: /changepassword ' +name_len: '&4Username kamu terlalu panjang atau terlalu pendek!' +regex: '&4Username kamu mengandung karakter illegal. Karakter yg diijinkan: REG_EX' +add_email: '&3Silahkan tambahkan email ke akunmu menggunakan command "/email add "' +recovery_email: '&3Lupa password? silahkan gunakan command "/email recovery "' +usage_captcha: '&3Kamu harus menyelesaikan kode captcha untuk login, silahkan gunakan command "/captcha "' +wrong_captcha: '&cCaptcha salah, gunakan command "/captcha THE_CAPTCHA" pada chat!' +valid_captcha: '&2Kode captcha terselesaikan!' +kick_forvip: '&3Player VIP mencoba masuk pada saat server sedang penuh!' +kick_fullserver: '&4Server sedang penuh, silahkan coba lagi nanti!' +usage_email_add: '&cUsage: /email add ' +usage_email_change: '&cUsage: /email change ' +usage_email_recovery: '&cUsage: /email recovery ' +new_email_invalid: '&cEmail baru tidak valid, coba lagi!' +old_email_invalid: '&cEmail lama tidak valid, coba lagi!' +email_invalid: '&cAlamat email tidak valid, coba lagi!' +email_added: '&2Berhasil menambahkan alamat email ke akunmu!' +email_confirm: '&cSilahkan konfirmasi alamat email kamu!' +email_changed: '&2Alamat email telah diubah dengan benar!' +email_send: '&2Email pemulihan akun telah dikirim! Silahkan periksa kotak masuk emailmu!' +email_exists: '&cEmail pemulihan sudah dikirim! kamu bisa membatalkan dan mengirimkan yg baru dengan command dibawah:' +country_banned: '&4Your country is banned from this server!' +antibot_auto_enabled: '&4[AntiBotService] AntiBot diaktifkan dikarenakan banyak koneksi yg diterima!' +antibot_auto_disabled: '&2[AntiBotService] AntiBot dimatikan setelah %m menit!' diff --git a/src/main/resources/messages/messages_it.yml b/src/main/resources/messages/messages_it.yml new file mode 100644 index 0000000..4e4a0fa --- /dev/null +++ b/src/main/resources/messages/messages_it.yml @@ -0,0 +1,58 @@ +unknown_user: 'L''utente non è presente nel database.' +unsafe_spawn: 'Il tuo punto di disconnessione risulta ostruito o insicuro, sei stato teletrasportato al punto di rigenerazione!' +not_logged_in: '&cNon hai ancora eseguito l''autenticazione!' +reg_voluntarily: 'Puoi eseguire la registrazione al server con il comando: "/register "' +usage_log: '&cUtilizzo: /login ' +wrong_pwd: '&cPassword non corretta!' +unregistered: '&cSei stato rimosso dal database con successo!' +reg_disabled: '&cLa registrazione tramite i comandi di gioco è disabilitata.' +valid_session: '&cAutenticato automaticamente attraverso la precedente sessione!' +login: '&cAutenticazone effettuata correttamente!' +vb_nonActiv: 'Il tuo account non è stato ancora verificato, controlla fra le tue email per scoprire come attivarlo!' +user_regged: '&cHai già effettuato la registrazione, non puoi eseguirla nuovamente.' +usage_reg: '&cUtilizzo: /register ' +error: 'Qualcosa è andato storto, riporta questo errore ad un Admin!' +max_reg: 'Hai raggiunto il numero massimo di registrazioni per questo indirizzo IP!' +no_perm: '&cNon hai il permesso di eseguire questa operazione.' +login_msg: '&cPerfavore, esegui l''autenticazione con il comando: "/login "' +reg_msg: '&cPerfavore, esegui la registrazione con il comando: "/register "' +reg_email_msg: '&cPerfavore, esegui la registrazione con il comando: "/register "' +usage_unreg: '&cUtilizzo: /unregister ' +pwd_changed: '&cPassword cambiata con successo!' +user_unknown: '&cL''utente non ha ancora eseguito la registrazione.' +password_error: 'Le Password non corrispondono!' +password_error_nick: 'Non puoi usare il tuo nome utente come password, scegline un''altra!' +password_error_unsafe: 'La password che hai inserito non è sicura, scegline un''altra!' +invalid_session: 'I tuoi dati di connessione attuali non sono quelli utilizzati in precedenza. Attendi la fine della sessione attuale.' +reg_only: 'Puoi giocare in questo server solo dopo aver effettuato la registrazione attraverso il sito web! Perfavore, vai su http://esempio.it per procedere!' +logged_in: '&cHai già eseguito l''autenticazione, non devi eseguirla nuovamente!' +logout: '&cDisconnessione avvenuta correttamente!' +same_nick: 'Questo stesso nome utente è già online sul server!' +registered: '&cRegistrato correttamente!' +pass_len: 'La password che hai inserito è troppo corta o troppo lunga, scegline un''altra!' +reload: 'La configurazione e il database sono stati ricaricati con successo!' +timeout: 'Tempo scaduto per effettuare l''autenticazione' +usage_changepassword: 'Utilizzo: /changepassword ' +name_len: '&cIl tuo nome utente è troppo corto o troppo lungo!' +regex: '&cIl tuo nome utente contiene caratteri non consentiti. I caratteri consentiti sono: REG_EX' +add_email: '&cPer poter recuperare la password in futuro, aggiungi un indirizzo email al tuo account con il comando: "/email add "' +recovery_email: '&cHai dimenticato la tua password? Puoi recuperarla eseguendo il comando: "/email recovery "' +usage_captcha: '&cAbbiamo bisogno che tu inserisca un captcha, perfavore scrivi: "/captcha THE_CAPTCHA"' +wrong_captcha: '&cCaptcha sbagliato, perfavore riprova con il comando: "/captcha THE_CAPTCHA"' +valid_captcha: '&cIl captcha inserito è valido!' +kick_forvip: '&cUn utente VIP è entrato mentre il server era pieno e ha preso il tuo posto!' +kick_fullserver: '&cIl server è attualmente pieno, riprova più tardi!' +usage_email_add: '&fUtilizzo: /email add ' +usage_email_change: '&fUtilizzo: /email change ' +usage_email_recovery: '&fUtilizzo: /email recovery ' +new_email_invalid: 'Il nuovo indirizzo email inserito non è valido!' +old_email_invalid: 'Il vecchio indirizzo email inserito non è valido!' +email_invalid: 'L''indirizzo email inserito non è valido' +email_added: 'Indirizzo email aggiunto correttamente!' +email_confirm: 'Conferma il tuo indirizzo email!' +email_changed: 'Indirizzo email cambiato correttamente!' +email_send: 'Una email di recupero è stata appena inviata al tuo indirizzo email!' +email_exists: 'Il tuo account ha già un''indirizzo email configurato. Se vuoi, puoi cambiarlo con il seguente comando:' +country_banned: 'Il tuo paese è bandito da questo server!' +antibot_auto_enabled: 'Il servizio di AntiBot è stato automaticamente abilitato a seguito delle numerose connessioni!' +antibot_auto_disabled: "Il servizio di AntiBot è stato automaticamente disabilitato dopo %m Minuti, sperando che l'attacco sia finito!" diff --git a/src/main/resources/messages/messages_ko.yml b/src/main/resources/messages/messages_ko.yml new file mode 100644 index 0000000..db1bd42 --- /dev/null +++ b/src/main/resources/messages/messages_ko.yml @@ -0,0 +1,62 @@ +# Korean translate by wolfwork # +# wolfdate25@gmail.com # +# 16.08.2014 Thanks for use # + +unknown_user: '&f사용자가 데이터베이스에 존재하지 않습니다' +unsafe_spawn: '&f당신이 종료한 위치는 안전하지 않았습니다, 세계의 소환지점으로 이동합니다' +not_logged_in: '&c접속되어있지 않습니다!' +reg_voluntarily: '&f당신은 당신의 이름을 "/register 비밀번호 비밀번호확인" 명령어로 가입하실 수 있습니다' +usage_log: '&c사용법: /login 비밀번호' +wrong_pwd: '&c잘못된 비밀번호입니다' +unregistered: '&c성공적으로 탈퇴했습니다!' +reg_disabled: '&c가입이 비활성화 되어있습니다' +valid_session: '&c세션 로그인' +login: '&c성공적인 접속입니다!' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +vb_nonActiv: '&f당신의 계정은 아직 활성화되어있지 않습니다, 당신의 이메일을 확인해보세요!' +user_regged: '&c사용자이름은 이미 가입했습니다' +usage_reg: '&c사용법: /register 비밀번호 비밀번호확인' +max_reg: '&f당신은 가입할 수 있는 계정의 최대 한도를 초과했습니다' +no_perm: '&c권한이 없습니다' +error: '&f오류가 발생했습니다; 관리자에게 문의해주세요' +login_msg: '&c접속 하실려면 "/login 비밀번호"를 치세요' +reg_msg: '&c가입하실려면 "/register 비밀번호 비밀번호재입력"을 치세요' +reg_email_msg: '&c가입하실려면 "/register <이메일> <이메일재입력>을 치세요"' +usage_unreg: '&c사용법: /unregister 비밀번호' +pwd_changed: '&c비밀번호를 변경했습니다!' +user_unknown: '&c사용자이름은 가입되지 않았습니다' +password_error: '&f비밀번호가 일치하지 않습니다' +invalid_session: '&f세션일자가 적합하지 않습니다. 세션이 종료될 때까지 기다려주세요' +reg_only: '&f가입한 플레이어만이 가능합니다! 가입하실려면 http://example.com 에 방문해주세요' +logged_in: '&c이미 접속되었습니다!' +logout: '&c성공적으로 접속해제하였습니다' +same_nick: '&f같은 이름으로 이미 플레이하고 있습니다' +registered: '&c성공적으로 가입했습니다!' +pass_len: '&f당신의 비밀번호는 최소 길이에 미치지 않거나 최대 길이를 초과했습니다' +reload: '&f설정과 데이터베이스는 갱신되었습니다' +timeout: '&f접속시간 초과' +usage_changepassword: '&f사용법: /changepassword 기존비밀번호 새로운비밀번호' +name_len: '&c당신의 이름은 너무 짧거나 너무 깁니다' +regex: '&c당신의 이름에는 불법적인 글자들이 포함되어있습니다. 허용된 글자: REG_EX' +add_email: '&c당신의 이메일을 추가해주세요 : /email add 당신의이메일 이메일재입력' +recovery_email: '&c비밀번호를 잊어버리셨다고요? /email recovery <당신의이메일>을 사용하세요' +usage_captcha: '&c보안문자 입력이 필요합니다, 입력해주세요: /captcha ' +wrong_captcha: '&c잘못된 보안문자, 사용해주세요 : /captcha THE_CAPTCHA' +valid_captcha: '&c당신의 보안문자는 적합합니다!' +kick_forvip: '&c서버가 만원인 상태일때 VIP 플레이어들만 입장이 가능합니다!' +kick_fullserver: '&c서버가 만원입니다, 나중에 다시 시도해주세요' +usage_email_add: '&f사용법: /email add <이메일> <이메일확인> ' +usage_email_change: '&f사용법: /email change <기존이메일> <새로운이메일> ' +usage_email_recovery: '&f사용법: /email recovery <이메일>' +new_email_invalid: '[AuthMe] 새 이메일이 올바르지 않습니다!' +old_email_invalid: '[AuthMe] 기존 이메일이 올바르지 않습니다!' +email_invalid: '[AuthMe] 올바르지 않은 이메일' +email_added: '[AuthMe] 이메일을 추가했습니다!' +email_confirm: '[AuthMe] 당신의 이메일을 확인하세요!' +email_changed: '[AuthMe] 이메일이 변경되었습니다!' +email_send: '[AuthMe] 복구 이메일을 보냈습니다!' +email_exists: '[AuthMe] 당신의 계정에 이미 이메일이 존재합니다. 아래의 명령어를 통해 이메일을 변경하실 수 있습니다' +country_banned: '당신의 국가는 이 서버에서 차단당했습니다' +antibot_auto_enabled: '[AuthMe] 봇차단모드가 연결 개수 때문에 자동적으로 활성화됩니다!' +antibot_auto_disabled: '[AuthMe] 봇차단모드가 %m 분 후에 자동적으로 비활성화됩니다' diff --git a/src/main/resources/messages/messages_lt.yml b/src/main/resources/messages/messages_lt.yml new file mode 100644 index 0000000..80a7b3a --- /dev/null +++ b/src/main/resources/messages/messages_lt.yml @@ -0,0 +1,57 @@ +unknown_user: '&cNaudotojo nera duombazeje' +unsafe_spawn: '&6Atsijungimo vieta nesaugi, perkeliame jus i atsiradimo vieta.' +not_logged_in: '&cTu neprisijunges!' +reg_voluntarily: '&ePrisiregistruokite: /register slaptazodis pakartotiSlaptazodi' +usage_log: '&eKomandos panaudojimas: /login slaptazodis' +wrong_pwd: '&cNeteisingas slaptazosdis' +unregistered: '&aSekmingai issiregistravote!' +reg_disabled: '&6Registracija yra isjungta' +valid_session: '&aSesijos prisijungimas' +login: '&aSekmingai prisijungete' +vb_nonActiv: '&aJusu vartotojas nera patvirtintas, patikrinkite el.pasta.' +user_regged: '&cVartotojo vardas jau uzregistruotas' +usage_reg: '&eNaudojimas: /register slaptazodis pakartotiSlaptazodi' +max_reg: '&cJus pasiekete maksimalu registraciju skaiciu.' +no_perm: '&cNera leidimo' +error: '&cAtsirado klaida, praneskite adminstratoriui.' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +login_msg: '&ePrasome prisijungti: /login slaptazodis' +reg_msg: '&ePrasome prisiregistruoti: /register slaptazodis pakartotiSlaptazodi' +reg_email_msg: '&cPlease register with "/register "' +usage_unreg: '&ePanaikinti registracija: "/unregister slaptazodis"' +pwd_changed: '&aSlaptazodis pakeistas' +user_unknown: '&cVartotojas neprisiregistraves' +password_error: '&cSlaptazodziai nesutampa' +invalid_session: '&cSesijos laikai nesutampa, prasome palaukti kol secija baigsis.' +reg_only: '&cTik prisiregistravusiem zaidejams: apsilankykite: http://example.com tam kad uzsiregistruoti.' +logged_in: '&cTu aju prisijunges!' +logout: '&aSekmingai atsijungete' +same_nick: '&cKazkas situo vardu jau zaidzia.' +registered: '&aSekmingai prisiregistravote.' +pass_len: '&cJusu slaptazodis buvo per ilgas arba per trumpas.' +reload: '&aNustatymai ir duomenu baze buvo perkrauta.' +timeout: '&cNespejote prisijungti' +usage_changepassword: '&ePanaudojimas: /changepassword senasSlaptazodis naujasSlaptazodis' +name_len: '&cJusu varsdas yra per ilgas arba per trumpas.' +regex: '&cJusu varde yra neledziamu simboliu, leidziami: REG_EX' +add_email: '&ePrasau pridekite savo el.pasta : /email add Email confirmEmail' +recovery_email: '&cPamirsote slaptazodi? Rasykite: /email recovery el.pastas' +usage_captcha: '&cPanaudojimas: /captcha ' +wrong_captcha: '&cNeteisinga Captcha, naudokite : /captcha THE_CAPTCHA' +valid_captcha: '&cJusu captcha Teisinga!' +kick_forvip: '&cA VIP prisijunge i pilna serveri!' +kick_fullserver: '&cServeris yra pilnas, Atsiprasome.' +usage_email_add: '&fUsage: /email add ' +usage_email_change: '&fUsage: /email change ' +usage_email_recovery: '&fUsage: /email recovery ' +new_email_invalid: '[AuthMe] New email invalid!' +old_email_invalid: '[AuthMe] Old email invalid!' +email_invalid: '[AuthMe] Invalid Email' +email_added: '[AuthMe] Email Added !' +email_confirm: '[AuthMe] Confirm your Email !' +email_changed: '[AuthMe] Email Change !' +email_send: '[AuthMe] Recovery Email Send !' +country_banned: 'Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped' diff --git a/src/main/resources/messages/messages_nl.yml b/src/main/resources/messages/messages_nl.yml new file mode 100644 index 0000000..acd42a2 --- /dev/null +++ b/src/main/resources/messages/messages_nl.yml @@ -0,0 +1,56 @@ +unknown_user: Gebruiker is niet gevonden in database +unsafe_spawn: De locatie waar je de vorige keer het spel verlied was gevaarlijk, je bent geteleporteert naar de Spawn +not_logged_in: '&cNiet ingelogt!' +reg_voluntarily: Je kunt je gebruikersnaam registreren met "/register " +usage_log: '&cGebruik: /login ' +wrong_pwd: '&cFout wachtwoord' +unregistered: '&cRegistratie succesvol ongedaan gemaakt!' +reg_disabled: '&cRegistratie is uitgeschakeld' +valid_session: '&cSessie ingelogt' +login: '&cSuccesvol ingelogt!' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +vb_nonActiv: Je accound is nog niet geactiveerd, controleer je mailbox! +user_regged: '&cGebruikersnaam is al geregistreerd' +usage_reg: '&cGebruik: /register ' +max_reg: Je hebt de maximale registraties van jouw account overschreden. +no_perm: '&cGeen toegang!' +error: Error; neem contact op met een ADMIN! +login_msg: '&cLog in met "/login "' +reg_msg: '&cRegistreer met "/register "' +usage_unreg: '&cGebruik: /unregister password' +pwd_changed: '&cWachtwoord aangepast!' +user_unknown: '&cGebruikersnaam niet geregistreerd' +password_error: Wachtwoord incorrect! +invalid_session: Sessie beschadigt, wacht tot de sessie is verlopen en join opnieuw. +reg_only: Alleen voor geregistreerde spelers! Bezoek http://example.com om te registreren +logged_in: '&cJe bent al ingelogt!' +logout: '&cJe bent succesvol uitgelogt' +same_nick: Er is al iemand met jou gebruikersnaam online. +registered: '&cSuccesvol geregistreerd!' +pass_len: Je gekozen wachtwoord voldoet niet aan de minimum of maximum lengte +reload: Configuratie en database is opnieuw opgestard +timeout: Login time-out; het duurde telang voor je je inlogde. +usage_changepassword: 'Gebruik: /changepassword ' +name_len: '&cJouw gebruikersnaam is te kort' +regex: '&cJouw gebruikersnaam bestaat uit illegale tekens. tegestaan chars: REG_EX' +add_email: '&cVoeg uw email toe Alstublieft met: /email add jouw wachtwoord herhaalwachtwoord' +recovery_email: '&cWachtwoord vergeten? gebruik alstublieft /email recovery ' +usage_captcha: '&cGebruik: /captcha ' +wrong_captcha: '&cverkeerde Captcha, Gebruik alstublieft : /captcha THE_CAPTCHA' +valid_captcha: '&cJouw captcha is geldig!' +kick_forvip: '&cA VIP Gebruiker ga naar de volledige server!' +kick_fullserver: '&cDe server is eigenlijk vol, Sorry!' +usage_email_add: '&fGebruik: /email add ' +usage_email_change: '&fGebruik: /email change ' +usage_email_recovery: '&fGebruik: /email recovery ' +new_email_invalid: '[AuthMe] Nieuw email ongeldig!' +old_email_invalid: '[AuthMe] Oud email ongeldig!' +email_invalid: '[AuthMe] ongeldig Email' +email_added: '[AuthMe] Bevestig jouw Email !' +email_confirm: '[AuthMe] Bevestig jouw Email !' +email_changed: '[AuthMe] Email Veranderd !' +email_send: '[AuthMe] Herstel Email Verzonden !' +country_banned: 'Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped' diff --git a/src/main/resources/messages/messages_pl.yml b/src/main/resources/messages/messages_pl.yml new file mode 100644 index 0000000..952fd1c --- /dev/null +++ b/src/main/resources/messages/messages_pl.yml @@ -0,0 +1,57 @@ +logged_in: '&fJestes juz zalogowany!' +not_logged_in: '&4Nie jestes zalogowany!' +reg_disabled: '&4Rejestracja jest wylaczona' +user_regged: '&4Gracz juz jest zarejestrowany' +usage_reg: '&4Uzycie: /register haslo powtorzHaslo' +usage_log: '&cUzycie: /login haslo' +user_unknown: '&fGracz nie jest zarejestrowany' +pwd_changed: '&fHaslo zostalo zmienione!' +reg_only: '&fTylko zarejestrowani uzytkownicy maja do tego dostep!' +valid_session: '&cSesja logowania' +login_msg: '&2Prosze sie zalogowac przy uzyciu &6/login ' +reg_msg: '&2Prosze sie zarejestrowac przy uzyciu &6/register ' +reg_email_msg: '&cStworz prosze konto komenda "/register "' +timeout: '&fUplynal limit czasu zalogowania' +wrong_pwd: '&cNiepoprawne haslo' +logout: '&cPomyslnie wylogowany' +usage_unreg: '&cUzycie: /unregister haslo' +registered: '&aPomyslnie zarejestrowany!' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +unregistered: '&4Pomyslnie odrejestrowany!' +login: '&aHaslo zaakceptowane!' +no_perm: '&4Nie masz uprawnien' +same_nick: '&fTen nick juz gra' +reg_voluntarily: '&fMozesz zarejestrowac swoj nick na serwerze przy uzyciu "/register haslo powtorzHaslo"' +reload: '&fKonfiguracja bazy danych zostala przeladowana' +error: '&fBlad prosimy napisac do aministracji' +unknown_user: '&fUzytkownika nie ma w bazie danych' +unsafe_spawn: '&fTwoje pozycja jest niebezpieczna. Zostaniesz przeniesiony na bezpieczny spawn.' +invalid_session: '&fSesja zakonczona!' +max_reg: '&fPrzekroczyles limit zarejestrowanych kont na serwerze.' +password_error: '&fHaslo niepoprawne!' +pass_len: '&fTwoje haslo jest za krotkie lub za dlugie! Sprobuj ponownie...' +vb_nonActiv: '&fTwoje konto nie zostalo aktywowane! Sprawdz maila.' +usage_changepassword: '&fUzycie: /changepassword starehaslo nowehaslo' +name_len: '&cTwoje konto ma za dluga badz za krotka nazwe' +regex: '&cTwoje konto ma w nazwie niedozwolone znaki. Dozwolone znaki: REG_EX' +add_email: '&cProsze dodac swoj email: /email add twojEmail powtorzEmail' +recovery_email: '&cZapomniales hasla? Prosze uzyj komendy /email recovery ' +usage_captcha: '&cWpisz: /captcha ' +wrong_captcha: '&cZly kod, prosze wpisac: /captcha THE_CAPTCHA' +valid_captcha: '&cTwoj kod jest nieprawidlowy!' +kick_forvip: '&cA Gracz VIP dolaczyl do gry!' +kick_fullserver: '&cSerwer jest teraz zapelniony, przepraszamy!' +usage_email_add: '&fWpisz: /email add ' +usage_email_change: '&fWpisz: /email change ' +usage_email_recovery: '&fWpisz: /email recovery ' +new_email_invalid: '[AuthMe] Nowy email niepoprawny!' +old_email_invalid: '[AuthMe] Stary email niepoprawny!' +email_invalid: '[AuthMe] Nieprawidlowy email' +email_added: '[AuthMe] Email dodany!' +email_confirm: '[AuthMe] Potwierdz swoj email!' +email_changed: '[AuthMe] Email zmieniony!' +email_send: '[AuthMe] Email z odzyskaniem wyslany!' +country_banned: 'Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped' diff --git a/src/main/resources/messages/messages_pt.yml b/src/main/resources/messages/messages_pt.yml new file mode 100644 index 0000000..02ec042 --- /dev/null +++ b/src/main/resources/messages/messages_pt.yml @@ -0,0 +1,58 @@ +unknown_user: '&fUtilizador não existente na base de dados' +unsafe_spawn: '&fA sua localização na saída não é segura, será tele-portado para a Spawn' +not_logged_in: '&cNão autenticado!' +reg_voluntarily: '&fPode registar o seu nickname no servidor com o comando "/register password ConfirmePassword"' +usage_log: '&cUse: /login password' +wrong_pwd: '&cPassword errada!' +unregistered: '&cRegisto eliminado com sucesso!' +reg_disabled: '&cRegito de novos utilizadores desactivado' +valid_session: '&cSessão válida' +login: '&cAutenticado com sucesso!' +vb_nonActiv: '&fA sua conta não foi ainda activada, verifique o seu email onde irá receber indicações para activação de conta. ' +user_regged: '&cUtilizador já registado' +usage_reg: '&cUse: /register seu@email.com seu@email.com' +max_reg: '&cAtingiu o numero máximo de registos permitidos' +no_perm: '&cSem Permissões' +error: '&fOcorreu um erro; Por favor contacte um admin' +login_msg: '&cIdentifique-se com "/login password"' +reg_msg: '&cPor favor registe-se com "/register password confirmePassword"' +reg_email_msg: '&ePor favor registe-se com "/register "' +usage_unreg: '&cUse: /unregister password' +pwd_changed: '&cPassword alterada!' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +user_unknown: '&cUsername não registado' +password_error: '&fAs passwords não coincidem' +invalid_session: '&fDados de sessão não correspondem. Por favor aguarde o fim da sessão' +reg_only: '&fApenas jogadores registados! Visite http://example.com para se registar' +logged_in: '&cJá se encontra autenticado!' +logout: '&cSaida com sucesso' +same_nick: '&fO mesmo nickname já se encontra a jogar no servidor' +registered: '&cRegistado com sucesso!' +pass_len: '&fPassword demasiado curta' +reload: '&fConfiguração e base de dados foram recarregadas' +timeout: '&fExcedeu o tempo para autenticação' +usage_changepassword: '&fUse: /changepassword passwordAntiga passwordNova' +name_len: '&cO seu nick é demasiado curto ou muito longo.' +regex: '&cO seu nickname contém caracteres não permitidos. Permitido: REG_EX' +add_email: '&cPor favor adicione o seu email com : /email add seuEmail confirmarSeuEmail' +recovery_email: '&cPerdeu a sua password? Para a recuperar escreva /email recovery ' +usage_captcha: '&cVocê precisa digitar um captcha, escreva: /captcha ' +wrong_captcha: '&cCaptcha errado, por favor escreva: /captcha THE_CAPTCHA' +valid_captcha: '&cO seu captcha é válido!' +kick_forvip: '&cUm jogador VIP entrou no servidor cheio!' +kick_fullserver: '&cO servidor está actualmente cheio, lamentamos!' +usage_email_add: '&fUse: /email add ' +usage_email_change: '&fUse: /email change ' +usage_email_recovery: '&fUse: /email recovery ' +email_add: '/email add ' +new_email_invalid: 'Novo email inválido!' +old_email_invalid: 'Email antigo inválido!' +email_invalid: 'Email inválido!' +email_added: 'Email adicionado com sucesso!' +email_confirm: 'Confirme o seu email!' +email_changed: 'Email alterado com sucesso!' +email_send: 'Nova palavra-passe enviada para o seu email!' +country_banned: 'O seu país está banido deste servidor' +antibot_auto_enabled: '[AuthMe] AntiBotMod activado automaticamente devido a um aumento anormal de tentativas de ligação!' +antibot_auto_disabled: '[AuthMe] AntiBotMod desactivado automaticamente após %m minutos, esperamos que a invasão tenha parado' diff --git a/src/main/resources/messages/messages_ru.yml b/src/main/resources/messages/messages_ru.yml new file mode 100644 index 0000000..ddb84cd --- /dev/null +++ b/src/main/resources/messages/messages_ru.yml @@ -0,0 +1,57 @@ +unknown_user: '&fПользователь не найден в Базе Данных' +unsafe_spawn: '&eВаше расположение перед выходом было опасным - вы перенесены на спавн' +not_logged_in: '&cВы еще не вошли!' +reg_voluntarily: '&aЧтобы зарегистрироваться введите: &5/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +usage_log: '&eСинтаксис: &d/l ПАРОЛЬ &eили &d/login ПАРОЛЬ' +wrong_pwd: '&4Неправильный пароль!' +unregistered: '&6Вы успешно удалили свой аккаунт!' +reg_disabled: '&4Регистрация отключена' +valid_session: '&aСессия открыта' +login: '&2Вы успешно вошли!' +vb_nonActiv: '&6Ваш аккаунт еще не активирован! Проверьте вашу почту!' +user_regged: '&4Такой игрок уже зарегистрирован' +usage_reg: '&4Использование: &5/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +max_reg: '&4Вы превысили макс количество регистраций на ваш IP' +no_perm: '&4Недостаточно прав' +error: '&4Произошла ошибка. Свяжитесь с администратором' +login_msg: '&4Авторизация: &5/l ПАРОЛЬ' +reg_msg: '&4Регистрация: &5/reg ПАРОЛЬ ПОВТОР_ПАРОЛЯ' +password_error_nick: '&fВы не можете использовать ваш ник в роли пароля' +password_error_unsafe: '&fВы не можете использовать небезопасный пароль' +reg_email_msg: '&4Регистрация: &5/reg EMAIL ПОВТОР_EMAIL' +usage_unreg: '&4Использование: &5/unregister ПАРОЛЬ' +pwd_changed: '&2Пароль изменен!' +user_unknown: '&4Такой игрок не зарегистрирован' +password_error: '&4Пароль не совпадает' +invalid_session: '&4Сессия некорректна. Дождитесь, пока она закончится' +reg_only: '&4Только для зарегистрированных! Посетите http://сайт_сервера.com/register/ для регистрации' +logged_in: '&4Вы уже авторизированы!' +logout: '&2Вы успешно вышли' +same_nick: '&4Такой игрок уже играет на сервере' +registered: '&2Успешная регистрация!' +pass_len: '&4Твой пароль либо слишком длинный, либо слишком короткий' +reload: '&6Конфигурация и база данных перезагружены' +timeout: '&4Время для авторизации истекло' +usage_changepassword: '&4Использование: &5/changepassword СТАРЫЙ_ПАРОЛЬ НОВЫЙ_ПАРОЛЬ' +name_len: '&4Ваш логин слишком длинный или слишком короткий' +regex: '&4Ваш логин содержит запрещенные символы. Разрешенные символы: REG_EX' +add_email: '&4Добавьте свой email: &5/email add ВАШ_EMAIL ВАШ_EMAIL' +recovery_email: '&4Забыли пароль? Используйте &5/email recovery ВАШ_EMAIL' +usage_captcha: '&4Вы должны ввести код, используйте: &5/captcha ' +wrong_captcha: '&4Неверный код, используйте: &5/captcha THE_CAPTCHA' +valid_captcha: '&2Вы успешно ввели код!' +kick_forvip: '&6VIP игрок зашел на переполненный сервер!' +kick_fullserver: '&4Сервер переполнен!' +usage_email_add: '&4Использование: &5/email add ВАШ_EMAIL ПОВТОР_EMAIL' +usage_email_change: '&4Использование: &5/email change СТАРЫЙ_EMAIL НОВЫЙ_EMAIL' +usage_email_recovery: '&4Использование: /email recovery EMAIL' +new_email_invalid: '[AuthMe] Недействительный новый email!' +old_email_invalid: '[AuthMe] Недействительный старый email!' +email_invalid: '[AuthMe] Недействительный email' +email_added: '[AuthMe] Email добавлен!' +email_confirm: '[AuthMe] Подтвердите ваш Email!' +email_changed: '[AuthMe] Email изменен!' +email_send: '[AuthMe] Письмо с инструкциями для восстановления было отправлено на ваш Email!' +country_banned: 'Вход с IP-адресов вашей страны воспрещен на этом сервере' +antibot_auto_enabled: '[AuthMe] AntiBot-режим автоматически включен из-за большого количества входов!' +antibot_auto_disabled: '[AuthMe] AntiBot-режим автоматичски отключен после %m мин. Надеюсь атака закончилась' diff --git a/src/main/resources/messages/messages_sk.yml b/src/main/resources/messages/messages_sk.yml new file mode 100644 index 0000000..010533f --- /dev/null +++ b/src/main/resources/messages/messages_sk.yml @@ -0,0 +1,61 @@ +# Slovak translate by Judzi # +# www.judzi.eu | judzi@cs-gaming.eu # +# 02.02.2013 - 4:35 AM - Thanks for use # + +logged_in: '&cAktuálne si uz prihláseny!' +not_logged_in: '&cNie si este prihláseny!' +reg_disabled: '&cRegistrácia nie je povolená' +user_regged: '&cZadané meno je uz zaregistrované' +usage_reg: '&cPríkaz: /register heslo zopakujHeslo' +usage_log: '&cPríkaz: /login heslo' +user_unknown: '&cZadané meno nie je zaregistrované!' +pwd_changed: '&cHeslo zmenené!' +reg_only: '&fVstup iba pre registrovanych! Navstiv http://example.com pre registráciu' +valid_session: '&cZapamätané prihlásenie' +login_msg: '&cPrihlás sa príkazom "/login heslo"' +reg_msg: '&cZaregistruj sa príkazom "/register heslo zopakujHeslo"' +reg_email_msg: '&cPlease register with "/register "' +timeout: '&fVyprsal cas na prihlásenie' +wrong_pwd: '&cZadal si zlé heslo' +password_error_nick: '&fYou can''t use your name as password' +password_error_unsafe: '&fYou can''t use unsafe passwords' +logout: '&cBol si úspesne odhláseny' +usage_unreg: '&cPríkaz: /unregister heslo' +registered: '&cBol si úspesne zaregistrovany' +unregistered: '&cUcet bol vymazany!' +login: '&cBol si úspesne prihláseny!' +no_perm: '&cZiadne' +same_nick: '&fHrác s tymto nickom uz hrá!' +reg_voluntarily: '&fZaregistruj sa pomocou príkazu "/register heslo zopakujHeslo"' +reload: '&fKonfigurácia a databáza bola obnovená' +error: '&fNastala chyba; Kontaktujte administrátora' +unknown_user: '&fHrac nie je v databázi' +unsafe_spawn: '&fTvoj pozícia bol nebezpecná, teleportujem hraca na spawn' +invalid_session: '&fZapamätane casove data nie su doveryhodne. Cakaj na ukoncenie spojenia' +max_reg: '&fDosiahol si maximum registrovanych uctov.' +password_error: '&fHeslá sa nezhodujú' +pass_len: '&fHeslo je velmi kratke alebo dlhe' +vb_nonActiv: '&fUcet nie je aktivny. Prezri si svoj e-mail!' +usage_changepassword: '&fPríkaz: /changepassword stareHeslo noveHeslo' +name_len: '&cTvoje meno je velmi krátke alebo dlhé' +regex: '&cTvoje meno obsahuje zakázané znaky. Povolené znaky: REG_EX' +add_email: '&cPridaj svoj e-mail príkazom "/email add email zopakujEmail"' +recovery_email: '&cZabudol si heslo? Pouzi príkaz /email recovery ' +usage_captcha: '&cUsage: /captcha ' +wrong_captcha: '&cWrong Captcha, please use : /captcha THE_CAPTCHA' +valid_captcha: '&cYour captcha is valid !' +kick_forvip: '&cA VIP Player join the full server!' +kick_fullserver: '&cThe server is actually full, Sorry!' +usage_email_add: '&fUsage: /email add ' +usage_email_change: '&fUsage: /email change ' +usage_email_recovery: '&fUsage: /email recovery ' +new_email_invalid: '[AuthMe] New email invalid!' +old_email_invalid: '[AuthMe] Old email invalid!' +email_invalid: '[AuthMe] Invalid Email' +email_added: '[AuthMe] Email Added !' +email_confirm: '[AuthMe] Confirm your Email !' +email_changed: '[AuthMe] Email Change !' +email_send: '[AuthMe] Recovery Email Send !' +country_banned: 'Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod automatically enabled due to massive connections!' +antibot_auto_disabled: '[AuthMe] AntiBotMod automatically disabled after %m Minutes, hope invasion stopped' diff --git a/src/main/resources/messages/messages_tr.yml b/src/main/resources/messages/messages_tr.yml new file mode 100644 index 0000000..7f00039 --- /dev/null +++ b/src/main/resources/messages/messages_tr.yml @@ -0,0 +1,58 @@ +unknown_user: '&fKullanici veritabanina ekli degil' +unsafe_spawn: '&fDogdugunuz konum guvenli degildi, lobiye isinlaniyorsunuz...' +not_logged_in: '&cGiris Yapmadin!' +reg_voluntarily: '&fKullanici adinla kayit olabilirsin! Komut: "/register sifren sifrentekrar"' +usage_log: '&cKullanimi: /login sifren' +wrong_pwd: '&cYanlis sifre' +unregistered: '&cSunucudan kaydiniz basariyla silindi!' +reg_disabled: '&cKayit deaktif' +valid_session: '&cOturum Acma' +login: '&cBasarili giris!' +vb_nonActiv: '&fHesabin aktiflestirilmedi! Emailini kontrol et' +user_regged: '&cKullanici zaten oyunda' +usage_reg: '&cKullanimi: /register sifre sifretekrar' +max_reg: '&fMaximim kayit limitini astin!' +no_perm: '&cYetkin yok' +error: '&fBir hata olustu; Lutfen adminle iletisime gec' +login_msg: '&cGiris Yapin : "/login sifre"' +reg_msg: '&cLutfen kaydolmak icin : "/register sifre sifretekrar"' +reg_email_msg: '&cLutfen Kaydolmak icin : "/register "' +usage_unreg: '&cKullanimi: /unregister sifren' +pwd_changed: '&cSifreniz degisti!' +user_unknown: '&cBu kullaniciyla kaydolunmamis!' +password_error: '&fSifren eslesmiyor' +password_error_nick: '&fYou can''t use your name as password, please choose another one' +password_error_unsafe: '&fThe chosen password is not safe, please choose another one' +invalid_session: '&fOturum veritabanlari uyusmuyor lutfen sonunu bekleyin' +reg_only: '&fSadece kayitli uyeler girebilir ! Kayit olmak icin www.orneksite.com adresini ziyaret ediniz !' +logged_in: '&cZaten Giris Yapilmis!' +logout: '&cBasarili cikis' +same_nick: '&fAyni kullanici oyunda' +registered: '&cBasarili kayit!' +pass_len: '&fSifren cok uzun ya da kisa olmamali ' +reload: '&fKonfigurasyon dosyasi ve veritabani yüklendi' +timeout: '&fZaman Asimi' +usage_changepassword: '&fkullanimi: /changepassword eskisifre yenisifre' +name_len: '&cKullanici adin cok kisa ya da cok uzun' +regex: '&cKullanici adin ozel karakterler iceriyor. Uygun karakterler: REG_EX' +add_email: '&cLutfen emailini ekle : /email add ' +recovery_email: '&cSifreni mi unuttun? Degistirmek icin : /email recovery ' +usage_captcha: '&cBir captcha yazman lazim , yazmak icin: /captcha ' +wrong_captcha: '&cYanlis Captcha, kullanmak icin : /captcha THE_CAPTCHA' +valid_captcha: '&cCaptcha gecerli !' +kick_forvip: '&cSenin yerine bir VIP kullanıcı girdi!' +kick_fullserver: '&cServer suanda dolu gozukuyor, Uzgunum!' +usage_email_add: '&fKullanimi: /email add ' +usage_email_change: '&fKullanimi: /email change ' +usage_email_recovery: '&fKullanimi: /email recovery ' +new_email_invalid: '[AuthMe] Yeni eposta gecersiz!' +old_email_invalid: '[AuthMe] Eski eposta gecersiz!' +email_invalid: '[AuthMe] Gecersiz Eposta' +email_added: '[AuthMe] Eposta Eklendi !' +email_confirm: '[AuthMe] Epostani Dogrula !' +email_changed: '[AuthMe] Eposta Degistirildi !' +email_send: '[AuthMe] Kurtarma postasi gonderildi !' +email_exists: '[AuthMe] An email already exists on your account. You can change it using the command below' +country_banned: 'Ulken bu serverdan banlandi !' +antibot_auto_enabled: '[AuthMe] AntiBotMode otomatik olarak etkinlestirildi!' +antibot_auto_disabled: '[AuthMe] AntiBotMode %m dakika sonra otomatik olarak isgal yuzundan devredisi birakildi' diff --git a/src/main/resources/messages/messages_uk.yml b/src/main/resources/messages/messages_uk.yml new file mode 100644 index 0000000..6b132d8 --- /dev/null +++ b/src/main/resources/messages/messages_uk.yml @@ -0,0 +1,57 @@ +unknown_user: '&fКористувача немає в базі даних' +unsafe_spawn: '&fМісце вашого виходу було небезпечне тому ми телепортували вас на спавн' +not_logged_in: '&cВи ще не ввійшли!' +reg_voluntarily: '&eЩоб зарєєструватися введіть команду &d"/reg Пароль Повтор_Пароля"' +usage_log: '&cВикористовуйте: &a/login Пароль &cабо &a/l Пароль' +wrong_pwd: '&cНевірний пароль' +unregistered: '&cВи успішно видалили свій акаунт!' +reg_disabled: '&cРеєстрація виключена' +valid_session: '&cСесія відкрита' +login: '&2Успішна авторизація!' +vb_nonActiv: '&fВаш акаунт не активований. Перевірте свою електронну адресу!' +user_regged: '&cТакий користувач вже зареєстрований' +usage_reg: '&cВикористовуйте: /reg Пароль Повтор_Пароля' +max_reg: '&fВи перевищили максимальне число реєстрацій на ваш IP' +no_perm: '&cУ Вас недостатньо прав' +error: '&fЩось пішло не так; Будь ласка зв`яжіться з адміністратором' +login_msg: '&cДля авторизації введіть "/login Пароль"' +reg_msg: '&cДля реєстрації введіть "/reg Пароль Повтор_Пароля"' +password_error_nick: '&fВи не можете використати ваш Нікнейм у якості паролю' +password_error_unsafe: '&fВи не можете використувати ненадійний пароль' +reg_email_msg: '&cДля реєстрації введіть "/reg Email Email"' +usage_unreg: '&cВикористовуйте: /unregister Пароль' +pwd_changed: '&cПароль змінено!' +user_unknown: '&cТакий користувач не зарєєстрований' +password_error: '&fПаролі не співпадають' +invalid_session: '&fСесія некоректна. Будь ласка зачекайте коли вона закінчиться' +reg_only: '&Вхід доступний лише зареєстрованим користувачам. Зареєструватися можна за адресою &9&nhttp://сайт_серверу.com&r' +logged_in: '&2Ви уже ввійшли!' +logout: '&cВи успішно вийшли' +same_nick: '&fГравець з вашим нікнеймом вже грає на сервері' +registered: '&cВи успішно зареєстровані!' +pass_len: '&fВаш пароль занадто довгий, або занадто короткий' +reload: '&fКонфiгурацiя i база даних успiшно перезавнтажені.' +timeout: '&fЧас для входу вийшов' +usage_changepassword: '&fВикористовуйте: /changepassword СтарийПароль НовийПароль' +name_len: '&cВаш нікнейм занадто довгий, або занадто короткий' +regex: '&cВаш нікнейм містить заборонені символи. Доступні символи: REG_EX' +add_email: '&cБудь ласка додайте свою електронну скриньку: /email add ВашEmail ВашEmail' +recovery_email: '&cЗабули пароль? Введіть /email recovery ВашПароль' +usage_captcha: '&cБудь ласка введіть капчу: /captcha ' +wrong_captcha: '&cНевірне значення капчи: /captcha THE_CAPTCHA' +valid_captcha: '&cКапча введена вірно!' +kick_forvip: '&cVIP зайшов на переповнений сервер!' +kick_fullserver: '&cНажаль, сервер переповнений!' +usage_email_add: '&fВикористовуйте: /email add ВашEmail ВашEmail' +usage_email_change: '&fВикористовуйте: /email change СтарийEmail НовийEmail' +usage_email_recovery: '&fВикористовуйте: /email recovery Email' +new_email_invalid: '[AuthMe] Новий Email недійсний!' +old_email_invalid: '[AuthMe] Старий Email недійсний!' +email_invalid: '[AuthMe] Невірний Email' +email_added: '[AuthMe] &2Email додано!' +email_confirm: '[AuthMe] Підтвердіть ваш Email!' +email_changed: '[AuthMe] &2Email змінено!' +email_send: '[AuthMe] Лист для відновлення надіслано на ваш Email!' +country_banned: 'Сервер не доступний для вашої країни | Your country is banned from this server' +antibot_auto_enabled: '[AuthMe] AntiBotMod автоматично увімкнений (забагато одначасних з`єднань)!' +antibot_auto_disabled: '[AuthMe] AntiBotMod автоматично вимкнувся, сподіваємось атака зупинена' diff --git a/src/main/resources/messages/messages_vn.yml b/src/main/resources/messages/messages_vn.yml new file mode 100644 index 0000000..7acb498 --- /dev/null +++ b/src/main/resources/messages/messages_vn.yml @@ -0,0 +1,55 @@ +unknown_user: '&fNgười chơi không tồn tại trong cơ sở dữ liệu' +unsafe_spawn: '&fNơi thoát server của bạn không an toàn, đang dịch chuyển bạn tới điểm spawn của server' +not_logged_in: '&cChưa đăng nhập!' +reg_voluntarily: '&fBạn có thể đăng kí tài khoản với lệnh "/register mật-khẩu nhập-lại-mật-khẩu"' +usage_log: '&eSử dụng: /login password' +wrong_pwd: '&cSai mật khẩu' +unregistered: '&cHuỷ đăng kí thành công!' +reg_disabled: '&cHệ thống đăng kí đã bị vô hiệu' +valid_session: '&cPhiên đăng nhập còn tồn tại, bạn không cần nhập mật khẩu' +login: '&cĐăng nhập thành công!' +vb_nonActiv: '&fTài khoản của bạn chưa được kích hoạt, kiểm tra email!' +user_regged: '&cTên đăng nhập này đã được đăng kí' +usage_reg: '&eSử dụng: /register mật-khẩu nhập-lại-mật-khẩu' +max_reg: '&fSố lượng tài khoản ở IP của bạn trong server này đã quá giới hạn cho phép' +no_perm: '&cKhông có quyền' +error: '&fCó lỗi xảy ra; Báo lại cho người điều hành server' +login_msg: '&cĐăng nhập với lệnh "/login mật-khẩu"' +reg_msg: '&cĐăng kí tài khoản với lệnh "/register mật-khẩu nhập-lại-mật-khẩu"' +reg_email_msg: '&cĐăng kí email cho tài khoản với lệnh "/register "' +usage_unreg: '&eSử dụng: /unregister mật-khẩu' +pwd_changed: '&cĐã đổi mật khẩu!' +user_unknown: '&cTài khoản này chưa được đăng kí' +password_error: '&fMật khẩu không khớp' +unvalid_session: '&fPhiên đăng nhập không hồi đáp, vui lòng chờ phiên đăng nhập kết thúc' +reg_only: '&fChỉ cho phép người đã đăng kí! Hãy vào trang http://web-của.bạn/ để đăng kí' +logged_in: '&cĐã đăng nhập!' +logout: '&cThoát đăng nhập thành công' +same_nick: '&fTài khoản đang được người khác sử dụng trong server' +registered: '&cĐăng kí thành công!' +pass_len: '&fMật khẩu của bạn quá ngắn hoặc quá dài' +reload: '&fThiết lập và dữ liệu đã được nạp lại' +timeout: '&fQuá thời gian đăng nhập' +usage_changepassword: '&eSử dụng: /changepassword mật-khẩu-cũ mật-khẩu-mới' +name_len: '&cTên đăng nhập của bạn quá ngắn hoặc quá dài' +regex: '&cTên đăng nhập của bạn có chứa kí tự đặc biệt không được cho phép. Các kí tự hợp lệ: REG_EX' +add_email: '&cVui lòng thêm địa chỉ email cho tài khoản với lệnh: /email add email-của-bạn nhập-lại-email-của-bạn' +recovery_email: '&cQuên mật khẩu? Hãy dùng lệnh /email recovery ' +usage_captcha: '&cBạn cần nhập mã xác nhận: /captcha ' +wrong_captcha: '&cSai mã xác nhận, nhập lại: /captcha ' +valid_captcha: '&aMã xác nhận hợp lệ!' +kick_forvip: '&cNgười chơi VIP đã vào server hiện đang full!' +kick_fullserver: '&cXin lỗi, hiện tại server không còn trống slot để bạn có thể vào!' +usage_email_add: '&eSử dụng: /email add ' +usage_email_change: '&eSử dụng: /email change ' +usage_email_recovery: '&eSử dụng: /email recovery ' +new_email_invalid: '[AuthMe] Địa chỉ email mới không hợp lệ!' +old_email_invalid: '[AuthMe] Địa chỉ email cũ không hợp lệ!' +email_invalid: '[AuthMe] Sai địa chỉ email' +email_added: '[AuthMe] Đã thêm địa chỉ email !' +email_confirm: '[AuthMe] Xác nhận email !' +email_changed: '[AuthMe] Đã thay đổi email !' +email_send: '[AuthMe] Đã gửi email khôi phục mật khẩu tới bạn !' +country_banned: 'Rất tiếc, quốc gia của bạn không được phép gia nhập server' +antibot_auto_enabled: '[AuthMe] AntiBot đã được kích hoạt vì lượng người chơi kết nối vượt quá giới hạn!' +antibot_auto_disabled: '[AuthMe] AntiBot tự huỷ kích hoạt sau %m phút, hi vọng lượng kết nối sẽ giảm bớt' \ No newline at end of file diff --git a/src/main/resources/messages/messages_zhcn.yml b/src/main/resources/messages/messages_zhcn.yml new file mode 100644 index 0000000..2d28081 Binary files /dev/null and b/src/main/resources/messages/messages_zhcn.yml differ diff --git a/src/main/resources/messages/messages_zhhk.yml b/src/main/resources/messages/messages_zhhk.yml new file mode 100644 index 0000000..6cd67c6 --- /dev/null +++ b/src/main/resources/messages/messages_zhhk.yml @@ -0,0 +1,60 @@ +# Translator: lifehome # +# Last modif: 1443428389 UTC # +# -------------------------------------------- # +unknown_user: '&8[&6用戶系統&8] &f用戶資料並不存在。' +unsafe_spawn: '&8[&6用戶系統&8] &f你的登出位置不安全,現在將傳送你到重生點。' +not_logged_in: '&8[&6用戶系統&8] &c你還沒有登入 !' +reg_voluntarily: '&8[&6用戶系統&8] &f你可以使用這個指令來註冊: 《 /register <密碼> <重覆密碼> 》' +usage_log: '&8[&6用戶系統&8] &f用法: 《 /login <密碼> 》' +wrong_pwd: '&8[&6用戶系統&8] &c你輸入了錯誤的密碼。' +unregistered: '&8[&6用戶系統&8] &c你已成功刪除會員註冊記錄。' +reg_disabled: '&8[&6用戶系統&8] &c本伺服器已停止新玩家註冊。' +valid_session: '&8[&6用戶系統&8] &b嗨 ! 歡迎回來喔~' +login: '&8[&6用戶系統&8] &c你成功登入了。' +password_error_nick: '&8[&6用戶系統&8] &c這個密碼太不安全了!' +password_error_unsafe: '&8[&6用戶系統&8] &c這個密碼太不安全了!' +vb_nonActiv: '&8[&6用戶系統&8] &f你的帳戶還沒有經過電郵驗證 !' +user_regged: '&8[&6用戶系統&8] &c此用戶名已經註冊過了。' +usage_reg: '&8[&6用戶系統&8] &f用法: 《 /register <密碼> <重覆密碼> 》' +max_reg: '&8[&6用戶系統&8] &f你的IP地址已達到註冊數上限。' +no_perm: '&8[&6用戶系統&8] &b你可以到 CraftingHK 玩家百科中查看說明文件。' +error: '&8[&6用戶系統&8] &f發生錯誤,請與管理員聯絡。' +login_msg: '&8[&6用戶系統&8] &c請使用這個指令來登入: 《 /login <密碼> 》' +reg_msg: '&8[&6用戶系統&8] &c請使用這個指令來註冊: 《 /register <密碼> <重覆密碼> 》' +reg_email_msg: '&8[&6用戶系統&8] &c請使用這個指令來註冊: 《 /register <電郵> <重覆電郵> 》' +usage_unreg: '&8[&6用戶系統&8] &f用法: 《 /unregister <密碼> 》' +pwd_changed: '&8[&6用戶系統&8] &c你成功更換了你的密碼 !' +user_unknown: '&8[&6用戶系統&8] &c此用戶名沒有已登記資料。' +password_error: '&8[&6用戶系統&8] &f密碼不符合。' +invalid_session: '&8[&6用戶系統&8] &f登入階段資料已損壞,請等待登入階段結束。' +reg_only: '&8[&6用戶系統&8] &f限已註冊會員,請先到 https://crafting.hk/ 註冊。' +logged_in: '&8[&6用戶系統&8] &c你已經登入過了。' +logout: '&8[&6用戶系統&8] &b你成功登出了。' +same_nick: '&8[&6用戶系統&8] &f同名玩家已在遊玩。' +registered: '&8[&6用戶系統&8] &b你成功註冊了。' +pass_len: '&8[&6用戶系統&8] &f你的密碼並不符合規定長度。' +reload: '&8[&6用戶系統&8] &b登入系統設定及資料庫重新載入完畢。' +timeout: '&8[&6用戶系統&8] &f登入逾時。' +usage_changepassword: '&8[&6用戶系統&8] &f用法: 《 /changepassword <舊密碼> <新密碼> 》' +name_len: '&8[&6用戶系統&8] &c你的用戶名不符合規定長度。' +regex: '&8[&6用戶系統&8] &c用戶名稱錯誤! 登入系統只接受以下字符: REG_EX' +add_email: '&8[&6用戶系統&8] &b請為你的帳戶立即添加電郵地址: 《 /email add <電郵地址> <重覆電郵地址> 》' +recovery_email: '&8[&6用戶系統&8] &c忘記密碼 ? 請使用這個指令來更新密碼: 《 /email recovery <電郵地址> 》' +usage_captcha: '&8[&6用戶系統&8] &f用法: 《 /captcha <驗證碼> 》' +wrong_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼無效,請使用 《 /captcha <驗證碼> 》 再次輸入。' +valid_captcha: '&8[&6用戶系統&8] &c你所輸入的驗證碼無效 !' +kick_forvip: '&c因為有VIP玩家登入了伺服器。' +kick_fullserver: '&c抱歉! 因為伺服器滿人了,所以你目前未能登入伺服器。' +usage_email_add: '&8[&6用戶系統&8] &f用法: 《 /email add <電郵> <重覆電郵> 》' +usage_email_change: '&8[&6用戶系統&8] &f用法: 《 /email change <舊電郵> <新電郵> 》' +usage_email_recovery: '&8[&6用戶系統&8] &f用法: 《 /email recovery <電郵> 》' +new_email_invalid: '&8[&6用戶系統&8] 你所填寫的新電郵地址並不正確。' +old_email_invalid: '&8[&6用戶系統&8] 你所填寫的舊電郵地址並不正確。' +email_invalid: '&8[&6用戶系統&8] 你所填寫的電郵地址並不正確。' +email_added: '&8[&6用戶系統&8] 已新增你的電郵地址。' +email_confirm: '&8[&6用戶系統&8] 請重覆輸入你的電郵地址。' +email_changed: '&8[&6用戶系統&8] 你的電郵地址已更改。' +email_send: '&8[&6用戶系統&8] 忘記密碼信件已寄出,請查收。' +country_banned: '&8[&6用戶系統&8] 本伺服器已停止對你的國家提供遊戲服務。' +antibot_auto_enabled: '&8[&6用戶系統&8] 防止機械人程序已因應現時大量不尋常連線而啟用。' +antibot_auto_disabled: '&8[&6用戶系統&8] 不正常連接數已減少,防止機械人程序將於 %m 分鐘後停止。' diff --git a/src/main/resources/messages/messages_zhtw.yml b/src/main/resources/messages/messages_zhtw.yml new file mode 100644 index 0000000..34c2131 --- /dev/null +++ b/src/main/resources/messages/messages_zhtw.yml @@ -0,0 +1,61 @@ +# Translator: MineWolf50 +# Last Time Edit : 2015 / 7 / 14 , A.M.10:14 +# = = = = = = = = = = = = = = = = = = = = = = = # +unknown_user: "&b【AuthMe】&6沒有在資料庫內找到該玩家。" +unsafe_spawn: '&b【AuthMe】&6你登出的地點不安全,已傳送你到安全的地點。' +not_logged_in: '&b【AuthMe】&6你還沒有登入!' +reg_voluntarily: '&b【AuthMe】&6使用 &c"/register <密碼> <確認密碼>" &6來註冊你的暱稱' +usage_log: '&b【AuthMe】&6用法: &c"/login <密碼>"' +wrong_pwd: '&b【AuthMe】&6密碼錯誤!' +unregistered: '&b【AuthMe】&6你已經成功取消註冊。' +reg_disabled: '&b【AuthMe】&6已關閉註冊功能' +password_error_nick: '&b【AuthMe】&6你不可以用你的 ID ( 名稱 ) 來當作密碼 !' +password_error_unsafe: '&b【AuthMe】&6你不可以使用這個不安全的密碼' +valid_session: '&b【AuthMe】&6你已經成功登入!' +login: '&b【AuthMe】&6密碼正確,你已成功登入!' +vb_nonActiv: '&b【AuthMe】&6你的帳號還沒有經過驗證! 檢查看看你的電子信箱 (Email) 吧!' +user_regged: '&b【AuthMe】&6這個帳號已經被註冊過了!' +usage_reg: '&b【AuthMe】&6用法: &c"/register <密碼> <確認密碼>"' +max_reg: '&b【AuthMe】&6你的 IP 位置所註冊的帳號數量已經達到最大。' +no_perm: '&b【AuthMe】&6你沒有使用該指令的權限。' +error: '&b【AuthMe】&6發生錯誤,請聯繫管理員' +login_msg: '&b【AuthMe】&6請使用 &c"/login <密碼>" &6來登入。' +reg_msg: '&b【AuthMe】&6請使用 "&c/register <密碼> <確認密碼>" 來註冊。' +reg_email_msg: '&b【AuthMe】&6請使用 &c"/register <重複Email>" 來註冊' +usage_unreg: '&b【AuthMe】&6用法: &c"/unregister <密碼>"' +pwd_changed: '&b【AuthMe】&6密碼變更成功!' +user_unknown: '&b【AuthMe】&6這個帳號還沒有註冊過' +password_error: '&b【AuthMe】&6兩次輸入的密碼不一致!' +invalid_session: '&b【AuthMe】&6憑證日期不相符!' +reg_only: '&b【AuthMe】&6請到下列網站 :「 http://example.com 」 進行註冊' +logged_in: '&b【AuthMe】&6你已經登入了!' +logout: '&b【AuthMe】&6你已成功登出' +same_nick: '&b【AuthMe】&6有同樣帳號的玩家在線上!' +registered: '&b【AuthMe】&6你已成功註冊' +pass_len: '&b【AuthMe】&6你的密碼 超過最大字數 / 小於最小字數' +reload: '&b【AuthMe】&6已重新讀取設定檔及資料庫' +timeout: '&b【AuthMe】&6超過登入時間,請稍後再試一次' +usage_changepassword: '&b【AuthMe】&6用法: &c"/changepassword <舊密碼> <新密碼>"' +name_len: '&b【AuthMe】&6你的暱稱 太長 / 太短 了!' +regex: '&b【AuthMe】&6暱稱裡包含不能使用的字符' +add_email: '&b【AuthMe】&6請使用 &c"/email add <你的Email> <再次輸入你的Email>" &6來添加 Email' +recovery_email: '&b【AuthMe】&6忘記密碼了嗎? 使用 &c"/email recovery <你的Email>"' +usage_captcha: '&b【AuthMe】&6請用 &c"/captcha " &6來輸入你的驗證碼' +wrong_captcha: '&b【AuthMe】&6錯誤的驗證碼' +valid_captcha: '&b【AuthMe】&6驗證碼無效!' +kick_forvip: '&b【AuthMe】&6你已經被請出。&c原因 : 有 VIP 玩家登入伺服器' +kick_fullserver: '&b【AuthMe】&6伺服器已經滿了,請等等再試一次' +usage_email_add: '&b【AuthMe】&6用法: &c"/email add <你的Email> <重複Email>"' +usage_email_change: '&b【AuthMe】&6用法: &c"/email change <舊的Email> <新的Email>"' +usage_email_recovery: '&b【AuthMe】&6用法: &c"/email recovery <你的Email>"' +new_email_invalid: '&b【AuthMe】&6新的Email無效!' +old_email_invalid: '&b【AuthMe】&6舊的Email無效!' +email_invalid: '&b【AuthMe】&6無效的Email!' +email_added: '&b【AuthMe】&6已添加Email!' +email_confirm: '&b【AuthMe】&6請驗證你的Email!' +email_changed: '&b【AuthMe】&6Email已變更!' +email_send: '&b【AuthMe】&6已經送出重設密碼要求至你的Email , 請查收。' +email_exists: '&b【AuthMe】&6這個帳戶已經有設定電子郵件了' +country_banned: '&b【AuthMe】&6你所在的地區無法進入此伺服器' +antibot_auto_enabled: '&b【AuthMe】&6AntiBotMod已自動啟用!' +antibot_auto_disabled: '&b【AuthMe】&6AntiBotMod將會於 &c%m &6分鐘後自動關閉' \ No newline at end of file diff --git a/src/main/resources/otheraccounts.yml b/src/main/resources/otheraccounts.yml new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/players.yml b/src/main/resources/players.yml new file mode 100644 index 0000000..cf746f5 --- /dev/null +++ b/src/main/resources/players.yml @@ -0,0 +1 @@ +players: [] \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 0000000..276773c --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,169 @@ +name: AuthMe +author: Xephi59 +website: http://dev.bukkit.org/bukkit-plugins/authme-reloaded/ +description: AuthMe prevents people, which aren't logged in, from doing stuff like placing blocks, moving, typing commands or seeing the inventory of the player. +main: fr.xephi.authme.AuthMe +version: ${project.version} +softdepend: [Vault, ChestShop, Multiverse-Core, Citizens, CombatTag, Essentials, EssentialsSpawn, PerWorldInventories, ProtocolLib] +commands: + register: + description: Register an account + usage: /register password confirmpassword + aliases: reg + login: + description: Login into a account + usage: /login password + aliases: l + changepassword: + description: Change password of a account + usage: /changepassword oldPassword newPassword + logout: + description: Logout + usage: /logout + unregister: + description: unregister your account + usage: /unregister password + authme: + description: AuthMe op commands + usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version' + email: + description: Add Email or recover password + usage: '/email add your@email.com your@email.com|change oldEmail newEmail|recovery your@email.com' + captcha: + description: Captcha + usage: /captcha theCaptcha + converter: + description: Converter from different other auth plugins + usage: /converter +permissions: + authme.player.*: + description: Gives access to all authme player commands + default: true + children: + authme.register: true + authme.login: true + authme.changepassword: true + authme.logout: true + authme.unregister: true + authme.l: true + authme.reg: true + authme.email: true + authme.captcha: true + authme.admin.*: + description: Gives access to all authme admin commands + children: + authme.admin.reload: true + authme.admin.register: true + authme.admin.changepassword: true + authme.admin.unregister: true + authme.admin.purge: true + authme.seeOtherAccounts: true + authme.admin.lastlogin: true + authme.admin.getemail: true + authme.admin.chgemail: true + authme.admin.purgelastpos: true + authme.admin.switchantibot: true + authme.bypassantibot: true + authme.admin.getip: true + authme.admin.converter: true + authme.admin.resetposition: true + authme.admin.forcelogin: true + authme.register: + description: Register an account + default: true + authme.login: + description: Login into a account + default: true + authme.changepassword: + description: Change password of a account + default: true + authme.logout: + description: Logout + default: true + authme.email: + description: Email + default: true + authme.allow2accounts: + description: allow more accounts for same ip + default: false + authme.seeOtherAccounts: + description: display other accounts about a player when he logs in + default: false + authme.unregister: + description: unregister your account + default: true + authme.admin.reload: + description: AuthMe reload commands + default: op + authme.admin.register: + description: AuthMe register command + default: op + authme.admin.changepassword: + description: AuthMe changepassword command + default: op + authme.admin.unregister: + description: AuthMe unregister command + default: op + authme.admin.purge: + description: AuthMe unregister command + default: op + authme.admin.lastlogin: + description: Get last login date about a player + default: op + authme.admin.getemail: + description: Get last email about a player + default: op + authme.admin.chgemail: + description: Change a player email + default: op + authme.admin.accounts: + description: Display Players Accounts + default: op + authme.captcha: + description: Captcha + default: true + authme.admin.setspawn: + description: Set the AuthMe spawn point + default: op + authme.admin.spawn: + description: Teleport to AuthMe spawn point + default: op + authme.vip: + description: Allow vip slot when the server is full + default: op + authme.admin.purgebannedplayers: + description: Purge banned players + default: op + authme.bypassforcesurvival: + description: Bypass all ForceSurvival features + default: false + authme.admin.purgelastpos: + description: Purge last pos of players + default: op + authme.admin.switchantibot: + description: Switch AntiBot mode on/off + default: op + authme.bypassantibot: + description: Bypass the AntiBot check + default: op + authme.admin.setfirstspawn: + description: Set the AuthMe First Spawn Point + default: op + authme.admin.firstspawn: + description: Teleport to AuthMe First Spawn Point + default: op + authme.admin.getip: + description: Get IP from a player ( fake and real ) + default: op + authme.admin.converter: + description: Allow /converter command + default: op + authme.admin.resetposition: + description: Reset last position for a player + default: op + authme.admin.forcelogin: + description: Force login for that player + default: op + authme.canbeforced: + description: Can this player be forced to login + default: true diff --git a/src/main/resources/spawn.yml b/src/main/resources/spawn.yml new file mode 100644 index 0000000..5191803 --- /dev/null +++ b/src/main/resources/spawn.yml @@ -0,0 +1,14 @@ +spawn: + world: '' + x: '' + y: '' + z: '' + yaw: '' + pitch: '' +firstspawn: + world: '' + x: '' + y: '' + z: '' + yaw: '' + pitch: '' \ No newline at end of file diff --git a/team.txt b/team.txt new file mode 100644 index 0000000..427516c --- /dev/null +++ b/team.txt @@ -0,0 +1,22 @@ +AuthMe-Team: + +Active staff: +Xephi (Xephi59) - Leader, Main developer (temporary inactive) +DNx5 - Developer +games647 - Developer +Gabriele C. (sgdc3) - Project Manager, Contributor + +Staff to contact: +CryLegend - Contributor, AuthMeBridge Developer (Need activation) + +External Contributors: +Gnat008 - Contributor + +Inactive staff: +Maxetto - Ticket Manager, Italian Translator, Basic Developer, Contributor (Inactive) +darkwarriors (d4rkwarriors) - Original AuthMeReloaded Author (Inactive) + +Translators: +irobin591 - DE Translator +WaterCXubic - ZHHK Translator +Bodyash - Russian/Ukrainian translator