Repository: MiSecurity/exchange_proxy Branch: master Commit: bd6604d4ddb2 Files: 32 Total size: 125.0 KB Directory structure: gitextract_rvs2bfmj/ ├── .gitignore ├── LICENSE ├── README.md ├── conf/ │ └── app.ini ├── go.mod ├── go.sum ├── logger/ │ └── log.go ├── main.go ├── models/ │ ├── device.go │ └── redis.go ├── plugins/ │ ├── active_sync/ │ │ ├── active_code.go │ │ ├── active_sync.go │ │ ├── sms.go │ │ └── user_info.go │ ├── owa/ │ │ └── owa.go │ └── web/ │ ├── public/ │ │ ├── css/ │ │ │ └── common.css │ │ ├── i18n/ │ │ │ └── i18n.js │ │ ├── js/ │ │ │ ├── jquery.i18n/ │ │ │ │ └── 1.0.4/ │ │ │ │ ├── jquery.i18n.js │ │ │ │ └── jquery.i18n.messagestore.js │ │ │ ├── jquery.i18n.fallbacks.js │ │ │ ├── jquery.i18n.js │ │ │ └── jquery.i18n.messagestore.js │ │ └── scss/ │ │ ├── common.scss │ │ └── reset.scss │ ├── templates/ │ │ ├── activeSync.html │ │ └── deviceState.html │ └── web.go ├── settings/ │ └── settings.go ├── util/ │ ├── http_client.go │ ├── lib.go │ └── wbxml/ │ └── wbxml.go └── vars/ └── vars.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by .ignore support plugin (hsz.mobi) certs/* 1.tgz .idea ================================================ FILE: LICENSE ================================================ 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 . ================================================ FILE: README.md ================================================ ## Exchange_proxy Exchange_proxy是由go语言开发的Exchange安全代理,可以将内网的Exchange服务器的https服务安全地发布出去, 支持的功能如下: - WEB端增加OTP二次认证 - 手机端增加设备激活绑定的功能 - 屏蔽了PC端的EWS协议 在使用该系统前,需要确保有以下基础设施的接口,并完成与代理的对接: - OTP动态口令系统 - 短信发送接口 - 通过员工姓名查询员工手机号的接口 以上接口准备并对接完成后,正确配置conf/app.ini即可启动代理服务器了。 ```ini [mail] hosts = mail.xiaomi.com,mail.sec.lu backend = https://10.10.10.10 port = 443 ssl = true cert = certs/ca.crt key = certs/ca.key ; debug level: Fatal, Error, Warn, Info, Debug debug_level = info [redis] host = 10.10.10.20 port = 6379 db = 0 password = redis_passw0rd [otp] url = https://otp_api_url/chk_otp [sms] url = http://sms_api_url/api/send_sms header = X-SMS-Token key = token [user_info] user_phone = http://hr_api_url/findMobile active_url = https://mail.sec.lu/a/ ``` 配置文件说明: - mail节下的配置项是配置邮箱服务器本身的 - hosts表示邮箱域名,支持配置多个用英文逗号分割的域名 - backend表示邮箱服务器地址 - ssl表示是否启用https,必须设为true - cert和key分别表示证书的公、私钥,与nginx的证书完全兼容 - debug_level表示日志级别,默认为info级别 - redis节表示redis服务器的配置 - otp节为动态口令检测API的URL - sms节表示短信接口的API - user_info节下的user_phone表示查找手机的接口,active_url表示手机中激活连接的URL 设置好配置文件后,可通过`./main`直接启动代理服务器,如下图所示: ![](http://docs.xsec.io/images/mail_proxy/mail_proxy041.png) WEB通过外网访问WEB端时,要求必须输入正确的OTP口令才可以登录,如下图所示: ![](http://docs.xsec.io/images/mail_proxy/mail_proxy03.png) 通过手机端访问时,只有通过短信中的提示激活后,方可收发邮件,如下图所示: - 收到激活短信 ![](http://docs.xsec.io/images/mail_proxy/mail_proxy04.png) - 激活确认页面 ![](http://docs.xsec.io/images/mail_proxy/mail_proxy05.png) - 激活成功页面 ![](http://docs.xsec.io/images/mail_proxy/mail_proxy06.png) 正式上线之前,最好提供相应的管理后台并与内网的管理系统对接,邮件代理管理后台提供以下功能: - 管理员可查看、修改每个用户的账户与设备状态 - 管理员可查看每个设备的激活进程,方便故障排查 - 用户也可自行管理自己的设备 设备数据保存在redis中,用go/python/php等语言都可以实现,我就不单独提供了。 代理系统的进程可以托管在supervisor或god中,部署了该系统后,可以解决邮件服务器手机端与WEB端的安全,目前的开源版本没有电脑端的安全代理功能,建议在PC端收发邮件时拨入VPN,或者在电脑中用BlueMail客户端收发邮件。 ================================================ FILE: conf/app.ini ================================================ [mail] hosts = mail.xiaomi.com,mail.sec.lu backend = https://10.10.10.10 port = 443 ssl = true cert = certs/ca.crt key = certs/ca.key ; debug level: Fatal, Error, Warn, Info, Debug debug_level = info [redis] host = 10.10.10.20 port = 6379 db = 0 password = redis_passw0rd [otp] url = https://otp_api_url/chk_otp [sms] url = http://sms_api_url/api/send_sms header = X-SMS-Token key = token [user_info] user_phone = http://hr_api_url/findMobile active_url = https://mail.sec.lu ================================================ FILE: go.mod ================================================ module exchange_proxy require ( github.com/go-redis/redis v6.15.1+incompatible github.com/gorilla/websocket v1.4.0 // indirect github.com/magicmonty/activesync-go v0.0.0-20121203123100-40f879136bcb github.com/magicmonty/wbxml-go v0.0.0-20121123081138-2c61d93f134b github.com/mailgun/timetools v0.0.0-20170619190023-f3a7b8ffff47 // indirect github.com/mattn/go-colorable v0.1.1 // indirect github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect github.com/onsi/ginkgo v1.7.0 // indirect github.com/onsi/gomega v1.4.3 // indirect github.com/sirupsen/logrus v1.3.0 github.com/smartystreets/goconvey v0.0.0-20190222223459-a17d461953aa // indirect github.com/toolkits/slice v0.0.0-20141116085117-e44a80af2484 github.com/vulcand/oxy v0.0.0-20181130145254-c34b0c501e43 github.com/x-cray/logrus-prefixed-formatter v0.5.2 golang.org/x/net v0.0.0-20190213061140-3a22650c66bd // indirect gopkg.in/ini.v1 v1.42.0 gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce // indirect ) ================================================ FILE: go.sum ================================================ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/go-redis/redis v6.15.1+incompatible h1:BZ9s4/vHrIqwOb0OPtTQ5uABxETJ3NRuUNoSUurnkew= github.com/go-redis/redis v6.15.1+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/jtolds/gls v4.2.1+incompatible h1:fSuqC+Gmlu6l/ZYAoZzx2pyucC8Xza35fpRVWLVmUEE= github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/magicmonty/activesync-go v0.0.0-20121203123100-40f879136bcb h1:uDfElOCEXqYB1xPY5qxjJwJShKdSY5LiJMWfm6S5QVc= github.com/magicmonty/activesync-go v0.0.0-20121203123100-40f879136bcb/go.mod h1:pvQDeG1h7YU4W6x4xqPOHVLjs4UQ/Sk4X5WCrsjIcPM= github.com/magicmonty/wbxml-go v0.0.0-20121123081138-2c61d93f134b h1:dbUq4tyYWJbb+uusWCXag8wdf+fqg7hO0oSp8eC0Ypg= github.com/magicmonty/wbxml-go v0.0.0-20121123081138-2c61d93f134b/go.mod h1:k5Vtn0pkLSLO8fbQWknTKf03dbWHM29tcbEZ7+4RVlQ= github.com/mailgun/timetools v0.0.0-20170619190023-f3a7b8ffff47 h1:jlyJPTyctWqANbaxi/nXRrxX4WeeAGMPaHPj9XlO0Rw= github.com/mailgun/timetools v0.0.0-20170619190023-f3a7b8ffff47/go.mod h1:RYmqHbhWwIz3z9eVmQ2rx82rulEMG0t+Q1bzfc9DYN4= github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v0.0.0-20190222223459-a17d461953aa h1:E+gaaifzi2xF65PbDmuKI3PhLWY6G5opMLniFq8vmXA= github.com/smartystreets/goconvey v0.0.0-20190222223459-a17d461953aa/go.mod h1:2RVY1rIf+2J2o/IM9+vPq9RzmHDSseB7FoXiSNIUsoU= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/toolkits/slice v0.0.0-20141116085117-e44a80af2484 h1:ERmNDajjCusGqV3uLhlHhRNpvQiGM1S6pd0RSe3LP+w= github.com/toolkits/slice v0.0.0-20141116085117-e44a80af2484/go.mod h1:2ZKxkgYEh//pN54EFSkJBak63sg0LxQQFjQmpEwxQx0= github.com/vulcand/oxy v0.0.0-20181130145254-c34b0c501e43 h1:2+LBGeYYE8JgE1UCKx+qRpoFyvF4NdGQpR8bFCCPfEw= github.com/vulcand/oxy v0.0.0-20181130145254-c34b0c501e43/go.mod h1:giFb8dicROVdV5W0HXlA5siMBLWKnVXZlkA4Y5ZIzrY= github.com/x-cray/logrus-prefixed-formatter v0.5.2 h1:00txxvfBM9muc0jiLIEAkAcIMJzfthRT6usrui8uGmg= github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 h1:u+LnwYTOOW7Ukr/fppxEb1Nwz0AtPflrblfvUudpo+I= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/ini.v1 v1.42.0 h1:7N3gPTt50s8GuLortA00n8AqRTk75qOP98+mTPpgzRk= gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU= gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= ================================================ FILE: logger/log.go ================================================ package logger import ( "github.com/sirupsen/logrus" "github.com/x-cray/logrus-prefixed-formatter" ) var ( Log *logrus.Entry ) func init() { logger := logrus.New() logger.Formatter = new(prefixed.TextFormatter) Log = logger.WithFields(logrus.Fields{"prefix": "exchange proxy"}) Log.Logger.SetLevel(logrus.InfoLevel) } ================================================ FILE: main.go ================================================ package main import ( "exchange_proxy/logger" "exchange_proxy/plugins/active_sync" "exchange_proxy/plugins/owa" "exchange_proxy/plugins/web" "exchange_proxy/vars" "fmt" "net/http" "github.com/toolkits/slice" ) func main() { mux := http.NewServeMux() staticFiles := http.FileServer(http.Dir("plugins/web/public")) mux.Handle("/static/", http.StripPrefix("/static/", staticFiles)) mux.HandleFunc("/", owa.OwaHandler(owa.OwaRedirect)) mux.HandleFunc("/owa/", owa.OwaHandler(owa.OwaRedirect)) mux.HandleFunc("/Microsoft-Server-ActiveSync", active_sync.ActiveSyncHandler(active_sync.SyncRedirect)) mux.HandleFunc("/a/", web.Activation) mux.HandleFunc("/a/activedevice", web.ActiveDevice) mux.HandleFunc("/a/ignoredevice", web.IgnoreDevice) mux.HandleFunc("/EWS/", web.NotFound) mux.HandleFunc("/ecp/", web.NotFound) mux.HandleFunc("/rpc/", web.NotFound) mux.HandleFunc("/Autodiscover/", web.NotFound) s := &http.Server{ Addr: fmt.Sprintf(":%v", vars.MailConfig.Port), Handler: mux, } go func() { listen80Port() }() var err error if vars.MailConfig.TLS { err = s.ListenAndServeTLS(vars.MailConfig.Cert, vars.MailConfig.Key) } else { err = s.ListenAndServe() } logger.Log.Println(err) } func listen80Port() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if slice.ContainsString(vars.MailConfig.Host, r.Host) { logger.Log.Debugf("redirect http://%v -> https://%v", r.Host, r.Host) w.Header().Set("Location", fmt.Sprintf("https://%v", r.Host)) w.WriteHeader(302) } }) s := &http.Server{ Addr: ":80", Handler: mux, } _ = s.ListenAndServe() } ================================================ FILE: models/device.go ================================================ package models import ( "exchange_proxy/util/wbxml" "exchange_proxy/vars" "encoding/json" "fmt" "strconv" ) type ( // 移动设备信息 Device struct { DeviceType string `json:"device_type"` DeviceId string `json:"device_id"` User string `json:"user"` State int `json:"state"` Time int64 `json:"time"` } UserPhone struct { Code int `json:"code"` Data string `json:"data"` } ) // 注册新设备,默认为未激活状态 func NewDevice(user string, device Device) (err error) { InitRedis() v := make(map[string]interface{}) v["user_state"] = 0 info, _ := json.Marshal(device) v[device.DeviceId] = string(info) key := fmt.Sprintf("iuser_%v", user) _, err = vars.RedisInstance.HMSet(key, v).Result() return err } // 新建用户,默认为激活状态 func NewUser(user string) (err error) { InitRedis() key := fmt.Sprintf("iuser_%v", user) v := make(map[string]interface{}) v["user_state"] = 0 _, err = vars.RedisInstance.HMSet(key, v).Result() return err } // 获取用户状态:激活与锁定 func GetUserState(user string) (userState int, err error) { userState = -1 InitRedis() key := fmt.Sprintf("iuser_%v", user) ret, err := vars.RedisInstance.HGet(key, "user_state").Result() userState, _ = strconv.Atoi(ret) return userState, err } // 获取设备状态:激活、未激活、锁定等 func GetDeviceState(user, deviceId string) (state int) { state = -1 InitRedis() key := fmt.Sprintf("iuser_%v", user) ret, err := vars.RedisInstance.HGet(key, deviceId).Result() if err == nil { var device Device err := json.Unmarshal([]byte(ret), &device) if err == nil { state = device.State } } return state } // 获取设备信息 func GetDeviceInfo(user, deviceId string) (err error, deviceInfo Device) { InitRedis() key := fmt.Sprintf("iuser_%v", user) info, err := vars.RedisInstance.HGet(key, deviceId).Result() if err == nil { err = json.Unmarshal([]byte(info), &deviceInfo) } return err, deviceInfo } // 设置设备的状态:激活,锁定 // ALLOW = 0 // NEW = 1 // LOCKED = 2 // BLOCK = 3 func SetDeviceState(user, deviceId string, state int) (err error) { InitRedis() key := fmt.Sprintf("iuser_%v", user) err, deviceInfo := GetDeviceInfo(user, deviceId) if err == nil { deviceInfo.State = state info, err := json.Marshal(deviceInfo) v := make(map[string]interface{}) v[deviceId] = string(info) if err == nil { _, err = vars.RedisInstance.HMSet(key, v).Result() } } return err } // 激活设备 func ActiveDevice(user, deviceId string) (err error) { state := 0 err = SetDeviceState(user, deviceId, state) return err } // 恢复设备 func RestoreDevice(user, deviceId string) (err error) { state := 1 err = SetDeviceState(user, deviceId, state) return err } // 锁定设备 func LockDevice(user, deviceId string) (err error) { state := 2 err = SetDeviceState(user, deviceId, state) return err } // 忽略设备 func IgnoreDevice(user, deviceId string) (err error) { state := 3 err = SetDeviceState(user, deviceId, state) return err } // 指令检测 func CheckCmd(cmd string, cmdType map[string]bool) (result bool) { if cmdType[cmd] { result = true } return result } // 存储手机设备的信息 func SetDeviceInfo(deviceId string, deviceInfo wbxml.DeviceInfo) (err error) { m := make(map[string]interface{}) deviceInfoStr, _ := json.Marshal(deviceInfo) m[deviceId] = string(deviceInfoStr) InitRedis() key := "DEVICE_INFO_XSEC_MAIL" _, err = vars.RedisInstance.HMSet(key, m).Result() return err } // 通过设备ID查询手机设备的信息 func GetDeviceInfoByDeviceId(deviceId string) (deviceInfo wbxml.DeviceInfo, err error) { InitRedis() key := "DEVICE_INFO_XSEC_MAIL" deviceInfoStr, err := vars.RedisInstance.HGet(key, deviceId).Result() err = json.Unmarshal([]byte(deviceInfoStr), &deviceInfo) return deviceInfo, err } // 获取设备列表 func GetDeviceList(username string) (devices []string, err error) { key := fmt.Sprintf("iuser_%v", username) InitRedis() devices, err = vars.RedisInstance.HVals(key).Result() return devices, err } // 获取设备数 func GetDeviceNum(username string) (n int) { devices, err := GetDeviceList(username) if err == nil { n = len(devices) } return n } ================================================ FILE: models/redis.go ================================================ package models import ( "fmt" "time" "exchange_proxy/logger" "exchange_proxy/vars" "github.com/go-redis/redis" ) func init() { InitRedis() } func InitRedis() () { var err error vars.RedisInstance, err = NewRedisClient(vars.RedisConf.Host, vars.RedisConf.Port, vars.RedisConf.Db, vars.RedisConf.Password) if err != nil { logger.Log.Errorf("connect redis failed, err: %v", err) } } func NewRedisClient(host string, port int, db int, password string) (*redis.Client, error) { client := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%v:%v", host, port), Password: password, // no password set DB: db, // use default DB ReadTimeout: time.Minute, // set timeout value = 60 }) _, err := client.Ping().Result() return client, err } ================================================ FILE: plugins/active_sync/active_code.go ================================================ package active_sync import ( "exchange_proxy/models" "exchange_proxy/util" "exchange_proxy/vars" "strings" "encoding/json" "fmt" "time" ) func DoActiveDevice(user, deviceId, deviceType string, device models.Device) { _, isActive := GetDeviceActiveFlag(user, deviceId) if !isActive { // 设置进入设备激活流程的FLAG SetDeviceActiveFlag(user, deviceId) // 获取用户手机号 phone, err := GetUserPhone(vars.UserPhoneUrl, user) if err == nil { // 生成激活码 _, code := SetActiveCode(user, deviceId, device) // 发送激活码 smsStatus := SendCode(user, deviceId, deviceType, phone, code) // 发送成功的话删除已发送过的激活码 if smsStatus { _ = DelActiveCodeFlag(user, deviceId) } } } else { // logger.Log.Infof("%v, 已经激活过,忽略请求", device) // 已经激活过,忽略请求 } } // 获取设备激活标识 func GetDeviceActiveFlag(username, deviceId string) (err error, result bool) { models.InitRedis() key := fmt.Sprintf("active_%v_%v", username, deviceId) v, err := vars.RedisInstance.Exists(key).Result() if v == 1 { result = true } // logger.Log.Infof("key:%v, v: %v, err: %v, result: %v", key, v, err, result) return err, result } // 设置设备激活标识 func SetDeviceActiveFlag(username, deviceId string) { models.InitRedis() key := fmt.Sprintf("active_%v_%v", username, deviceId) _, _ = vars.RedisInstance.Set(key, deviceId, 60*time.Second).Result() } // 激活码是否生成过,生成过的话返回老激活码 func GetActiveCodeFlag(username, deviceId string) (has bool, code string) { key := fmt.Sprintf("icodeF_%v_%v", username, deviceId) models.InitRedis() ret, err := vars.RedisInstance.Get(key).Result() if err == nil && ret != "" { has = true code = ret } return has, code } // 设置验证码的标识,判断是否生成过验证码,12小时后失效 func SetActiveCodeFlag(username, deviceId, code string) { key := fmt.Sprintf("icodeF_%v_%v", username, deviceId) models.InitRedis() vars.RedisInstance.Set(key, code, 60*60*12*time.Second) } // 删除生成激活码的标识 func DelActiveCodeFlag(username, deviceId string) (err error) { key := fmt.Sprintf("icodeF_%v_%v", username, deviceId) models.InitRedis() _, err = vars.RedisInstance.Del(key).Result() return err } // 设置激活码的值及超时时间,该函数不对外公开 func setActiveCode(device models.Device, code string) (err error) { key := fmt.Sprintf("icode_%v", code) deviceStr, err := json.Marshal(device) v := fmt.Sprintf("%v-_-%v", device.User, string(deviceStr)) models.InitRedis() _, err = vars.RedisInstance.Set(key, v, 60*60*12*time.Second).Result() return err } // 激活码保存到redis中,有效期为8小时,不会多次生成 func SetActiveCode(username, deviceId string, device models.Device) (err error, code string) { has, oldCode := GetActiveCodeFlag(username, deviceId) if has { code = oldCode err = setActiveCode(device, oldCode) } else { code = util.GenerateAtiveCode(username, deviceId) SetActiveCodeFlag(username, deviceId, code) err = setActiveCode(device, code) } return err, code } // 删除激活码 func RemoveActiveCode(code string) (err error) { key := fmt.Sprintf("icode_%v", code) models.InitRedis() _, err = vars.RedisInstance.Del(key).Result() return err } // 获取激活码的值 func getActiveCodeValue(code string) (err error, has bool, user string, deviceInfo models.Device) { key := fmt.Sprintf("icode_%v", code) models.InitRedis() c, err := vars.RedisInstance.Get(key).Result() if err == nil { t := strings.Split(c, "-_-") if len(t) == 2 { user = t[0] deviceStr := t[1] err = json.Unmarshal([]byte(deviceStr), &deviceInfo) if err == nil { has = true } } } return err, has, user, deviceInfo } // 检测激活码 func CheckActiveCode(code string) (err error, has bool, user string, deviceInfo models.Device) { err, has, user, deviceInfo = getActiveCodeValue(code) return err, has, user, deviceInfo } // 激活时,验证激活码 func VerifyActiveCode(code string) (result bool, user string, device models.Device) { err, has, user, deviceInfo := CheckActiveCode(code) if err == nil && has { status := deviceInfo.State if status == 1 { result = true } } return result, user, deviceInfo } // 在激活流程中使用过激活码后重置激活码的状态,设为已激活并在2小时后自动删除 func ResetActiveCodeStatus(code, username string, device models.Device, state int) (result bool, err error) { models.InitRedis() key := fmt.Sprintf("icode_%v", code) device.State = state err = setActiveCode(device, code) if err == nil { result, err = vars.RedisInstance.Expire(key, 60*60*2*time.Second).Result() err = ResetSmsStatus(username, device.DeviceId) } return result, err } ================================================ FILE: plugins/active_sync/active_sync.go ================================================ package active_sync import ( "bytes" "crypto/tls" "io/ioutil" "net/http" "strings" "time" "exchange_proxy/logger" "exchange_proxy/models" "exchange_proxy/util/wbxml" "exchange_proxy/vars" "github.com/toolkits/slice" "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/testutils" ) func filterCmd(resp *http.Response) (err error) { var bodyBytes []byte bodyBytes, err = ioutil.ReadAll(resp.Request.Body) // 恢复Req.body的值给ParseForm函数使用 resp.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) values := resp.Request.URL.Query() if len(values) == 4 { cmd := values["Cmd"][0] mail := values["User"][0] deviceId := values["DeviceId"][0] user := "" // 取邮箱前缀 u := strings.Split(mail, "@") if len(u) == 2 { user = u[0] } // 取域的\后面部分 u1 := strings.Split(mail, "\\") if len(u1) == 2 { user = u1[1] } deviceState := models.GetDeviceState(user, deviceId) logger.Log.Infof("in filterCmd, user: %v, deviceId: %v, deviceState: %v", user, deviceId, deviceState) // 设备未激活时,过滤掉特定指令的返回值 if deviceState != 0 { if models.CheckCmd(cmd, vars.ResponseCmds) { resp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(""))) } } } // 恢复Req.body的值传到下一个处理器中 resp.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) return err } func SyncRedirect(w http.ResponseWriter, req *http.Request) { if slice.ContainsString(vars.MailConfig.Host, req.Host) { req.URL = testutils.ParseURI(vars.MailConfig.Backend) vars.FwdSync.ServeHTTP(w, req) } else { w.WriteHeader(444) } } func ActiveSyncHandler(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if vars.MailConfig.TLS { r := forward.RoundTripper( &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, ) // 对手机设备的处理逻辑 if strings.HasPrefix(req.RequestURI, "/Microsoft-Server-ActiveSync") { values := req.URL.Query() if len(values) > 0 { mail := values["User"][0] deviceId := values["DeviceId"][0] deviceType := values["DeviceType"][0] cmd := values["Cmd"][0] user := "" // 取邮箱前缀 u := strings.Split(mail, "@") if len(u) == 2 { user = u[0] } // 取域的\后面部分 u1 := strings.Split(mail, "\\") if len(u1) == 2 { user = u1[1] } device := models.Device{User: user, DeviceId: deviceId, DeviceType: deviceType, State: 1, Time: time.Now().Unix()} // 如果设备ID为0或为空,直接退出请求 if len(deviceId) <= 1 { w.WriteHeader(444) } // 获取设备信息的详细信息 var bodyBytes []byte bodyBytes, err := ioutil.ReadAll(req.Body) if err == nil { // 判断大小,否则可能会把邮件的附件传进来处理 if len(bodyBytes) < 500 { deviceInfo, err := wbxml.Parse(bodyBytes) if err == nil && deviceInfo.Model != "" { logger.Log.Debugf("deviceInfo: %v, err: %v", deviceInfo, err) _ = models.SetDeviceInfo(deviceId, deviceInfo) } } } // 用完后恢复req.Body的值,否则之后的处理器不能再用了 req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) userState, _ := models.GetUserState(user) // logger.Log.Infof("user: %v, state: %v", user, userState) // 用户状态为1,表示已经锁定的账户,直接退出请求 if userState == 1 { w.WriteHeader(444) } else if userState < 0 { _ = models.NewUser(user) } deviceState := models.GetDeviceState(user, deviceId) logger.Log.Debugf("user: %v, deviceId: %v, deviceState: %v, deviceType: %v, Cmd: %v", user, deviceId, deviceState, deviceType, cmd) if deviceState < 0 { // 设置不存在时,创建设备 _ = models.NewDevice(user, device) // 未激活前需要过滤掉可以返回给客户端数据的指令及返回的数据 vars.FwdSync, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r, forward.ResponseModifier(filterCmd)) h(w, req) } else if deviceState == 0 { // 设备已激活就直接放行 vars.FwdSync, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r, forward.Stream(true)) h(w, req) } else if deviceState == 1 { // 设备未激活时,进入激活流程 DoActiveDevice(user, deviceId, deviceType, device) // 未激活前需要过滤掉可以返回给客户端数据的指令及返回的数据 vars.FwdSync, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r, forward.ResponseModifier(filterCmd)) h(w, req) if models.CheckCmd(cmd, vars.RequestCmds) { w.WriteHeader(401) } } else { // 其他状态为锁定或阻止,不代理到后端,在代理层面直接返回 w.WriteHeader(200) } } else { // 对于OPTIONS指令,暂时直接透传到后端 vars.FwdSync, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r) h(w, req) } } } } } ================================================ FILE: plugins/active_sync/sms.go ================================================ package active_sync import ( "exchange_proxy/logger" "exchange_proxy/models" "exchange_proxy/vars" "fmt" "io/ioutil" "net/http" "strconv" "strings" "time" ) func SendCode(user, deviceId, deviceType, phone, code string) (status bool) { status = true key := fmt.Sprintf("sms_%v_%v_%v", user, deviceId, phone) models.InitRedis() ret, err := vars.RedisInstance.HMGet(key, "times", "send_time").Result() // logger.Log.Infof("key: %v, ret: %v, len(ret): %v, err: %v", key, ret, len(ret), err) now := time.Now().Unix() if err == nil && len(ret) == 2 { t, _ := ret[0].(string) times, _ := strconv.Atoi(t) st, _ := ret[1].(string) iSendTime, _ := strconv.Atoi(st) sendTime := int64(iSendTime) if times <= 5 && now-sendTime > 60*60*10 { content := generateSmsContent(user, deviceId, code, "", deviceType) _, ok := SendSmsAPI(user, phone, deviceId, code, content, "") status = ok times = times + 1 sendTime = now v := make(map[string]interface{}) v["times"] = times v["send_time"] = sendTime _, _ = vars.RedisInstance.HMSet(key, v).Result() } else { status = false } } return status } // 重置短信状态,保证激活之后能再次收到短信,否则要等8小时之后了 func ResetSmsStatus(user, deviceId string) (err error) { phone, err := GetUserPhone(vars.UserPhoneUrl, user) if err == nil { key := fmt.Sprintf("sms_%v_%v_%v", user, deviceId, phone) models.InitRedis() vars.RedisInstance.Del(key) } return err } // 发送短信 func SendSmsAPI(username, phone, deviceId, code, content, srcIp string) (err error, result bool) { client := &http.Client{} postData := strings.NewReader(fmt.Sprintf("recipients=%s&content=%s", phone, content)) req, err := http.NewRequest("POST", vars.SmsApiUrl, postData) if err == nil { req.Header.Add(vars.SmsApiHeader, vars.SmsApiKey) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err == nil { result = true defer resp.Body.Close() ret, err := ioutil.ReadAll(resp.Body) logger.Log.Infof("user:%v, deviceId: %v, code: %v, sms send result: %v, err: %v", username, deviceId, code, strings.TrimSpace(string(ret)), err) } } return err, result } // 生成短信内容 func generateSmsContent(username, deviceId, code, srcIp, deviceType string) (smsContent string) { // 获取用户手机设备信息 deviceInfo, err := models.GetDeviceInfoByDeviceId(deviceId) if err == nil { phone := deviceInfo.PhoneNumber if deviceInfo.Model != "" { deviceType = deviceInfo.Model } if len(phone) > 5 { smsContent = fmt.Sprintf("您的邮箱 %v 正在一台新的设备(%v,手机号码为:%v)上登录,请点击链接查看详情并允许或拒绝,%v/a/?c=%v (此链接8小时后失效)", username, deviceType, phone, vars.ActiveUrl, code) } } else { smsContent = fmt.Sprintf("您的邮箱 %v 正在一台新的设备(%v)上登录,请点击链接查看详情并允许或拒绝,%v/a/?c=%v (此链接8小时后失效)", username, deviceType, vars.ActiveUrl, code) } return smsContent } ================================================ FILE: plugins/active_sync/user_info.go ================================================ package active_sync import ( "encoding/json" "fmt" "io/ioutil" "net/http" "exchange_proxy/models" ) // 获取手机号 func GetUserPhone(url, user string) (phone string, err error) { var userPhone models.UserPhone resp, err := http.Get(fmt.Sprintf("%v?username=%v", url, user)) if err == nil { defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err == nil { err = json.Unmarshal(body, &userPhone) if err == nil && userPhone.Code == 200 { phone = userPhone.Data } } } return phone, err } ================================================ FILE: plugins/owa/owa.go ================================================ package owa import ( "bytes" "crypto/tls" "fmt" "io/ioutil" "net/http" "strconv" "strings" "github.com/toolkits/slice" "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/testutils" "exchange_proxy/logger" "exchange_proxy/util" "exchange_proxy/vars" ) func addOtp(resp *http.Response) error { b, err := ioutil.ReadAll(resp.Body) if err == nil { err = resp.Body.Close() oldHtml := "
" newHtml := "
动态口令:
" b = bytes.Replace(b, []byte(oldHtml), []byte(newHtml), -1) // replace html body := ioutil.NopCloser(bytes.NewReader(b)) resp.Body = body resp.ContentLength = int64(len(b)) resp.Header.Set("Content-Length", strconv.Itoa(len(b))) } return err } func OwaRedirect(w http.ResponseWriter, req *http.Request) { if slice.ContainsString(vars.MailConfig.Host, req.Host) { req.URL = testutils.ParseURI(vars.MailConfig.Backend) vars.FwdOWA.ServeHTTP(w, req) } else { u := fmt.Sprintf("https://%v//owa/auth/logon.aspx", vars.MailConfig.Host[0]) w.Header().Set("Location", u) w.WriteHeader(302) } } func OwaHandler(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { // 内网用户不用验证OTP口令 if strings.HasPrefix(req.RemoteAddr, "10.") || strings.HasPrefix(req.RemoteAddr, "192.") { r := forward.RoundTripper( &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, ) vars.FwdOWA, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r) h(w, req) } else { if vars.MailConfig.TLS { r := forward.RoundTripper( &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, ) if req.Method == "GET" && strings.HasPrefix(req.RequestURI, "/owa/auth/logon.aspx") { vars.FwdOWA, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r, forward.ResponseModifier(addOtp)) h(w, req) } else if req.Method == "POST" && strings.HasPrefix(req.RequestURI, "/owa/auth/logon.aspx") { var bodyBytes []byte if req.Body != nil { bodyBytes, _ = ioutil.ReadAll(req.Body) // 恢复Req.body的值给ParseForm函数使用 req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) _ = req.ParseForm() username := req.FormValue("username") customToken := req.FormValue("customToken") // 恢复Req.body的值传到下一个处理器中 req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) result, err := util.CheckToken(vars.OtpUrl, username, customToken) logger.Log.Printf("user: %v, token: %v, result: %v", username, customToken, result) if err == nil && result { vars.FwdOWA, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r) h(w, req) } else { w.Header().Set("Location", "/owa/auth/logon.aspx") w.WriteHeader(302) } } } else { vars.FwdOWA, _ = forward.New(forward.PassHostHeader(true), forward.Logger(logger.Log.Logger), r) h(w, req) } } } } } ================================================ FILE: plugins/web/public/css/common.css ================================================ *{margin:0;padding:0}a,a:hover{text-decoration:none;color:#09f}body{font-size:14px;font-family:arial, "Hiragino Sans GB", "Microsoft YaHei", "微軟正黑體", "儷黑 Pro", sans-serif;color:#000;background-color:#fff}.tac{text-align:center}.fl{float:left}.fr{float:right}ul{list-style:none}.clearfix:before,.clearfix:after{content:" ";display:table}.clearfix:after{clear:both}.container{padding:20px;max-width:400px;margin:auto}.mi_logo{width:48px;height:48px;margin:30px auto}.dear_user{font-size:16px;font-weight:bold;padding:10px 0}.help_phone{padding:10px 0}.modal{display:none;opacity:0;position:fixed;z-index:999;left:0;top:0;height:100%;width:100%;transition:opacity .5s}.allow_btn{margin-top:60px}.modal.visible{display:block;opacity:1}.modal_mask{position:absolute;left:0;top:0;width:100%;height:100%;opacity:.4;filter:alpha(opacity=40);background-color:black}.modal_box{text-align:center;position:absolute;bottom:-30px;width:90%;left:50%;box-shadow:0 1px 8px rgba(128,128,128,0.3);border:1px solid #d1d1d1;border-radius:10px;overflow:hidden;background-color:white;transition:width .5s ease, height .5s ease;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);-webkit-transform:translate(-50%, -50%, 0);transform:translate(-50%, -50%, 0);_top:0;_left:0;_margin-left:0;_margin-top:0;max-width:400px}.modal_body{margin:20px;text-align:left}.modal_footer{display:flex;border-top:1px solid #f8f8f8}.modal_btn{flex:1;padding:15px 0}.modal_btn_ok{color:#ff6700;border-left:1px solid #f8f8f8}.btn{margin-bottom:20px;text-align:center;padding:12px 0;border-radius:6px}.btn_ok{background-color:#ff6700;color:#fff}.btn_no{background-color:#fff;color:#999;border:1px solid #d3d3d3}.state{margin-top:30px}.state img{width:100px;height:100px;margin-top:40px}.state dd{font-size:30px;margin:20px 0}.device_list{margin:20px 0 20px 30px;list-style-type:disc}.device_list.gray{width:220px;color:#999;margin:40px auto 0 auto}.caution{margin:30px 0}.caution .line{width:100%;margin-bottom:-10px;border-bottom:1px solid #f0f0f0}.caution .txt{color:#999;background-color:#fff;padding:5px 10px}.tips{margin:20px 0}.icon_gter{width:10%;height:16px;display:block;position:relative}.icon_gter:after{content:"";width:12px;height:12px;border-width:1px;border-style:solid;border-color:transparent transparent rgba(0,0,0,0.3) rgba(0,0,0,0.3);-webkit-transform:rotate(-135deg);transform:rotate(-135deg);position:absolute;left:5px;top:4px}.icon_lser{width:10%;height:16px;display:block;position:relative}.icon_lser:after{content:"";width:12px;height:12px;border-width:1px;border-style:solid;border-color:transparent transparent rgba(0,0,0,0.3) rgba(0,0,0,0.3);-webkit-transform:rotate(45deg);transform:rotate(45deg);position:absolute;left:5px;top:4px}.active_tips{text-align:center}.more_tips .tips{height:60px;overflow:auto}.more_sec_info{font-size:12px}.lang-select-list{height:20px;line-height:20px;text-align:center}.lang-select-list li{font-size:14px;display:inline-block}.lang-select-list li a{padding:10px;color:#999}.lang-select-list li a.current{color:#ef5b00}.outlook_tips{color:#f66;font-size:12px;padding-bottom:20px;display:none} /*# sourceMappingURL=common.css.map */ ================================================ FILE: plugins/web/public/i18n/i18n.js ================================================ var txt = { cn: { "doc_title": "邮箱激活系统", "dear_user": "亲爱的:", "new_device": "您的邮箱 正在一台新的设备()上登录,详情如下", "device_name": "设备名称", "device_model": "设备型号", "device_type": "设备类型", "device_id": "设备ID", "imei_id": "IMEI", "phone_number":"手机号码", "ip_address": "新设备IP地址", "change_pwd": "如果这不是您本人操作,您的邮箱密码可能已经泄露,请修改密码并拒绝该请求。", "help_phone": "如需协助请联系IT部门", "outlook_tips": "您使用的是outlook客户端,用户名和密码会被保存到第三方微软公司的服务器中,存在安全风险,推荐使用手机自带的邮件客户端", "allow": " 允许", "reject": " 拒绝", "allow_confirm_tips": "确定后,将同步您的邮箱到该设备,如需禁用该设备,请登录内网帐号中心的“手机邮箱”中进行操作", "cancel": " 取消", "ok": "确定", "reject_manage_account": "拒绝后,将无法同步您的邮箱到该设备。如需重新激活该设备,请登录内网帐号中心的“手机邮箱”中进行操作", "device_actived": "设备已授权", "device_rejected": "设备已拒绝", "device_exceed": "设备数已超出限制", "page_not_found": "页面未找到", "link_invalid": "激活链接无效或已过期", "caution": "温馨提示", "auth_to_mis_manage": "已授权设备请登录到内网账号中心的“手机邮箱”中进行管理", "reject_to_mis_manage": "已拒绝设备请登录到内网账号中心的“手机邮箱”中进行管理", "to_mis_change_pwd": "如果这不是您本人操作,您的邮箱密码可能已泄露,并且有人正在尝试登陆您的邮箱,请立即点拒绝访问,并修改密码。", "devices_exceeds_the_limit": "已经激活的设备数超出了10台的限制,请中删除不再使用的设备", "more_sec_info": "更多安全知识,请访问 小米安全中心 ", "new_ip": "您的邮箱 正在使用()客户端进行同步邮件,详情如下", "client_type": "客户端类型", "device_ip": "移动设备IP地址", "client_ip": "客户端IP地址", "expire_tips": "该客户端 IP 有效期为 8 个小时,过期后需要重新进行授权", "allow_confirm_tips_ip": "确定后,将同步您的邮箱到该客户端,该客户端 IP 有效期为 8 个小时,如需禁用该 IP,请登录到“邮箱管理中心”中对 IP 进行管理", "reject_manage_account_ip": "拒绝后,将无法同步您的邮箱到该客户端。如需重新激活该 IP,请登录到“邮箱管理中心”中对 IP 进行管理", "ip_actived": "客户端 IP 已激活", "ip_rejected": "客户端 IP 已拒绝", "auth_to_mis_manage_ip": "已授权 IP 请登录到“邮箱管理中心”中对 IP 进行管理", "reject_to_mis_manage_ip": "已拒绝 IP 请登录到“邮箱管理中心”中对 IP 进行管理", "to_mis_change_pwd_ip": "如果该客户端 IP 不是您的 IP ,您的密码可能已经泄露,请立即修改密码" } }; $(function() { var $i18n = $.i18n(); $i18n.load(txt).done(function() { $('html').i18n(); $("[data-i18n^='[html]']").html(function() { return $.i18n($(this).attr('data-i18n').replace('\[html\]', '')); }); }) }) ================================================ FILE: plugins/web/public/js/jquery.i18n/1.0.4/jquery.i18n.js ================================================ /** * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do * anything special to choose one license or the other and you don't have to * notify anyone which license you are using. You are free to use * UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; var nav, I18N, slice = Array.prototype.slice; /** * @constructor * @param {Object} options */ I18N = function ( options ) { // Load defaults this.options = $.extend( {}, I18N.defaults, options ); this.parser = this.options.parser; this.locale = this.options.locale; this.messageStore = this.options.messageStore; this.languages = {}; this.init(); }; I18N.prototype = { /** * Initialize by loading locales and setting up * String.prototype.toLocaleString and String.locale. */ init: function () { var i18n = this; // Set locale of String environment String.locale = i18n.locale; // Override String.localeString method String.prototype.toLocaleString = function () { var localeParts, localePartIndex, value, locale, fallbackIndex, tryingLocale, message; value = this.valueOf(); locale = i18n.locale; fallbackIndex = 0; while ( locale ) { // Iterate through locales starting at most-specific until // localization is found. As in fi-Latn-FI, fi-Latn and fi. localeParts = locale.split( '-' ); localePartIndex = localeParts.length; do { tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' ); message = i18n.messageStore.get( tryingLocale, value ); if ( message ) { return message; } localePartIndex--; } while ( localePartIndex ); if ( locale === 'en' ) { break; } locale = ( $.i18n.fallbacks[i18n.locale] && $.i18n.fallbacks[i18n.locale][fallbackIndex] ) || i18n.options.fallbackLocale; $.i18n.log( 'Trying fallback locale for ' + i18n.locale + ': ' + locale ); fallbackIndex++; } // key not found return ''; }; }, /* * Destroy the i18n instance. */ destroy: function () { $.removeData( document, 'i18n' ); }, /** * General message loading API This can take a URL string for * the json formatted messages. Example: * load('path/to/all_localizations.json'); * * To load a localization file for a locale: * * load('path/to/de-messages.json', 'de' ); * * * To load a localization file from a directory: * * load('path/to/i18n/directory', 'de' ); * * The above method has the advantage of fallback resolution. * ie, it will automatically load the fallback locales for de. * For most usecases, this is the recommended method. * It is optional to have trailing slash at end. * * A data object containing message key- message translation mappings * can also be passed. Example: * * load( { 'hello' : 'Hello' }, optionalLocale ); * * * A source map containing key-value pair of languagename and locations * can also be passed. Example: * * load( { * bn: 'i18n/bn.json', * he: 'i18n/he.json', * en: 'i18n/en.json' * } ) * * * If the data argument is null/undefined/false, * all cached messages for the i18n instance will get reset. * * @param {String|Object} source * @param {String} locale Language tag * @returns {jQuery.Promise} */ load: function ( source, locale ) { var fallbackLocales, locIndex, fallbackLocale, sourceMap = {}; if ( !source && !locale ) { source = 'i18n/' + $.i18n().locale + '.json'; locale = $.i18n().locale; } if ( typeof source === 'string' && source.split( '.' ).pop() !== 'json' ) { // Load specified locale then check for fallbacks when directory is specified in load() sourceMap[locale] = source + '/' + locale + '.json'; fallbackLocales = ( $.i18n.fallbacks[locale] || [] ) .concat( this.options.fallbackLocale ); for ( locIndex in fallbackLocales ) { fallbackLocale = fallbackLocales[locIndex]; sourceMap[fallbackLocale] = source + '/' + fallbackLocale + '.json'; } return this.load( sourceMap ); } else { return this.messageStore.load( source, locale ); } }, /** * Does parameter and magic word substitution. * * @param {string} key Message key * @param {Array} parameters Message parameters * @return {string} */ parse: function ( key, parameters ) { var message = key.toLocaleString(); // FIXME: This changes the state of the I18N object, // should probably not change the 'this.parser' but just // pass it to the parser. this.parser.language = $.i18n.languages[$.i18n().locale] || $.i18n.languages['default']; if ( message === '' ) { message = key; } return this.parser.parse( message, parameters ); } }; /** * Process a message from the $.I18N instance * for the current document, stored in jQuery.data(document). * * @param {string} key Key of the message. * @param {string} param1 [param...] Variadic list of parameters for {key}. * @return {string|$.I18N} Parsed message, or if no key was given * the instance of $.I18N is returned. */ $.i18n = function ( key, param1 ) { var parameters, i18n = $.data( document, 'i18n' ), options = typeof key === 'object' && key; // If the locale option for this call is different then the setup so far, // update it automatically. This doesn't just change the context for this // call but for all future call as well. // If there is no i18n setup yet, don't do this. It will be taken care of // by the `new I18N` construction below. // NOTE: It should only change language for this one call. // Then cache instances of I18N somewhere. if ( options && options.locale && i18n && i18n.locale !== options.locale ) { String.locale = i18n.locale = options.locale; } if ( !i18n ) { i18n = new I18N( options ); $.data( document, 'i18n', i18n ); } if ( typeof key === 'string' ) { if ( param1 !== undefined ) { parameters = slice.call( arguments, 1 ); } else { parameters = []; } return i18n.parse( key, parameters ); } else { // FIXME: remove this feature/bug. return i18n; } }; $.fn.i18n = function () { var i18n = $.data( document, 'i18n' ); if ( !i18n ) { i18n = new I18N(); $.data( document, 'i18n', i18n ); } String.locale = i18n.locale; return this.each( function () { var $this = $( this ), messageKey = $this.data( 'i18n' ); if ( messageKey ) { $this.text( i18n.parse( messageKey ) ); } else { $this.find( '[data-i18n]' ).i18n(); } } ); }; String.locale = String.locale || $( 'html' ).attr( 'lang' ); if ( !String.locale ) { if ( typeof window.navigator !== undefined ) { nav = window.navigator; String.locale = nav.language || nav.userLanguage || ''; } else { String.locale = ''; } } $.i18n.languages = {}; $.i18n.messageStore = $.i18n.messageStore || {}; $.i18n.parser = { // The default parser only handles variable substitution parse: function ( message, parameters ) { return message.replace( /\$(\d+)/g, function ( str, match ) { var index = parseInt( match, 10 ) - 1; return parameters[index] !== undefined ? parameters[index] : '$' + match; } ); }, emitter: {} }; $.i18n.fallbacks = {}; $.i18n.debug = false; $.i18n.log = function ( /* arguments */ ) { if ( window.console && $.i18n.debug ) { window.console.log.apply( window.console, arguments ); } }; /* Static members */ I18N.defaults = { locale: String.locale, fallbackLocale: 'en', parser: $.i18n.parser, messageStore: $.i18n.messageStore }; // Expose constructor $.i18n.constructor = I18N; }( jQuery ) ); ================================================ FILE: plugins/web/public/js/jquery.i18n/1.0.4/jquery.i18n.messagestore.js ================================================ /** * jQuery Internationalization library - Message Store * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do anything special to * choose one license or the other and you don't have to notify anyone which license you are using. * You are free to use UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $, window, undefined ) { 'use strict'; var MessageStore = function () { this.messages = {}; this.sources = {}; }; /** * See https://github.com/wikimedia/jquery.i18n/wiki/Specification#wiki-Message_File_Loading */ MessageStore.prototype = { /** * General message loading API This can take a URL string for * the json formatted messages. * load('path/to/all_localizations.json'); * * This can also load a localization file for a locale * load( 'path/to/de-messages.json', 'de' ); * * A data object containing message key- message translation mappings * can also be passed Eg: * * load( { 'hello' : 'Hello' }, optionalLocale ); * If the data argument is * null/undefined/false, * all cached messages for the i18n instance will get reset. * * @param {String|Object} source * @param {String} locale Language tag * @return {jQuery.Promise} */ load: function ( source, locale ) { var key = null, deferred = null, deferreds = [], messageStore = this; if ( typeof source === 'string' ) { // This is a URL to the messages file. $.i18n.log( 'Loading messages from: ' + source ); deferred = jsonMessageLoader( source ) .done( function ( localization ) { messageStore.set( locale, localization ); } ); return deferred.promise(); } if ( locale ) { // source is an key-value pair of messages for given locale messageStore.set( locale, source ); return $.Deferred().resolve(); } else { // source is a key-value pair of locales and their source for ( key in source ) { if ( Object.prototype.hasOwnProperty.call( source, key ) ) { locale = key; // No {locale} given, assume data is a group of languages, // call this function again for each language. deferreds.push( messageStore.load( source[key], locale ) ); } } return $.when.apply( $, deferreds ); } }, /** * Set messages to the given locale. * If locale exists, add messages to the locale. * @param locale * @param messages */ set: function ( locale, messages ) { if ( !this.messages[locale] ) { this.messages[locale] = messages; } else { this.messages[locale] = $.extend( this.messages[locale], messages ); } }, /** * * @param locale * @param messageKey * @returns {Boolean} */ get: function ( locale, messageKey ) { return this.messages[locale] && this.messages[locale][messageKey]; } }; function jsonMessageLoader( url ) { var deferred = $.Deferred(); $.getJSON( url ) .done( deferred.resolve ) .fail( function ( jqxhr, settings, exception ) { $.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception ); // Ignore 404 exception, because we are handling fallabacks explicitly deferred.resolve(); } ); return deferred.promise(); } $.extend( $.i18n.messageStore, new MessageStore() ); }( jQuery, window ) ); ================================================ FILE: plugins/web/public/js/jquery.i18n.fallbacks.js ================================================ /*! * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do anything special to * choose one license or the other and you don't have to notify anyone which license you are using. * You are free to use UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; $.i18n = $.i18n || {}; $.extend( $.i18n.fallbacks, { ab: [ 'ru' ], ace: [ 'id' ], aln: [ 'sq' ], // Not so standard - als is supposed to be Tosk Albanian, // but in Wikipedia it's used for a Germanic language. als: [ 'gsw', 'de' ], an: [ 'es' ], anp: [ 'hi' ], arn: [ 'es' ], arz: [ 'ar' ], av: [ 'ru' ], ay: [ 'es' ], ba: [ 'ru' ], bar: [ 'de' ], 'bat-smg': [ 'sgs', 'lt' ], bcc: [ 'fa' ], 'be-x-old': [ 'be-tarask' ], bh: [ 'bho' ], bjn: [ 'id' ], bm: [ 'fr' ], bpy: [ 'bn' ], bqi: [ 'fa' ], bug: [ 'id' ], 'cbk-zam': [ 'es' ], ce: [ 'ru' ], crh: [ 'crh-latn' ], 'crh-cyrl': [ 'ru' ], csb: [ 'pl' ], cv: [ 'ru' ], 'de-at': [ 'de' ], 'de-ch': [ 'de' ], 'de-formal': [ 'de' ], dsb: [ 'de' ], dtp: [ 'ms' ], egl: [ 'it' ], eml: [ 'it' ], ff: [ 'fr' ], fit: [ 'fi' ], 'fiu-vro': [ 'vro', 'et' ], frc: [ 'fr' ], frp: [ 'fr' ], frr: [ 'de' ], fur: [ 'it' ], gag: [ 'tr' ], gan: [ 'gan-hant', 'zh-hant', 'zh-hans' ], 'gan-hans': [ 'zh-hans' ], 'gan-hant': [ 'zh-hant', 'zh-hans' ], gl: [ 'pt' ], glk: [ 'fa' ], gn: [ 'es' ], gsw: [ 'de' ], hif: [ 'hif-latn' ], hsb: [ 'de' ], ht: [ 'fr' ], ii: [ 'zh-cn', 'zh-hans' ], inh: [ 'ru' ], iu: [ 'ike-cans' ], jut: [ 'da' ], jv: [ 'id' ], kaa: [ 'kk-latn', 'kk-cyrl' ], kbd: [ 'kbd-cyrl' ], khw: [ 'ur' ], kiu: [ 'tr' ], kk: [ 'kk-cyrl' ], 'kk-arab': [ 'kk-cyrl' ], 'kk-latn': [ 'kk-cyrl' ], 'kk-cn': [ 'kk-arab', 'kk-cyrl' ], 'kk-kz': [ 'kk-cyrl' ], 'kk-tr': [ 'kk-latn', 'kk-cyrl' ], kl: [ 'da' ], 'ko-kp': [ 'ko' ], koi: [ 'ru' ], krc: [ 'ru' ], ks: [ 'ks-arab' ], ksh: [ 'de' ], ku: [ 'ku-latn' ], 'ku-arab': [ 'ckb' ], kv: [ 'ru' ], lad: [ 'es' ], lb: [ 'de' ], lbe: [ 'ru' ], lez: [ 'ru' ], li: [ 'nl' ], lij: [ 'it' ], liv: [ 'et' ], lmo: [ 'it' ], ln: [ 'fr' ], ltg: [ 'lv' ], lzz: [ 'tr' ], mai: [ 'hi' ], 'map-bms': [ 'jv', 'id' ], mg: [ 'fr' ], mhr: [ 'ru' ], min: [ 'id' ], mo: [ 'ro' ], mrj: [ 'ru' ], mwl: [ 'pt' ], myv: [ 'ru' ], mzn: [ 'fa' ], nah: [ 'es' ], nap: [ 'it' ], nds: [ 'de' ], 'nds-nl': [ 'nl' ], 'nl-informal': [ 'nl' ], no: [ 'nb' ], os: [ 'ru' ], pcd: [ 'fr' ], pdc: [ 'de' ], pdt: [ 'de' ], pfl: [ 'de' ], pms: [ 'it' ], pt: [ 'pt-br' ], 'pt-br': [ 'pt' ], qu: [ 'es' ], qug: [ 'qu', 'es' ], rgn: [ 'it' ], rmy: [ 'ro' ], 'roa-rup': [ 'rup' ], rue: [ 'uk', 'ru' ], ruq: [ 'ruq-latn', 'ro' ], 'ruq-cyrl': [ 'mk' ], 'ruq-latn': [ 'ro' ], sa: [ 'hi' ], sah: [ 'ru' ], scn: [ 'it' ], sg: [ 'fr' ], sgs: [ 'lt' ], sli: [ 'de' ], sr: [ 'sr-ec' ], srn: [ 'nl' ], stq: [ 'de' ], su: [ 'id' ], szl: [ 'pl' ], tcy: [ 'kn' ], tg: [ 'tg-cyrl' ], tt: [ 'tt-cyrl', 'ru' ], 'tt-cyrl': [ 'ru' ], ty: [ 'fr' ], udm: [ 'ru' ], ug: [ 'ug-arab' ], uk: [ 'ru' ], vec: [ 'it' ], vep: [ 'et' ], vls: [ 'nl' ], vmf: [ 'de' ], vot: [ 'fi' ], vro: [ 'et' ], wa: [ 'fr' ], wo: [ 'fr' ], wuu: [ 'zh-hans' ], xal: [ 'ru' ], xmf: [ 'ka' ], yi: [ 'he' ], za: [ 'zh-hans' ], zea: [ 'nl' ], zh: [ 'zh-hans' ], 'zh-classical': [ 'lzh' ], 'zh-cn': [ 'zh-hans' ], 'zh-hant': [ 'zh-hans' ], 'zh-hk': [ 'zh-hant', 'zh-hans' ], 'zh-min-nan': [ 'nan' ], 'zh-mo': [ 'zh-hk', 'zh-hant', 'zh-hans' ], 'zh-my': [ 'zh-sg', 'zh-hans' ], 'zh-sg': [ 'zh-hans' ], 'zh-tw': [ 'zh-hant', 'zh-hans' ], 'zh-yue': [ 'yue' ] } ); }( jQuery ) ); ================================================ FILE: plugins/web/public/js/jquery.i18n.js ================================================ /*! * jQuery Internationalization library * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do * anything special to choose one license or the other and you don't have to * notify anyone which license you are using. You are free to use * UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; var I18N, slice = Array.prototype.slice; /** * @constructor * @param {Object} options */ I18N = function ( options ) { // Load defaults this.options = $.extend( {}, I18N.defaults, options ); this.parser = this.options.parser; this.locale = this.options.locale; this.messageStore = this.options.messageStore; this.languages = {}; }; I18N.prototype = { /** * Localize a given messageKey to a locale. * @param {String} messageKey * @return {String} Localized message */ localize: function ( messageKey ) { var localeParts, localePartIndex, locale, fallbackIndex, tryingLocale, message; locale = this.locale; fallbackIndex = 0; while ( locale ) { // Iterate through locales starting at most-specific until // localization is found. As in fi-Latn-FI, fi-Latn and fi. localeParts = locale.split( '-' ); localePartIndex = localeParts.length; do { tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' ); message = this.messageStore.get( tryingLocale, messageKey ); if ( message ) { return message; } localePartIndex--; } while ( localePartIndex ); if ( locale === 'en' ) { break; } locale = ( $.i18n.fallbacks[ this.locale ] && $.i18n.fallbacks[ this.locale ][ fallbackIndex ] ) || this.options.fallbackLocale; $.i18n.log( 'Trying fallback locale for ' + this.locale + ': ' + locale + ' (' + messageKey + ')' ); fallbackIndex++; } // key not found return ''; }, /* * Destroy the i18n instance. */ destroy: function () { $.removeData( document, 'i18n' ); }, /** * General message loading API This can take a URL string for * the json formatted messages. Example: * load('path/to/all_localizations.json'); * * To load a localization file for a locale: * * load('path/to/de-messages.json', 'de' ); * * * To load a localization file from a directory: * * load('path/to/i18n/directory', 'de' ); * * The above method has the advantage of fallback resolution. * ie, it will automatically load the fallback locales for de. * For most usecases, this is the recommended method. * It is optional to have trailing slash at end. * * A data object containing message key- message translation mappings * can also be passed. Example: * * load( { 'hello' : 'Hello' }, optionalLocale ); * * * A source map containing key-value pair of languagename and locations * can also be passed. Example: * * load( { * bn: 'i18n/bn.json', * he: 'i18n/he.json', * en: 'i18n/en.json' * } ) * * * If the data argument is null/undefined/false, * all cached messages for the i18n instance will get reset. * * @param {string|Object} source * @param {string} locale Language tag * @return {jQuery.Promise} */ load: function ( source, locale ) { var fallbackLocales, locIndex, fallbackLocale, sourceMap = {}; if ( !source && !locale ) { source = 'i18n/' + $.i18n().locale + '.json'; locale = $.i18n().locale; } if ( typeof source === 'string' && // source extension should be json, but can have query params after that. source.split( '?' )[ 0 ].split( '.' ).pop() !== 'json' ) { // Load specified locale then check for fallbacks when directory is // specified in load() sourceMap[ locale ] = source + '/' + locale + '.json'; fallbackLocales = ( $.i18n.fallbacks[ locale ] || [] ) .concat( this.options.fallbackLocale ); for ( locIndex = 0; locIndex < fallbackLocales.length; locIndex++ ) { fallbackLocale = fallbackLocales[ locIndex ]; sourceMap[ fallbackLocale ] = source + '/' + fallbackLocale + '.json'; } return this.load( sourceMap ); } else { return this.messageStore.load( source, locale ); } }, /** * Does parameter and magic word substitution. * * @param {string} key Message key * @param {Array} parameters Message parameters * @return {string} */ parse: function ( key, parameters ) { var message = this.localize( key ); // FIXME: This changes the state of the I18N object, // should probably not change the 'this.parser' but just // pass it to the parser. this.parser.language = $.i18n.languages[ $.i18n().locale ] || $.i18n.languages[ 'default' ]; if ( message === '' ) { message = key; } return this.parser.parse( message, parameters ); } }; /** * Process a message from the $.I18N instance * for the current document, stored in jQuery.data(document). * * @param {string} key Key of the message. * @param {string} param1 [param...] Variadic list of parameters for {key}. * @return {string|$.I18N} Parsed message, or if no key was given * the instance of $.I18N is returned. */ $.i18n = function ( key, param1 ) { var parameters, i18n = $.data( document, 'i18n' ), options = typeof key === 'object' && key; // If the locale option for this call is different then the setup so far, // update it automatically. This doesn't just change the context for this // call but for all future call as well. // If there is no i18n setup yet, don't do this. It will be taken care of // by the `new I18N` construction below. // NOTE: It should only change language for this one call. // Then cache instances of I18N somewhere. if ( options && options.locale && i18n && i18n.locale !== options.locale ) { i18n.locale = options.locale; } if ( !i18n ) { i18n = new I18N( options ); $.data( document, 'i18n', i18n ); } if ( typeof key === 'string' ) { if ( param1 !== undefined ) { parameters = slice.call( arguments, 1 ); } else { parameters = []; } return i18n.parse( key, parameters ); } else { // FIXME: remove this feature/bug. return i18n; } }; $.fn.i18n = function () { var i18n = $.data( document, 'i18n' ); if ( !i18n ) { i18n = new I18N(); $.data( document, 'i18n', i18n ); } return this.each( function () { var $this = $( this ), messageKey = $this.data( 'i18n' ), lBracket, rBracket, type, key; if ( messageKey ) { lBracket = messageKey.indexOf( '[' ); rBracket = messageKey.indexOf( ']' ); if ( lBracket !== -1 && rBracket !== -1 && lBracket < rBracket ) { type = messageKey.slice( lBracket + 1, rBracket ); key = messageKey.slice( rBracket + 1 ); if ( type === 'html' ) { $this.html( i18n.parse( key ) ); } else { $this.attr( type, i18n.parse( key ) ); } } else { $this.text( i18n.parse( messageKey ) ); } } else { $this.find( '[data-i18n]' ).i18n(); } } ); }; function getDefaultLocale() { var nav, locale = $( 'html' ).attr( 'lang' ); if ( !locale ) { if ( typeof window.navigator !== undefined ) { nav = window.navigator; locale = nav.language || nav.userLanguage || ''; } else { locale = ''; } } return locale; } $.i18n.languages = {}; $.i18n.messageStore = $.i18n.messageStore || {}; $.i18n.parser = { // The default parser only handles variable substitution parse: function ( message, parameters ) { return message.replace( /\$(\d+)/g, function ( str, match ) { var index = parseInt( match, 10 ) - 1; return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match; } ); }, emitter: {} }; $.i18n.fallbacks = {}; $.i18n.debug = false; $.i18n.log = function ( /* arguments */ ) { if ( window.console && $.i18n.debug ) { window.console.log.apply( window.console, arguments ); } }; /* Static members */ I18N.defaults = { locale: getDefaultLocale(), fallbackLocale: 'en', parser: $.i18n.parser, messageStore: $.i18n.messageStore }; // Expose constructor $.i18n.constructor = I18N; }( jQuery ) ); ================================================ FILE: plugins/web/public/js/jquery.i18n.messagestore.js ================================================ /*! * jQuery Internationalization library - Message Store * * Copyright (C) 2012 Santhosh Thottingal * * jquery.i18n is dual licensed GPLv2 or later and MIT. You don't have to do anything special to * choose one license or the other and you don't have to notify anyone which license you are using. * You are free to use UniversalLanguageSelector in commercial projects as long as the copyright * header is left intact. See files GPL-LICENSE and MIT-LICENSE for details. * * @licence GNU General Public Licence 2.0 or later * @licence MIT License */ ( function ( $ ) { 'use strict'; var MessageStore = function () { this.messages = {}; this.sources = {}; }; function jsonMessageLoader( url ) { var deferred = $.Deferred(); $.getJSON( url ) .done( deferred.resolve ) .fail( function ( jqxhr, settings, exception ) { $.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception ); // Ignore 404 exception, because we are handling fallabacks explicitly deferred.resolve(); } ); return deferred.promise(); } /** * See https://github.com/wikimedia/jquery.i18n/wiki/Specification#wiki-Message_File_Loading */ MessageStore.prototype = { /** * General message loading API This can take a URL string for * the json formatted messages. * load('path/to/all_localizations.json'); * * This can also load a localization file for a locale * load( 'path/to/de-messages.json', 'de' ); * * A data object containing message key- message translation mappings * can also be passed Eg: * * load( { 'hello' : 'Hello' }, optionalLocale ); * If the data argument is * null/undefined/false, * all cached messages for the i18n instance will get reset. * * @param {string|Object} source * @param {string} locale Language tag * @return {jQuery.Promise} */ load: function ( source, locale ) { var key = null, deferred = null, deferreds = [], messageStore = this; if ( typeof source === 'string' ) { // This is a URL to the messages file. $.i18n.log( 'Loading messages from: ' + source ); deferred = jsonMessageLoader( source ) .done( function ( localization ) { messageStore.set( locale, localization ); } ); return deferred.promise(); } if ( locale ) { // source is an key-value pair of messages for given locale messageStore.set( locale, source ); return $.Deferred().resolve(); } else { // source is a key-value pair of locales and their source for ( key in source ) { if ( Object.prototype.hasOwnProperty.call( source, key ) ) { locale = key; // No {locale} given, assume data is a group of languages, // call this function again for each language. deferreds.push( messageStore.load( source[ key ], locale ) ); } } return $.when.apply( $, deferreds ); } }, /** * Set messages to the given locale. * If locale exists, add messages to the locale. * * @param {string} locale * @param {Object} messages */ set: function ( locale, messages ) { if ( !this.messages[ locale ] ) { this.messages[ locale ] = messages; } else { this.messages[ locale ] = $.extend( this.messages[ locale ], messages ); } }, /** * * @param {string} locale * @param {string} messageKey * @return {boolean} */ get: function ( locale, messageKey ) { return this.messages[ locale ] && this.messages[ locale ][ messageKey ]; } }; $.extend( $.i18n.messageStore, new MessageStore() ); }( jQuery ) ); ================================================ FILE: plugins/web/public/scss/common.scss ================================================ @import "reset"; .container { padding: 20px; max-width: 400px; margin: auto; } .mi_logo { width: 48px; height: 48px; margin: 30px auto; } .dear_user { font-size: 16px; font-weight: bold; padding: 10px 0; } .help_phone { padding: 10px 0; } .modal { display: none; opacity: 0; position: fixed; z-index: 999; left: 0; top: 0; height: 100%; width: 100%; transition: opacity .5s; } .allow_btn { margin-top: 60px; } .modal.visible { display: block; opacity: 1; } .modal_mask { position: absolute; left: 0; top: 0; width: 100%; height: 100%; opacity: .4; filter: alpha(opacity=40); background-color: black; } .modal_box { text-align: center; position: absolute; bottom: -30px; width: 90%; left: 50%; box-shadow: 0 1px 8px rgba(128, 128, 128, 0.3); border: 1px solid #d1d1d1; border-radius: 10px; overflow: hidden; background-color: white; transition: width .5s ease, height .5s ease; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%, 0); transform: translate(-50%, -50%, 0); _top: 0; _left: 0; _margin-left: 0; _margin-top: 0; max-width: 400px; } .modal_body { margin: 20px; text-align: left; } .modal_footer { display: flex; border-top: 1px solid #f8f8f8; } .modal_btn { flex: 1; padding: 15px 0; } .modal_btn_ok { color: #ff6700; border-left: 1px solid #f8f8f8; } .btn { margin-bottom: 20px; text-align: center; padding: 12px 0; border-radius: 6px; } .btn_ok { background-color: #ff6700; color: #fff; } .btn_no { background-color: #fff; color: #999; border: 1px solid #d3d3d3; } .state { margin-top: 30px; img { width: 100px; height: 100px; margin-top: 40px; } dd { font-size: 30px; margin: 20px 0; } } .device_list { margin: 20px 0 20px 30px; list-style-type: disc; &.gray { width: 220px; color: #999; margin: 40px auto 0 auto; } } .caution { margin: 30px 0; .line { width: 100%; margin-bottom: -10px; border-bottom: 1px solid #f0f0f0; } .txt { color: #999; background-color: #fff; padding: 5px 10px; } } .tips { margin: 20px 0; } .icon_gter { width: 10%; height: 16px; display: block; position: relative; &:after { content: ""; width: 12px; height: 12px; border-width: 1px; border-style: solid; border-color: transparent transparent rgba(0, 0, 0, 0.3) rgba(0, 0, 0, 0.3); -webkit-transform: rotate(-135deg); transform: rotate(-135deg); position: absolute; left: 5px; top: 4px; } } .icon_lser { width: 10%; height: 16px; display: block; position: relative; &:after { content: ""; width: 12px; height: 12px; border-width: 1px; border-style: solid; border-color: transparent transparent rgba(0, 0, 0, 0.3) rgba(0, 0, 0, 0.3); -webkit-transform: rotate(45deg); transform: rotate(45deg); position: absolute; left: 5px; top: 4px; } } .active_tips { text-align: center; } .more_tips { .tips { height: 60px; overflow: auto; } } .more_sec_info { font-size: 12px; } .lang-select-list { height: 20px; line-height: 20px; text-align: center; li { font-size: 14px; display: inline-block; a { padding: 10px; color: #999; &.current { color: #ef5b00; } } } } .outlook_tips { color: #f66; font-size: 12px; padding-bottom: 20px; display: none; } ================================================ FILE: plugins/web/public/scss/reset.scss ================================================ * { margin: 0; padding: 0; } a, a:hover { text-decoration: none; color: #09f; } body { font-size: 14px; font-family: arial, "Hiragino Sans GB", "Microsoft YaHei", "微軟正黑體", "儷黑 Pro", sans-serif; color: #000; background-color: #fff; } .tac { text-align: center; } .fl { float: left; } .fr { float: right } ul { list-style: none; } .clearfix { &:before, &:after { content: " "; display: table; } &:after { clear: both; } } ================================================ FILE: plugins/web/templates/activeSync.html ================================================ 邮箱激活系统

亲爱的

您的邮箱 正在一台新的设备()上登录,详情如下

    您使用的是outlook客户端,用户名和密码会被保存到第三方微软公司的服务器中,存在安全风险,推荐使用手机自带的邮件客户端

    如果这不是您本人操作,您的邮箱密码可能已经泄露,请登录到内网帐号中心修改密码并拒绝该请求

    如需协助请联系IT部门

    允许
    拒绝
    ================================================ FILE: plugins/web/templates/deviceState.html ================================================ 邮箱激活系统
    state_logo
      温馨提示

      已授权设备请登录到内网账号中心中的“手机邮箱”中进行管理

      如果该设备不是您的设备,您的密码可能已经泄漏,请登录到内网账号中心修改密码

      已拒绝设备请登录到内网账号中心中的“手机邮箱”中进行管理

      已经激活的设备数超出了10台的限制,请登录到内网账号中心,在“手机邮箱”中删除不再使用的设备

      更多安全知识,请访问小米安全中心

      ================================================ FILE: plugins/web/web.go ================================================ package web import ( "exchange_proxy/logger" "exchange_proxy/models" "exchange_proxy/plugins/active_sync" "encoding/json" "html/template" "net/http" ) type ( ApiData struct { Name string DeviceModel string DeviceType string DeviceId string Imei string PhoneNumber string ActiveStatus string Code string } RespData struct { Code int Data string Message string } ) func Activation(w http.ResponseWriter, r *http.Request) { _ = r.ParseForm() c := r.FormValue("c") tSync, _ := template.ParseFiles("plugins/web/templates/activeSync.html") tState, _ := template.ParseFiles("plugins/web/templates/deviceState.html") var ( deviceName string deviceMode string imei string deviceId string deviceNum int apiDate ApiData ) if c != "" { // 检查激活码 err, has, user, deviceInfo := active_sync.CheckActiveCode(c) // 激活码是存在的 if err == nil && has { // 获取当前用户的设备数 deviceNum = models.GetDeviceNum(user) deviceId = deviceInfo.DeviceId apiDate.Name = user apiDate.DeviceId = deviceId apiDate.DeviceModel = deviceInfo.DeviceType apiDate.DeviceType = deviceInfo.DeviceType apiDate.Code = c // 取出手机端通过WBXML协议获取的数据 wbxmlInfo, err := models.GetDeviceInfoByDeviceId(deviceId) if err == nil { deviceName = wbxmlInfo.FriendlyName deviceName = wbxmlInfo.Model imei = wbxmlInfo.IMEI phone := wbxmlInfo.PhoneNumber apiDate.DeviceModel = deviceMode apiDate.Imei = imei apiDate.DeviceType = deviceName apiDate.PhoneNumber = phone } CodeStatus := deviceInfo.State deviceStatue := models.GetDeviceState(user, deviceId) logger.Log.Infof("user: %v, deviceId: %v, CodeStatus: %v, deviceStatue: %v", user, deviceId, CodeStatus, deviceStatue) switch CodeStatus { case 0: // 显示已激活的状态页面 if deviceStatue == 0 { apiDate.ActiveStatus = "STATE_ACTIVED" _ = tState.Execute(w, apiDate) // 显示已拒绝状态的页面 } else if deviceStatue == 3 { apiDate.ActiveStatus = "STATE_REJECTED" _ = tState.Execute(w, apiDate) } default: // 激活的设备数已经超过10个 if deviceNum >= 10 { apiDate.ActiveStatus = "STATE_EXCEED" _ = tState.Execute(w, apiDate) } else { // 显示激活页面 _ = tSync.Execute(w, apiDate) } } } else { // 激活码不存在 apiDate.ActiveStatus = "STATE_INVALID" _ = tState.Execute(w, apiDate) } } else { // 激活码为空 apiDate.ActiveStatus = "STATE_INVALID" _ = tState.Execute(w, apiDate) } } func ActiveDevice(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { _ = r.ParseForm() c := r.FormValue("c") respData := RespData{Code: 500, Data: "", Message: "设备不存在"} if c != "" { result, user, device := active_sync.VerifyActiveCode(c) if result { _ = models.ActiveDevice(user, device.DeviceId) _, _ = active_sync.ResetActiveCodeStatus(c, user, device, 0) respData.Code = 200 respData.Message = "已经允许设备访问" } } data, _ := json.Marshal(respData) _, _ = w.Write(data) } } func IgnoreDevice(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { _ = r.ParseForm() c := r.FormValue("c") respData := RespData{Code: 500, Data: "", Message: "设备不存在"} if c != "" { result, user, device := active_sync.VerifyActiveCode(c) if result { _ = models.IgnoreDevice(user, device.DeviceId) _, _ = active_sync.ResetActiveCodeStatus(c, user, device, 3) respData.Code = 200 respData.Message = "已忽略该设备" } } data, _ := json.Marshal(respData) _, _ = w.Write(data) } } func NotFound(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) } ================================================ FILE: settings/settings.go ================================================ package settings import ( "exchange_proxy/logger" "gopkg.in/ini.v1" ) var ( Cfg *ini.File ) func init() { var err error source := "conf/app.ini" Cfg, err = ini.Load(source) if err != nil { logger.Log.Panicln(err) } } ================================================ FILE: util/http_client.go ================================================ package util import ( "encoding/json" "io/ioutil" "net/http" "net/url" ) type TokenResult struct { Code int `json:"code"` Data string `json:"data"` } func CheckToken(urlOtp, username, token string) (result bool, err error) { users := make([]string, 0) users = append(users, username) tokens := make([]string, 0) tokens = append(tokens, token) resp, err := http.PostForm(urlOtp, url.Values{"username": users, "verificationCode": tokens}) if err == nil { defer resp.Body.Close() ret, err := ioutil.ReadAll(resp.Body) if err == nil { tokenResult := TokenResult{} err = json.Unmarshal(ret, &tokenResult) if err == nil { if tokenResult.Code == 200 && tokenResult.Data == "success" { result = true } } } } return result, err } ================================================ FILE: util/lib.go ================================================ package util import ( "crypto/md5" "fmt" "io" "math/rand" "time" ) // md5 func MD5(s string) (m string) { h := md5.New() _, _ = io.WriteString(h, s) return fmt.Sprintf("%x", h.Sum(nil)) } // 生成固定的随机字符串 func RandomString(n int) string { var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") b := make([]rune, n) for i := range b { b[i] = letter[rand.Intn(len(letter))] } return string(b) } // 生成激活码 func GenerateAtiveCode(username, deviceId string) (code string) { randString := RandomString(10) t := fmt.Sprintf("%v%v%v%v", username, deviceId, randString, time.Now().UnixNano()) code = MD5(t)[5:17] return code } ================================================ FILE: util/wbxml/wbxml.go ================================================ package wbxml import ( "bytes" "encoding/xml" "regexp" "exchange_proxy/logger" . "github.com/magicmonty/activesync-go/activesync" . "github.com/magicmonty/activesync-go/activesync/base" . "github.com/magicmonty/wbxml-go/wbxml" ) /* ``` MIX 2 888833336669999 MIX 2 Android 8.0.0 +8618599999999 Android/8.0.0-EAS-1.3 中国联通 (46001) MS-EAS-Provisioning-WBXML ``` */ type ( Provision struct { XMLName xml.Name `xml:"Provision"` Text string `xml:",chardata"` O string `xml:"O,attr"` S string `xml:"S,attr"` DeviceInformation struct { Text string `xml:",chardata"` Set struct { Text string `xml:",chardata"` Model string `xml:"Model"` IMEI string `xml:"IMEI"` FriendlyName string `xml:"FriendlyName"` OS string `xml:"OS"` PhoneNumber string `xml:"PhoneNumber"` UserAgent string `xml:"UserAgent"` MobileOperator string `xml:"MobileOperator"` } `xml:"Set"` } `xml:"DeviceInformation"` Policies struct { Text string `xml:",chardata"` Policy struct { Text string `xml:",chardata"` PolicyType string `xml:"PolicyType"` } `xml:"Policy"` } `xml:"Policies"` } DeviceInfo struct { Model string `json:"model"` IMEI string `json:"imei"` FriendlyName string `json:"friendly_name"` PhoneNumber string `json:"phone_number"` MobileOperator string `json:"mobile_operator"` } ) func removeInvalidChars(b []byte) []byte { re := regexp.MustCompile("[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]") return re.ReplaceAll(b, []byte{}) } func EncodeXML(xmlString []byte) { xmlString = removeInvalidChars([]byte(xmlString)) w := bytes.NewBuffer(make([]byte, 0)) e := NewEncoder( MakeCodeBook(PROTOCOL_VERSION_14_1), string(xmlString), w) err := e.Encode() if err != nil { logger.Log.Println(err.Error()) } else { logger.Log.Println(w) } } func getDecodeResult(data ...byte) string { var result string result, _ = Decode(bytes.NewBuffer(data), MakeCodeBook(PROTOCOL_VERSION_14_1)) return result } func Parse(data []byte) (deviceInfo DeviceInfo, err error) { xmldata := getDecodeResult(data...) out := Provision{} err = xml.Unmarshal([]byte(xmldata), &out) if err == nil { logger.Log.Debugf("Model: %v", out.DeviceInformation.Set.Model) logger.Log.Debugf("Imie: %v", out.DeviceInformation.Set.IMEI) logger.Log.Debugf("FriendlyName: %v", out.DeviceInformation.Set.FriendlyName) logger.Log.Debugf("PhoneNumber: %v", out.DeviceInformation.Set.PhoneNumber) logger.Log.Debugf("MobileOperator: %v", out.DeviceInformation.Set.MobileOperator) deviceInfo.Model = out.DeviceInformation.Set.Model deviceInfo.IMEI = out.DeviceInformation.Set.IMEI deviceInfo.FriendlyName = out.DeviceInformation.Set.FriendlyName deviceInfo.PhoneNumber = out.DeviceInformation.Set.PhoneNumber deviceInfo.MobileOperator = out.DeviceInformation.Set.MobileOperator } return deviceInfo, err } ================================================ FILE: vars/vars.go ================================================ package vars import ( "exchange_proxy/logger" "exchange_proxy/settings" "path/filepath" "strings" "github.com/go-redis/redis" "github.com/sirupsen/logrus" "github.com/vulcand/oxy/forward" ) type ( Config struct { Host []string Backend string Port int TLS bool Cert string Key string DebugLevel string } RedisConfig struct { Host string Port int Db int Password string } ) var ( FwdOWA *forward.Forwarder FwdSync *forward.Forwarder RedisInstance *redis.Client MailConfig Config RedisConf RedisConfig RequestCmds = make(map[string]bool) ResponseCmds = make(map[string]bool) CurDir string ) // 代理用到的API接口的信息 var ( // 用户激活的URL ActiveUrl string //OTP接口 OtpUrl string // 短信接口的URL,header头名称与值 SmsApiUrl string SmsApiHeader string SmsApiKey string // 根据用户名查找手机号的接口的URL UserPhoneUrl string ) func init() { sec := settings.Cfg.Section("mail") hosts := sec.Key("hosts").MustString("mail.xsec.io") MailConfig.Host = strings.Split(hosts, ",") MailConfig.Port = sec.Key("port").MustInt(443) MailConfig.Backend = sec.Key("backend").MustString("https://8.8.8.8") MailConfig.TLS = sec.Key("ssl").MustBool(true) MailConfig.Cert = sec.Key("cert").MustString("certs/ca.crt") MailConfig.Key = sec.Key("key").MustString("certs/ca.key") MailConfig.DebugLevel = sec.Key("debug_level").MustString("info") secRedis := settings.Cfg.Section("redis") RedisConf.Host = secRedis.Key("host").MustString("127.0.0.1") RedisConf.Port = secRedis.Key("port").MustInt(6379) RedisConf.Db = secRedis.Key("db").MustInt(0) RedisConf.Password = secRedis.Key("password").MustString("passw0rd") FwdOWA, _ = forward.New() FwdSync, _ = forward.New() // 获取当前目录 CurDir, _ = GetCurDir() // 初始化过滤指令列表 initActiveSyncCmds() // 初始化代理用的到API接口的值 initApiInfo() // 初始化日志级别 initDebugLevel() logger.Log.Printf("host: %v, port: %v, ssl: %v, path: %v", strings.Join(MailConfig.Host, ","), MailConfig.Port, MailConfig.TLS, CurDir) } // 手机端未激活前的过滤指令列表 func initActiveSyncCmds() { // 请求的指令 RequestCmds["SendMail"] = true RequestCmds["FolderCreate"] = true RequestCmds["FolderDelete"] = true RequestCmds["FolderUpdate"] = true RequestCmds["MeetingResponse"] = true RequestCmds["ItemOperations"] = true RequestCmds["SmartForward"] = true RequestCmds["SmartReply"] = true RequestCmds["MoveItems"] = true // 响应的指令 ResponseCmds["Sync"] = true ResponseCmds["Search"] = true ResponseCmds["GetAttachment"] = true ResponseCmds["GetItemEstimate"] = true ResponseCmds["MeetingResponse"] = true } // 初始化API接口的值 func initApiInfo() { sec := settings.Cfg.Section("otp") OtpUrl = sec.Key("url").MustString("") sec = settings.Cfg.Section("sms") SmsApiUrl = sec.Key("url").MustString("") SmsApiHeader = sec.Key("header").MustString("") SmsApiKey = sec.Key("key").MustString("") secUserInfo := settings.Cfg.Section("user_info") UserPhoneUrl = secUserInfo.Key("user_phone").MustString("") ActiveUrl = secUserInfo.Key("active_url").MustString("") } // 初始化log的级别 func initDebugLevel() { level := strings.ToLower(MailConfig.DebugLevel) switch level { case "info": logger.Log.Logger.SetLevel(logrus.InfoLevel) case "debug": logger.Log.Logger.SetLevel(logrus.DebugLevel) case "warn": logger.Log.Logger.SetLevel(logrus.WarnLevel) case "error": logger.Log.Logger.SetLevel(logrus.ErrorLevel) case "fatal": logger.Log.Logger.SetLevel(logrus.FatalLevel) default: logger.Log.Logger.SetLevel(logrus.InfoLevel) } } func GetCurDir() (path string, err error) { path, err = filepath.Abs(".") return path, err }