├── .github
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
└── ISSUE_TEMPLATE.md
├── .gitignore
├── LICENSE
├── README.md
├── README_CN.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── me
│ │ └── ele
│ │ └── demo
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── me
│ │ │ └── ele
│ │ │ └── trojan
│ │ │ └── demo
│ │ │ ├── CustomApplication.java
│ │ │ ├── DemoHook.java
│ │ │ ├── HttpRecordHelper.java
│ │ │ ├── MainActivity.java
│ │ │ ├── RecordRequestInterceptor.java
│ │ │ └── upload
│ │ │ └── DemoLeanCloudUploader.java
│ └── res
│ │ ├── color
│ │ └── selector_blue.xml
│ │ ├── drawable-xxhdpi
│ │ ├── tab_explore.png
│ │ ├── tab_explore_normal.png
│ │ ├── tab_home.png
│ │ ├── tab_home_normal.png
│ │ ├── tab_profile.png
│ │ └── tab_profile_normal.png
│ │ ├── drawable
│ │ ├── selector_menu_home.xml
│ │ ├── selector_tab_article.xml
│ │ └── selector_tab_mine.xml
│ │ ├── layout
│ │ ├── activity_list_view.xml
│ │ ├── activity_main.xml
│ │ ├── activity_recycle_view.xml
│ │ ├── activity_view_pager.xml
│ │ ├── activity_write_file2.xml
│ │ ├── article_frag_layout.xml
│ │ ├── custom_tab_item.xml
│ │ ├── lib_frag_layout.xml
│ │ ├── mine_frag_layout.xml
│ │ └── text_item.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── me
│ └── ele
│ └── trojan
│ └── demo
│ └── ExampleUnitTest.java
├── assets
├── trojan_banner.png
└── trojan_license.png
├── build.gradle
├── decrypt
├── trojan_decrypt.c
├── trojan_decrypt.py
└── trojan_decrypt.so
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── trojan
├── .gitignore
├── CMakeLists.txt
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── me
│ └── ele
│ └── trojan
│ └── ExampleInstrumentedTest.java
└── main
├── AndroidManifest.xml
├── cpp
├── ErrInfo.cpp
├── ErrInfo.h
├── JNIHelp.cpp
├── JNIHelp.h
├── LogWriter.cpp
├── LogWriter.h
├── Logger.h
├── tea
│ ├── TEACipher.cpp
│ ├── TEACipher.h
│ ├── base64.cpp
│ └── base64.h
└── trojan-lib.cpp
├── java
└── me
│ └── ele
│ └── trojan
│ ├── Trojan.java
│ ├── TrojanManager.java
│ ├── config
│ ├── LogConstants.java
│ ├── TrojanConfig.java
│ └── TrojanConstants.java
│ ├── executor
│ └── TrojanExecutor.java
│ ├── helper
│ ├── FileHelper.java
│ ├── PerformanceHelper.java
│ └── PermissionHelper.java
│ ├── internal
│ ├── ActivityLife.java
│ └── ExceptionHandler.java
│ ├── lancet
│ └── LancetHook.java
│ ├── listener
│ ├── PrepareUploadListener.java
│ └── WaitUploadListener.java
│ ├── log
│ └── Logger.java
│ ├── receiver
│ └── TrojanReceiver.java
│ ├── record
│ ├── ILogFormatter.java
│ ├── ILogRecorder.java
│ ├── ILogWriter.java
│ └── impl
│ │ ├── LogFormatter.java
│ │ ├── LogRecorder.java
│ │ ├── MmapLogWriter.java
│ │ └── NormalLogWriter.java
│ ├── upload
│ ├── ILogUploader.java
│ └── impl
│ │ └── LogUploader.java
│ └── utils
│ ├── AppUtils.java
│ ├── DateUtils.java
│ ├── DeviceUtils.java
│ ├── GsonUtils.java
│ ├── IOUtil.java
│ ├── NetworkUtils.java
│ ├── StringUtils.java
│ └── TagUtil.java
└── res
└── values
└── strings.xml
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at xiaofeng.zhong@ele.me. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | This document contains information and guidelines about contributing to this project.
4 | Please read it before you start participating.
5 |
6 | **Topics**
7 |
8 | * [Asking Questions](#asking-questions)
9 | * [Reporting Issues](#reporting-issues)
10 | * [Developers Certificate of Origin](#developers-certificate-of-origin)
11 |
12 | ## Asking Questions
13 |
14 | We don't use GitHub as a support forum.
15 | For any usage questions that are not specific to the project itself,
16 | please ask on [Stack Overflow](https://stackoverflow.com) instead.
17 | By doing so, you'll be more likely to quickly solve your problem,
18 | and you'll allow anyone else with the same question to find the answer.
19 | This also allows maintainers to focus on improving the project for others.
20 |
21 | ## Reporting Issues
22 |
23 | A great way to contribute to the project
24 | is to send a detailed issue when you encounter an problem.
25 | We always appreciate a well-written, thorough bug report.
26 |
27 | Check that the project issues database
28 | doesn't already include that problem or suggestion before submitting an issue.
29 | If you find a match, add a quick "+1" or "I have this problem too."
30 | Doing this helps prioritize the most common problems and requests.
31 |
32 | When reporting issues, please include the following:
33 |
34 | * The version of Xcode you're using
35 | * The version of iOS or macOS you're targeting
36 | * The full output of any stack trace or compiler error
37 | * A code snippet that reproduces the described behavior, if applicable
38 | * Any other details that would be useful in understanding the problem
39 |
40 | This information will help us review and fix your issue faster.
41 |
42 | ## Developer's Certificate of Origin
43 |
44 | By making a contribution to this project, I certify that:
45 |
46 | - (a) The contribution was created in whole or in part by me and I
47 | have the right to submit it under the open source license
48 | indicated in the file; or
49 |
50 | - (b) The contribution is based upon previous work that, to the best
51 | of my knowledge, is covered under an appropriate open source
52 | license and I have the right under that license to submit that
53 | work with modifications, whether created in whole or in part
54 | by me, under the same open source license (unless I am
55 | permitted to submit under a different license), as indicated
56 | in the file; or
57 |
58 | - (c) The contribution was provided directly to me by some other
59 | person who certified (a), (b) or (c) and I have not modified
60 | it.
61 |
62 | - (d) I understand and agree that this project and the contribution
63 | are public and that a record of the contribution (including all
64 | personal information I submit with it, including my sign-off) is
65 | maintained indefinitely and may be redistributed consistent with
66 | this project or the open source license(s) involved.
67 |
68 | ---
69 |
70 | *Some of the ideas and wording for the statements above were based on work by the [Alamofire](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md) communities. We commend them for their efforts to facilitate collaboration in their projects.*
71 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ### Check List
2 |
3 | Thanks for considering to open an issue. Before you submit your issue, please confirm these boxes are checked.
4 |
5 | - [ ] I have read the [README.md](https://github.com/ELELogistics/Trojan/blob/master/README.md), but there is no information I need.
6 | - [ ] I have searched in [existing issues](https://github.com/ELELogistics/Trojan/issues?utf8=%E2%9C%93&q=is%3Aissue), but did find a same one.
7 |
8 | ### Issue Description
9 |
10 | #### Description
11 |
12 | [Tell us about the issue]
13 |
14 | #### Reproduce
15 |
16 | [The steps to reproduce this issue. What are the parameters, where did you put your code, etc.]
17 |
18 | #### Other Comment
19 |
20 | [Add anything else here]
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | [Trojan](https://github.com/ELELogistics/Trojan) is a stable and efficient mobile lightweight log SDK that not only records general logs, such as Http, power changes, component life cycles, but also records the definition of the log, which it is useful to analysis problems through the user logs. Here is the following characteristics:
16 |
17 | * Concise API, it is easy to achieve diary record function through a few lines of code;
18 | * Use the AOP technologies [Lancet](https://github.com/eleme/lancet) SDK, it is comfortable to collect common logs, also support incremental compile;
19 | * Use mmap technology to ensure the efficiency of log records;
20 | * Scalability, developers can customize the log file to achieve the purpose of the upload;
21 | * Small traffic overhead, remote control user log file upload or not by online configuration;
22 | * High stability, it is very stable at many apps.
23 |
24 | > [中文介绍](/README_CN.md)
25 |
26 | ## Overview
27 |
28 | In the open source [Trojan](https://github.com/ELELogistics/Trojan) SDK, we have collected basic logs such as Activity and Fragment lifecycles, View Click events, network status changes, phone battery status changes, also include collecting [KLog](https://github.com/ZhaoKaiQiang/KLog) logs, if KLog is not used in the project, it can be customized according to the project specific conditions. Considering that the implementation framework for network modules is different at fact, there are [OkHttp](https://github.com/square/okhttp), [Volley](https://github.com/google/volley), [Android-Async-Http](https://github.com/loopj/android-async-http), etc. Therefore, this part of collecting network logs is not suitable for customization. Users can use [Lancet](https://github.com/eleme/lancet) to collect logs at the specific network framework. In [Demo](https://github.com/ELELogistics/Trojan/blob/master/app/src/main/java/me/ele/trojan/demo/DemoHook.java), we can achieve acquisition Http request and response functions in OkHttp, it can be used as a reference. As for business-related logs, users should collect by self.
29 |
30 | ## Installation
31 |
32 | Add in the root directory's build.gradle:
33 |
34 | ```java
35 | buildscript {
36 | dependencies {
37 | ......
38 | classpath 'me.ele:lancet-plugin:1.0.2'
39 | }
40 | }
41 | ```
42 |
43 | Add in the app directory's build.gradle:
44 |
45 | ```java
46 | apply plugin: 'me.ele.lancet'
47 |
48 | dependencies {
49 | ......
50 | provided 'me.ele:lancet-base:1.0.2'
51 | compile 'me.ele:trojan-library:0.0.5'
52 | }
53 | ```
54 |
55 | ## Use
56 |
57 | ### 1. Initialization
58 |
59 | Add in the custom Application:
60 |
61 | ```java
62 | TrojanConfig config = new TrojanConfig.Builder(this)
63 | // Set user information
64 | .userInfo("xxxx")
65 | // Set device id
66 | .deviceId("xxxx")
67 | // Set cipher key if need encry log
68 | .cipherKey("xxxx")
69 | // Optional, save log file in sdcard by default
70 | .logDir("xxxx")
71 | // Console log switch, the default is open
72 | .enableLog(true)
73 | .build();
74 | Trojan.init(config);
75 | ```
76 |
77 | Special Note:
78 |
79 | 1. The log files are stored in sdcard by default and will not be lost even if the application is uninstalled;
80 | 2. To be compatible with multiple processes, log files stored in their respective directories;
81 | 3. The log is not encrypted by default, we currently only provide TEA encryption in view for high efficiency。
82 |
83 | ### 2. Record the log
84 |
85 | Trojan provides two ways to recode log:
86 |
87 | Firstly:
88 |
89 | ```java
90 | Trojan.log("Trojan", "We have a nice day!");
91 | ```
92 |
93 | Secondly:
94 |
95 | ```java
96 | List msgList = new LinkedList <>();
97 | msgList.add("Hello Trojan!");
98 | msgList.add("We have a nice day!");
99 | msgList.add("Hello world!");
100 | Trojan.log("Trojan", msgList);
101 | ```
102 |
103 | By default, a single line log is not encrypted, and if you need to encrypt it, the following is used:
104 |
105 | ```java
106 | Trojan.log("Trojan", "We have a nice day!", true);
107 | ```
108 |
109 | ### 3. User Information
110 |
111 | When the user information changes or switch users, you can call:
112 |
113 | ```java
114 | Trojan.refreshUser("new user info");
115 | ```
116 |
117 | Of course, if the user logs out, you can pass a null value:
118 |
119 | ```java
120 | Trojan.refreshUser(null);
121 | ```
122 |
123 | ### 4. Upload Solution
124 |
125 | In [Demo](https://github.com/ELELogistics/Trojan/blob/master/app/src/main/java/me/ele/trojan/demo/upload/DemoLeanCloudUploader.java) we provided free and simple way such as [LeanCloud](https://leancloud.cn/) to upload log file, you can browse, download and download log file.
126 |
127 | ### 5. Data Decryption
128 |
129 | When we set the encryption key, we can encrypt a single log to ensure the security of sensitive data. We must decrypt the encrypted data When we analyze the log. Use the [decryption script](/decrypt/trojan_decrypt.py) as follows:
130 |
131 | 1. Compile and generate decryption SO library on MAC, The so library has been generated in the repository. This step can be omitted:
132 |
133 | ```java
134 | gcc -shared -Wl,-install_name,trojan_decrypt.so -o trojan_decrypt.so -fPIC trojan_decrypt.c
135 |
136 | ```
137 | 2. Call python script to decrypt the data on MAC, you need to pass in the decryption key and file path to be decrypted, it should be noted that the path of the python script:
138 |
139 | ```java
140 | python ./trojan_decrypt.py cipher-key cipher-file-path
141 |
142 | ```
143 |
144 | ## PS
145 |
146 | Through the above steps, you can integrate [Trojan](https://github.com/ELELogistics/Trojan) SDK to record user's log, That is very simple! If you have any questions about the use of Lancet, you can get more details by [Readme](https://github.com/eleme/lancet/blob/dev/README_zh.md).
147 |
148 | ## License
149 |
150 | 
151 |
152 | Trojan is available under the Apache-2.0 license. See the [LICENSE](/LICENSE) file for more info.
153 |
--------------------------------------------------------------------------------
/README_CN.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | [Trojan](https://github.com/ELELogistics/Trojan)是一个稳定高效的移动端轻量级日志SDK,既可以记录通用日志,比如网络请求、电量变化、页面生命周期,也可以记录自定义的日志,从而可以通过用户日志来帮助我们定位分析问题。具有以下特点:
16 |
17 | * 简洁的 API,通过几行代码就可以接入,实现日记记录功能;
18 | * 使用 AOP 技术 [Lancet](https://github.com/eleme/lancet) 框架插桩收集通用日志,并且支持增量编译;
19 | * 使用 mmap 技术,保证日记记录的高效性;
20 | * 扩展性高,开发者可以自定义日志文件的上传功能;
21 | * 流量开销小,支持在线配置,远程控制用户日志文件上传与否;
22 | * 稳定性高,目前已稳定运行在饿了么物流团队众包等多个 APP 上。
23 |
24 | > [English Introduction](/README.md)
25 |
26 | ## 综述
27 |
28 | 在开源的 [Trojan](https://github.com/ELELogistics/Trojan) SDK中,目前采集了 Activity 和 Fragment 生命周期,View Click 事件,网络状态变化,手机电量状态变化等基础日志,还通过 AOP 技术插桩 [KLog](https://github.com/ZhaoKaiQiang/KLog)采集 Log 日志,要是项目中未使用 KLog,也可以根据项目情况具体定制。考虑到每个项目中网络模块的实现框架都不尽相同,有 [OkHttp](https://github.com/square/okhttp)、[Volley](https://github.com/google/volley)、[Android-Async-Http](https://github.com/loopj/android-async-http) 等等,所以采集网络日志这一部分不方便统一处理,需要使用者通过 [Lancet](https://github.com/eleme/lancet) 插桩具体网络框架来收集日志。在 [Demo](https://github.com/ELELogistics/Trojan/blob/master/app/src/main/java/me/ele/trojan/demo/DemoHook.java) 中具体以 OkHttp 为例,实现采集 Http request 和 response 的功能,可作为参考。而与业务相关的日志,需要使用者自己采集。
29 |
30 | ## 配置
31 |
32 | 在根目录的 build.gradle 添加:
33 |
34 | ```java
35 | buildscript {
36 | dependencies {
37 | .......
38 | classpath 'me.ele:lancet-plugin:1.0.2'
39 | }
40 | }
41 | ```
42 |
43 | 在 app 目录的 'build.gradle' 添加:
44 |
45 | ```java
46 | apply plugin: 'me.ele.lancet'
47 |
48 | dependencies {
49 | ......
50 | provided 'me.ele:lancet-base:1.0.2'
51 | compile 'me.ele:trojan-library:0.0.5'
52 | }
53 | ```
54 |
55 | ## 使用
56 |
57 | ### 1. 初始化
58 |
59 | 在自定义的 `Application` 添加:
60 |
61 | ```java
62 | TrojanConfig config = new TrojanConfig.Builder(this)
63 | // Set user information
64 | .userInfo("xxxx")
65 | // Set device id
66 | .deviceId("xxxx")
67 | // Set cipher key if need encry log
68 | .cipherKey("xxxx")
69 | // Optional, save log file in sdcard by default
70 | .logDir("xxxx")
71 | // Console log switch, the default is open
72 | .enableLog(true)
73 | .build();
74 | Trojan.init(config);
75 | ```
76 |
77 | 特别说明:
78 |
79 | 1. 日志文件默认保存在 sdcard 中,即使应用被卸载,也不会丢失日志;
80 | 2. 为兼容多进程,避免文件相互干扰,日志文件保存在各自的目录下,目录以进程名来命名;
81 | 3. 默认情况下日志不加密,考虑到加密的高效性,目前仅提供TEA加密方式。
82 |
83 | ### 2. 记录日志
84 |
85 | Trojan 提供两种方式记录日志:
86 |
87 | 第一种:
88 |
89 | ```java
90 | Trojan.log("Trojan", "We have a nice day!");
91 | ```
92 |
93 | 第二种:
94 |
95 | ```java
96 | List msgList = new LinkedList<>();
97 | msgList.add("Hello Trojan!");
98 | msgList.add("We have a nice day!");
99 | msgList.add("Hello world!");
100 | Trojan.log("Trojan", msgList);
101 | ```
102 |
103 | 默认情况下,对于单行日志不加密,如果需要加密,则使用如下:
104 |
105 | ```java
106 | Trojan.log("Trojan", "We have a nice day!", true);
107 | ```
108 |
109 | ### 3. 用户信息
110 |
111 | 当用户信息发生改变或者切换用户时,可以调用:
112 |
113 | ```java
114 | Trojan.refreshUser("new user info");
115 | ```
116 |
117 | 当然了,要是用户登出,可以传空值,即表示登出操作:
118 |
119 | ```java
120 | Trojan.refreshUser(null);
121 | ```
122 |
123 | ### 4. 上传方案
124 |
125 | 针对日志上传,在 [Demo](https://github.com/ELELogistics/Trojan/blob/master/app/src/main/java/me/ele/trojan/demo/upload/DemoLeanCloudUploader.java) 中提供了 [LeanCloud](https://leancloud.cn/) 这种免费简单的方式,可以实现上传、浏览、下载等文件服务的基本功能,可供参考。
126 |
127 | ### 5. 数据解密
128 |
129 | 当设置了加密秘钥,为保证敏感数据的安全性,可以加密单行日志,在日志分析时就需要对加密数据进行解密。[解密脚本](/decrypt/trojan_decrypt.py)使用如下:
130 |
131 | 1. 在MAC上编译生成解密SO库,在仓库中已经生成了so库,这一步可以省略:
132 |
133 | ```java
134 | gcc -shared -Wl,-install_name,trojan_decrypt.so -o trojan_decrypt.so -fPIC trojan_decrypt.c
135 |
136 | ```
137 | 2. 在MAC上调用python脚本解密数据,需要传入解密秘钥和待解密的文件路径,需要注意的是python脚本的路径要对:
138 |
139 | ```java
140 | python ./trojan_decrypt.py cipher-key cipher-file-path
141 |
142 | ```
143 |
144 | ## 备注
145 |
146 | 通过集成 [Trojan](https://github.com/ELELogistics/Trojan),可以轻松实现用户日志的记录功能,是不是很简单呀!要是对 Lancet 的使用有疑问,大家可以参考 [https://github.com/eleme/lancet/blob/dev/README_zh.md](https://github.com/eleme/lancet/blob/dev/README_zh.md),这里就不赘述。
147 |
148 | ## 协议
149 |
150 | 
151 |
152 | Trojan基于Apache-2.0协议进行分发和使用,更多信息参见[协议](/LICENSE)文件。
153 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'me.ele.lancet'
3 |
4 | android {
5 |
6 | compileSdkVersion 23
7 | buildToolsVersion '25.0.2'
8 | defaultConfig {
9 | applicationId "me.ele.trojan.demo"
10 | minSdkVersion 15
11 | targetSdkVersion 23
12 | versionCode 1
13 | versionName "1.0"
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | debug {
22 | debuggable true
23 | jniDebuggable true
24 | }
25 | }
26 | lintOptions {
27 | abortOnError false
28 | }
29 | }
30 |
31 | dependencies {
32 | testCompile 'junit:junit:4.12'
33 | compile fileTree(include: ['*.jar'], dir: 'libs')
34 | compile 'com.android.support.constraint:constraint-layout:1.0.2'
35 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
36 | exclude group: 'com.android.support', module: 'support-annotations'
37 | })
38 |
39 | compile 'com.android.support:design:23.4.0'
40 | compile 'com.android.support:recyclerview-v7:23.4.0'
41 | compile 'com.android.support:appcompat-v7:23.4.0'
42 |
43 | compile 'cn.leancloud.android:avoscloud-sdk:v4.4.4'
44 | compile "com.squareup.retrofit2:converter-gson:2.0.1"
45 |
46 | provided "me.ele:lancet-base:1.0.2"
47 |
48 | compile project(':trojan')
49 | //compile 'me.ele:trojan-library:0.0.2'
50 |
51 | //debugCompile project(path: ':trojan', configuration: 'debug')
52 | //releaseCompile project(path: ':trojan', configuration: 'release')
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/eleme/Downloads/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/me/ele/demo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package me.ele.demo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will executeRecord on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("me.ele.trojantest", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/me/ele/trojan/demo/CustomApplication.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo;
2 |
3 | import android.app.Application;
4 | import android.os.Environment;
5 |
6 | import me.ele.trojan.Trojan;
7 | import me.ele.trojan.config.TrojanConfig;
8 |
9 | /**
10 | * Created by wangallen on 2017/6/7.
11 | */
12 |
13 | public class CustomApplication extends Application {
14 |
15 | @Override
16 | public void onCreate() {
17 | super.onCreate();
18 |
19 | TrojanConfig config = new TrojanConfig.Builder(this)
20 | .userInfo("520")
21 | .deviceId("726e78ec-c351-3a52-ac02-ec04e689a9f3")
22 | .enableLog(true)
23 | .cipherKey("1234567890abcdef")
24 | .build();
25 | Trojan.init(config);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/me/ele/trojan/demo/DemoHook.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo;
2 |
3 | import android.util.Log;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | import me.ele.lancet.base.Origin;
9 | import me.ele.lancet.base.annotations.Insert;
10 | import me.ele.lancet.base.annotations.NameRegex;
11 | import me.ele.lancet.base.annotations.Proxy;
12 | import me.ele.lancet.base.annotations.TargetClass;
13 | import me.ele.trojan.Trojan;
14 | import me.ele.trojan.log.Logger;
15 | import okhttp3.Interceptor;
16 | import okhttp3.Response;
17 |
18 | /**
19 | * Created by michaelzhong on 2017/12/26.
20 | */
21 |
22 | public class DemoHook {
23 |
24 | @Proxy("e")
25 | @TargetClass("android.util.Log")
26 | public static int e(String tag, String msg) {
27 | Trojan.log(tag, msg);
28 | return (int) Origin.call();
29 | }
30 |
31 |
32 | @TargetClass("okhttp3.OkHttpClient")
33 | @NameRegex("okhttp3/RealCall")
34 | @Proxy("interceptors")
35 | public List networkInterceptors() {
36 | // record the http request
37 | Logger.i("networkInterceptors");
38 | List interceptors = (List) Origin.call();
39 | List newList = new ArrayList<>(interceptors.size() + 1);
40 | newList.addAll(interceptors);
41 | newList.add(new RecordRequestInterceptor());
42 | return newList;
43 | }
44 |
45 | @Insert("getResponseWithInterceptorChain")
46 | @TargetClass(value = "okhttp3.RealCall")
47 | private Response getResponseWithInterceptorChain() throws Throwable {
48 | // record the http response
49 | Logger.i("getResponseWithInterceptorChain");
50 | Response response = (Response) Origin.call();
51 | try {
52 | HttpRecordHelper.recordResponse(response);
53 | } catch (Exception ex) {
54 | ex.printStackTrace();
55 | }
56 | return response;
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/app/src/main/java/me/ele/trojan/demo/HttpRecordHelper.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo;
2 |
3 | import java.io.EOFException;
4 | import java.io.IOException;
5 | import java.nio.charset.Charset;
6 | import java.util.LinkedList;
7 | import java.util.List;
8 |
9 | import me.ele.trojan.Trojan;
10 | import me.ele.trojan.log.Logger;
11 | import okhttp3.MediaType;
12 | import okhttp3.Request;
13 | import okhttp3.Response;
14 | import okhttp3.ResponseBody;
15 | import okio.Buffer;
16 | import okio.BufferedSource;
17 |
18 | /**
19 | * Created by panda on 2017/12/12.
20 | */
21 |
22 | public class HttpRecordHelper {
23 |
24 | private static final Charset UTF8 = Charset.forName("UTF-8");
25 |
26 | public static void recordRequest(Request request) {
27 | String method = request.method();
28 | String url = request.url().toString();
29 | Logger.i("recordRequest-->method:" + method + ",url:" + url);
30 | List msgList = new LinkedList<>();
31 | msgList.add(method);
32 | msgList.add(url);
33 | Trojan.log("TrojanRequest", msgList);
34 | }
35 |
36 | public static Response recordResponse(Response response) throws IOException {
37 | ResponseBody responseBody = response.body();
38 | long contentLength = responseBody.contentLength();
39 |
40 | BufferedSource source = responseBody.source();
41 | source.request(Long.MAX_VALUE); // Buffer the entire body.
42 | Buffer buffer = source.buffer();
43 |
44 | Charset charset = UTF8;
45 | MediaType contentType = responseBody.contentType();
46 | if (contentType != null) {
47 | charset = contentType.charset(UTF8);
48 | }
49 |
50 | List msgList = new LinkedList<>();
51 | msgList.add(response.request().method());
52 | msgList.add(response.request().url().toString());
53 |
54 | if (isPlaintext(buffer) && contentLength != 0) {
55 | msgList.add(buffer.clone().readString(charset));
56 | } else {
57 | msgList.add("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
58 | }
59 | Trojan.log("TrojanResponse", msgList);
60 |
61 | return response;
62 | }
63 |
64 | /**
65 | * Returns true if the body in question probably contains human readable text. Uses a small sample
66 | * of code points to detect unicode control characters commonly used in binary file signatures.
67 | */
68 | private static boolean isPlaintext(Buffer buffer) {
69 | try {
70 | Buffer prefix = new Buffer();
71 | long byteCount = buffer.size() < 64 ? buffer.size() : 64;
72 | buffer.copyTo(prefix, 0, byteCount);
73 | for (int i = 0; i < 16; i++) {
74 | if (prefix.exhausted()) {
75 | break;
76 | }
77 | int codePoint = prefix.readUtf8CodePoint();
78 | if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
79 | return false;
80 | }
81 | }
82 | return true;
83 | } catch (EOFException e) {
84 | return false; // Truncated UTF-8 sequence.
85 | }
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/app/src/main/java/me/ele/trojan/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo;
2 |
3 | import android.Manifest;
4 | import android.content.pm.PackageManager;
5 | import android.os.Bundle;
6 | import android.support.v4.app.ActivityCompat;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.view.View;
9 |
10 | import java.io.File;
11 | import java.io.IOException;
12 | import java.util.List;
13 |
14 | import me.ele.trojan.Trojan;
15 | import me.ele.trojan.demo.upload.DemoLeanCloudUploader;
16 | import me.ele.trojan.listener.WaitUploadListener;
17 | import me.ele.trojan.log.Logger;
18 | import me.ele.trojan.utils.DateUtils;
19 |
20 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
21 |
22 | private static final String TAG = "Trojan";
23 |
24 | private static final int REQUEST_WRITE_PERMISSION_CODE = 888;
25 |
26 | private static final String DEMO_USER_A = "520";
27 |
28 | private static final String DEMO_USER_B = "214";
29 |
30 | private String trojanUser = DEMO_USER_A;
31 |
32 | private DemoLeanCloudUploader uploader;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | setContentView(R.layout.activity_main);
38 |
39 | requestWritePermissions();
40 |
41 | uploader = new DemoLeanCloudUploader(this);
42 |
43 | findViewById(R.id.btn_request_permission).setOnClickListener(this);
44 | findViewById(R.id.btn_write_log).setOnClickListener(this);
45 | findViewById(R.id.btn_write_big_log).setOnClickListener(this);
46 | findViewById(R.id.btn_write_encrypt_log).setOnClickListener(this);
47 | findViewById(R.id.btn_change_user).setOnClickListener(this);
48 | findViewById(R.id.btn_upload_log_file).setOnClickListener(this);
49 | findViewById(R.id.btn_get_log_by_date).setOnClickListener(this);
50 | }
51 |
52 | private void requestWritePermissions() {
53 | int hasWritePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
54 | if (hasWritePermission != PackageManager.PERMISSION_GRANTED) {
55 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION_CODE);
56 | return;
57 | } else {
58 | Logger.e(TAG, "permission granted");
59 | }
60 | }
61 |
62 | @Override
63 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
64 | switch (requestCode) {
65 | case REQUEST_WRITE_PERMISSION_CODE:
66 | Logger.e(TAG, "got writer permission now");
67 | break;
68 | }
69 | }
70 |
71 | @Override
72 | public void onClick(View v) {
73 | final int viewId = v.getId();
74 | if (viewId == R.id.btn_request_permission) {
75 | requestWritePermissions();
76 | } else if (viewId == R.id.btn_write_log) {
77 | Trojan.log(TAG, "Have a nice day from Trojan!");
78 | } else if (viewId == R.id.btn_write_big_log) {
79 | for (int i = 0; i < 10000; i++) {
80 | Trojan.log(TAG, "Have a nice day from Trojan by " + (i + 1) + "!");
81 | }
82 | } else if (viewId == R.id.btn_write_encrypt_log) {
83 | Trojan.log(TAG, 1, "Have a nice day from Trojan, 饿了么物流移动组!", true);
84 | } else if (viewId == R.id.btn_change_user) {
85 | if (trojanUser.equals(DEMO_USER_A)) {
86 | trojanUser = DEMO_USER_B;
87 | } else {
88 | trojanUser = DEMO_USER_A;
89 | }
90 | Trojan.refreshUser(trojanUser);
91 | } else if (viewId == R.id.btn_upload_log_file) {
92 | Trojan.prepareUploadLogFileAsync(new WaitUploadListener() {
93 | @Override
94 | public void onReadyToUpload(final String user, final String device, final List waitUploadFileList) {
95 | Logger.e("MainActivity->onReadyToUpload:" + waitUploadFileList);
96 | if (waitUploadFileList == null || waitUploadFileList.size() == 0) {
97 | return;
98 | }
99 | new Thread() {
100 | @Override
101 | public void run() {
102 | for (File logFile : waitUploadFileList) {
103 | try {
104 | uploader.uploadLogFile(user, device, logFile);
105 | } catch (IOException e) {
106 | e.printStackTrace();
107 | } catch (Exception e) {
108 | e.printStackTrace();
109 | }
110 | }
111 | }
112 | }.start();
113 | }
114 |
115 | @Override
116 | public void onReadyFail() {
117 | Logger.e("MainActivity->onReadyFail");
118 | }
119 | });
120 | } else if (viewId == R.id.btn_get_log_by_date) {
121 | new Thread() {
122 | @Override
123 | public void run() {
124 | Logger.e("MainActivity->2018-04-01:" + Trojan.prepareUploadLogFileSync("2018-04-01"));
125 | Logger.e("MainActivity->2018-05-01:" + Trojan.prepareUploadLogFileSync("2018-05-01"));
126 | Logger.e("MainActivity->2018-04-08:" + Trojan.prepareUploadLogFileSync("2018-04-08"));
127 | Logger.e("MainActivity->2018-04-10:" + Trojan.prepareUploadLogFileSync(DateUtils.getDate()));
128 | }
129 | }.start();
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/app/src/main/java/me/ele/trojan/demo/RecordRequestInterceptor.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo;
2 |
3 | import java.io.IOException;
4 |
5 | import okhttp3.Interceptor;
6 | import okhttp3.Request;
7 | import okhttp3.Response;
8 |
9 | /**
10 | * Created by panda on 2017/12/19.
11 | */
12 |
13 | public class RecordRequestInterceptor implements Interceptor {
14 | @Override
15 | public Response intercept(Chain chain) throws IOException {
16 | Request request = chain.request();
17 | HttpRecordHelper.recordRequest(request);
18 | return chain.proceed(request);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/java/me/ele/trojan/demo/upload/DemoLeanCloudUploader.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo.upload;
2 |
3 | import android.content.Context;
4 | import android.text.TextUtils;
5 |
6 | import com.avos.avoscloud.AVException;
7 | import com.avos.avoscloud.AVFile;
8 | import com.avos.avoscloud.AVOSCloud;
9 |
10 | import java.io.File;
11 | import java.io.FileNotFoundException;
12 |
13 | import me.ele.trojan.config.TrojanConstants;
14 | import me.ele.trojan.log.Logger;
15 |
16 | /**
17 | * Created by michaelzhong on 2017/11/7.
18 | */
19 |
20 | public class DemoLeanCloudUploader {
21 |
22 | private static final String APPLICATION_ID = "gtzw5LbEtLc3OyXBodNKdsnU-gzGzoHsz";
23 |
24 | private static final String CLIENT_KEY = "QC72vlbV7m06lsfuJeCz0uiB";
25 |
26 | public DemoLeanCloudUploader(Context context) {
27 | AVOSCloud.initialize(context, APPLICATION_ID, CLIENT_KEY);
28 | }
29 |
30 | public void uploadLogFile(String user, String device, File gzFile) throws Exception {
31 | Logger.i("DemoLeanCloudUploader-->uploadLogFile,gzFile:" + gzFile);
32 | if (gzFile == null || !gzFile.isFile()) {
33 | Logger.e("DemoLeanCloudUploader-->uploadLogFile,not exists");
34 | return;
35 | }
36 | String leanCloudFileName = getLeanCloudFileName(user, device, gzFile.getName());
37 | Logger.i("DemoLeanCloudUploader-->uploadLogFile,leanCloudFileName:" + leanCloudFileName);
38 | try {
39 | AVFile avFile = AVFile.withAbsoluteLocalPath(leanCloudFileName, gzFile.getAbsolutePath());
40 | avFile.save();
41 | gzFile.delete();
42 | Logger.i("DemoLeanCloudUploader-->uploadLogFile,success");
43 | } catch (FileNotFoundException ex) {
44 | ex.printStackTrace();
45 | throw ex;
46 | } catch (AVException avException) {
47 | avException.printStackTrace();
48 | throw avException;
49 | }
50 | }
51 |
52 | private String getLeanCloudFileName(String user, String device, String logFileName) {
53 | StringBuilder fileNameBuilder = new StringBuilder();
54 | if (!TextUtils.isEmpty(user)) {
55 | fileNameBuilder.append(user);
56 | fileNameBuilder.append("-");
57 | }
58 | fileNameBuilder.append(logFileName.replace(TrojanConstants.GZ, ""));
59 | if (!TextUtils.isEmpty(device)) {
60 | fileNameBuilder.append("-");
61 | fileNameBuilder.append(device);
62 | }
63 | fileNameBuilder.append(TrojanConstants.GZ);
64 | return fileNameBuilder.toString();
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/app/src/main/res/color/selector_blue.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/tab_explore.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/drawable-xxhdpi/tab_explore.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/tab_explore_normal.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/drawable-xxhdpi/tab_explore_normal.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/tab_home.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/drawable-xxhdpi/tab_home.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/tab_home_normal.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/drawable-xxhdpi/tab_home_normal.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/tab_profile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/drawable-xxhdpi/tab_profile.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/tab_profile_normal.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/drawable-xxhdpi/tab_profile_normal.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/selector_menu_home.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/selector_tab_article.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/selector_tab_mine.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_list_view.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
15 |
16 |
20 |
21 |
26 |
27 |
32 |
33 |
38 |
39 |
44 |
45 |
50 |
51 |
56 |
57 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_recycle_view.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_view_pager.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_write_file2.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
14 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/article_frag_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/custom_tab_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/lib_frag_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/mine_frag_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/text_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 | #3F51B5
8 | #303F9F
9 |
10 | #FF4081
11 |
12 | #0000
13 |
14 | #000
15 |
16 | #fff
17 |
18 | #999
19 |
20 | #0a74ac
21 |
22 | #1296db
23 |
24 | #1296db
25 | #8A8A8A
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Trojan Demo
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/me/ele/trojan/demo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.demo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | /**
8 | * Example local unit test, which will executeRecord on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/assets/trojan_banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/assets/trojan_banner.png
--------------------------------------------------------------------------------
/assets/trojan_license.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/assets/trojan_license.png
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | maven {
7 | url 'https://maven.google.com/'
8 | name 'Google'
9 | }
10 | maven {
11 | url "http://mvn.leancloud.cn/nexus/content/repositories/public"
12 | }
13 | }
14 | dependencies {
15 | classpath 'com.android.tools.build:gradle:2.3.3'
16 | classpath 'me.ele:lancet-plugin:1.0.2'
17 | classpath 'com.novoda:bintray-release:0.3.4'
18 | }
19 | }
20 |
21 | allprojects {
22 | repositories {
23 | jcenter()
24 | maven {
25 | url 'https://maven.google.com/'
26 | name 'Google'
27 | }
28 | maven {
29 | url "http://mvn.leancloud.cn/nexus/content/repositories/public"
30 | }
31 | }
32 | }
33 |
34 | task clean(type: Delete) {
35 | delete rootProject.buildDir
36 | }
37 |
--------------------------------------------------------------------------------
/decrypt/trojan_decrypt.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | //#include "base64.cpp"
7 |
8 | static const char b64_table[] = {
9 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
10 | 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
11 | 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
12 | 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
13 | 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
14 | 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
15 | 'w', 'x', 'y', 'z', '0', '1', '2', '3',
16 | '4', '5', '6', '7', '8', '9', '+', '/'
17 | };
18 |
19 | #ifndef b64_malloc
20 | # define b64_malloc(ptr) malloc(ptr)
21 | #endif
22 | #ifndef b64_realloc
23 | # define b64_realloc(ptr, size) realloc(ptr, size)
24 | #endif
25 |
26 | /**
27 | * Encode `unsigned char *' source with `size_t' size.
28 | * Returns a `char *' base64 encoded string.
29 | */
30 |
31 | char *b64_encode(const unsigned char *, size_t);
32 |
33 | /**
34 | * Dencode `char *' source with `size_t' size.
35 | * Returns a `unsigned char *' base64 decoded string.
36 | */
37 | unsigned char *b64_decode(const char *, size_t);
38 |
39 | /**
40 | * Dencode `char *' source with `size_t' size.
41 | * Returns a `unsigned char *' base64 decoded string + size of decoded string.
42 | */
43 | unsigned char *b64_decode_ex(const char *, size_t, size_t *);
44 |
45 | char *b64_encode(const unsigned char *src, size_t len) {
46 | int i = 0;
47 | int j = 0;
48 | char *enc = NULL;
49 | size_t size = 0;
50 | unsigned char buf[4];
51 | unsigned char tmp[3];
52 |
53 | // alloc
54 | enc = (char *) b64_malloc(1);
55 | if (NULL == enc) { return NULL; }
56 |
57 | // parse until end of source
58 | while (len--) {
59 | // read up to 3 bytes at a time into `tmp'
60 | tmp[i++] = *(src++);
61 |
62 | // if 3 bytes read then encode into `buf'
63 | if (3 == i) {
64 | buf[0] = (tmp[0] & 0xfc) >> 2;
65 | buf[1] = ((tmp[0] & 0x03) << 4) + ((tmp[1] & 0xf0) >> 4);
66 | buf[2] = ((tmp[1] & 0x0f) << 2) + ((tmp[2] & 0xc0) >> 6);
67 | buf[3] = tmp[2] & 0x3f;
68 |
69 | // allocate 4 new byts for `enc` and
70 | // then translate each encoded buffer
71 | // part by index from the base 64 index table
72 | // into `enc' unsigned char array
73 | enc = (char *) b64_realloc(enc, size + 4);
74 | for (i = 0; i < 4; ++i) {
75 | enc[size++] = b64_table[buf[i]];
76 | }
77 |
78 | // reset index
79 | i = 0;
80 | }
81 | }
82 |
83 | // remainder
84 | if (i > 0) {
85 | // fill `tmp' with `\0' at most 3 times
86 | for (j = i; j < 3; ++j) {
87 | tmp[j] = '\0';
88 | }
89 |
90 | // perform same codec as above
91 | buf[0] = (tmp[0] & 0xfc) >> 2;
92 | buf[1] = ((tmp[0] & 0x03) << 4) + ((tmp[1] & 0xf0) >> 4);
93 | buf[2] = ((tmp[1] & 0x0f) << 2) + ((tmp[2] & 0xc0) >> 6);
94 | buf[3] = tmp[2] & 0x3f;
95 |
96 | // perform same write to `enc` with new allocation
97 | for (j = 0; (j < i + 1); ++j) {
98 | enc = (char *) b64_realloc(enc, size + 1);
99 | enc[size++] = b64_table[buf[j]];
100 | }
101 |
102 | // while there is still a remainder
103 | // append `=' to `enc'
104 | while ((i++ < 3)) {
105 | enc = (char *) b64_realloc(enc, size + 1);
106 | enc[size++] = '=';
107 | }
108 | }
109 |
110 | // Make sure we have enough space to add '\0' character at end.
111 | enc = (char *) b64_realloc(enc, size + 1);
112 | enc[size] = '\0';
113 |
114 | return enc;
115 | }
116 |
117 | unsigned char *b64_decode(const char *src, size_t len) {
118 | return b64_decode_ex(src, len, NULL);
119 | }
120 |
121 | unsigned char *
122 | b64_decode_ex(const char *src, size_t len, size_t *decsize) {
123 | int i = 0;
124 | int j = 0;
125 | int l = 0;
126 | size_t size = 0;
127 | unsigned char *dec = NULL;
128 | unsigned char buf[3];
129 | unsigned char tmp[4];
130 |
131 | // alloc
132 | dec = (unsigned char *) b64_malloc(1);
133 | if (NULL == dec) { return NULL; }
134 |
135 | // parse until end of source
136 | while (len--) {
137 | // break if char is `=' or not base64 char
138 | if ('=' == src[j]) { break; }
139 | if (!(isalnum(src[j]) || '+' == src[j] || '/' == src[j])) { break; }
140 |
141 | // read up to 4 bytes at a time into `tmp'
142 | tmp[i++] = src[j++];
143 |
144 | // if 4 bytes read then decode into `buf'
145 | if (4 == i) {
146 | // translate values in `tmp' from table
147 | for (i = 0; i < 4; ++i) {
148 | // find translation char in `b64_table'
149 | for (l = 0; l < 64; ++l) {
150 | if (tmp[i] == b64_table[l]) {
151 | tmp[i] = l;
152 | break;
153 | }
154 | }
155 | }
156 |
157 | // decode
158 | buf[0] = (tmp[0] << 2) + ((tmp[1] & 0x30) >> 4);
159 | buf[1] = ((tmp[1] & 0xf) << 4) + ((tmp[2] & 0x3c) >> 2);
160 | buf[2] = ((tmp[2] & 0x3) << 6) + tmp[3];
161 |
162 | // write decoded buffer to `dec'
163 | dec = (unsigned char *) b64_realloc(dec, size + 3);
164 | if (dec != NULL) {
165 | for (i = 0; i < 3; ++i) {
166 | dec[size++] = buf[i];
167 | }
168 | } else {
169 | return NULL;
170 | }
171 |
172 | // reset
173 | i = 0;
174 | }
175 | }
176 |
177 | // remainder
178 | if (i > 0) {
179 | // fill `tmp' with `\0' at most 4 times
180 | for (j = i; j < 4; ++j) {
181 | tmp[j] = '\0';
182 | }
183 |
184 | // translate remainder
185 | for (j = 0; j < 4; ++j) {
186 | // find translation char in `b64_table'
187 | for (l = 0; l < 64; ++l) {
188 | if (tmp[j] == b64_table[l]) {
189 | tmp[j] = l;
190 | break;
191 | }
192 | }
193 | }
194 |
195 | // decode remainder
196 | buf[0] = (tmp[0] << 2) + ((tmp[1] & 0x30) >> 4);
197 | buf[1] = ((tmp[1] & 0xf) << 4) + ((tmp[2] & 0x3c) >> 2);
198 | buf[2] = ((tmp[2] & 0x3) << 6) + tmp[3];
199 |
200 | // write remainer decoded buffer to `dec'
201 | dec = (unsigned char *) b64_realloc(dec, size + (i - 1));
202 | if (dec != NULL) {
203 | for (j = 0; (j < i - 1); ++j) {
204 | dec[size++] = buf[j];
205 | }
206 | } else {
207 | return NULL;
208 | }
209 | }
210 |
211 | // Make sure we have enough space to add '\0' character at end.
212 | dec = (unsigned char *) b64_realloc(dec, size + 1);
213 | if (dec != NULL) {
214 | dec[size] = '\0';
215 | } else {
216 | return NULL;
217 | }
218 |
219 | // Return back the size of decoded string if demanded.
220 | if (decsize != NULL) {
221 | *decsize = size;
222 | }
223 |
224 | return dec;
225 | }
226 |
227 | void encryptLong(uint32_t *firstChunk, uint32_t *secondChunk, uint32_t *key);
228 |
229 | void decryptLong(uint32_t *firstChunk, uint32_t *secondChunk, uint32_t *key);
230 |
231 | void encryptChar(char *buffer, int size, uint32_t *key);
232 |
233 | void decryptChar(char *buffer, int size, uint32_t *key);
234 |
235 | const char* teaDecrypt(char *key, char *source);
236 |
237 | void encryptLong(uint32_t *firstChunk, uint32_t *secondChunk, uint32_t *key) {
238 | uint32_t y = *firstChunk;
239 | uint32_t z = *secondChunk;
240 | uint32_t sum = 0;
241 |
242 | uint32_t delta = 0x9e3779b9;
243 |
244 | //8轮运算(需要对应下面的解密核心函数的轮数一样)
245 | for (int i = 0; i < 32; i++) {
246 | sum += delta;
247 | y += ((z << 4) + key[0]) ^ (z + sum) ^ ((z >> 5) + key[1]);
248 | z += ((y << 4) + key[2]) ^ (y + sum) ^ ((y >> 5) + key[3]);
249 | }
250 |
251 | *firstChunk = y;
252 | *secondChunk = z;
253 | }
254 |
255 | void decryptLong(uint32_t *firstChunk, uint32_t *secondChunk, uint32_t *key) {
256 | uint32_t sum = 0;
257 | uint32_t y = *firstChunk;
258 | uint32_t z = *secondChunk;
259 | uint32_t delta = 0x9e3779b9;
260 |
261 | //32轮运算,所以是2的5次方;16轮运算,所以是2的4次方;8轮运算,所以是2的3次方
262 | sum = 0xC6EF3720;
263 |
264 | //8轮运算
265 | for (int i = 0; i < 32; i++) {
266 | z -= (y << 4) + key[2] ^ y + sum ^ (y >> 5) + key[3];
267 | y -= (z << 4) + key[0] ^ z + sum ^ (z >> 5) + key[1];
268 | sum -= delta;
269 | }
270 | *firstChunk = y;
271 | *secondChunk = z;
272 | }
273 |
274 | //buffer:输入的待加密数据buffer,在函数中直接对元数据buffer进行加密;size:buffer长度;key是密钥;
275 | void encryptChar(char *buffer, int size, uint32_t *key) {
276 | char *p = buffer;
277 | int leftSize = size;
278 | while (p < buffer + size && leftSize >= sizeof(uint32_t) * 2) {
279 | encryptLong((uint32_t *) p, (uint32_t *) (p + sizeof(uint32_t)), key);
280 | p += sizeof(uint32_t) * 2;
281 | leftSize -= sizeof(uint32_t) * 2;
282 | }
283 | }
284 |
285 | //buffer:输入的待解密数据buffer,在函数中直接对元数据buffer进行解密;size:buffer长度;key是密钥;
286 | void decryptChar(char *buffer, int size, uint32_t *key) {
287 | char *p = buffer;
288 | int leftSize = size;
289 | while (p < buffer + size && leftSize >= sizeof(uint32_t) * 2) {
290 | decryptLong((uint32_t *) p, (uint32_t *) (p + sizeof(uint32_t)), key);
291 | p += sizeof(uint32_t) * 2;
292 | leftSize -= sizeof(uint32_t) * 2;
293 | }
294 | }
295 |
296 | const char* teaDecrypt(char *key, char *source) {
297 |
298 | char *des = (char *)(b64_decode(source, strlen(source)));
299 |
300 | decryptChar(des, strlen(des), (uint32_t *)(key));
301 |
302 | return (const char*) des;
303 | }
--------------------------------------------------------------------------------
/decrypt/trojan_decrypt.py:
--------------------------------------------------------------------------------
1 | from ctypes import *
2 | import fileinput
3 | import os
4 | import sys
5 |
6 | #load the shared object file
7 | adder = CDLL('./trojan_decrypt.so')
8 |
9 | key = sys.argv[1]
10 |
11 | inputFilePath = sys.argv[2]
12 |
13 | parentFilePath = os.path.split(inputFilePath)[0]
14 |
15 | outputFileName = ""
16 |
17 | if os.path.split(inputFilePath)[1].find('.') >= 0:
18 | outputFileName = os.path.split(inputFilePath)[1].split('.')[0] + "-new" + '.' + os.path.split(inputFilePath)[1].split('.')[1]
19 | else:
20 | outputFileName = os.path.split(inputFilePath)[1] + "-new"
21 |
22 | outputFilePath = parentFilePath + "/" + outputFileName
23 |
24 | if os.path.exists(outputFilePath):
25 | os.remove(outputFilePath)
26 |
27 | teaDecrypt = adder.teaDecrypt
28 | teaDecrypt.argtypes = [c_char_p, c_char_p]
29 | teaDecrypt.restype = c_char_p
30 |
31 | fr = open(inputFilePath, "r")
32 | fw = open(outputFilePath, "w")
33 | while 1:
34 | lines = fr.readlines(100000)
35 | if not lines:
36 | break
37 | for line in lines:
38 | pass
39 | if line.startswith(""):
40 | line = line.split("")[1]
41 | fw.write(teaDecrypt(key, line))
42 | fw.write("\n")
43 | else:
44 | fw.write(line)
45 |
46 |
47 | fr.close()
48 | fw.close()
49 |
--------------------------------------------------------------------------------
/decrypt/trojan_decrypt.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/decrypt/trojan_decrypt.so
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eleme/Trojan/7e2e566fb158521872e0c4767e612d5501caff6b/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jun 15 11:10:05 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':trojan'
2 |
--------------------------------------------------------------------------------
/trojan/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/trojan/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | # For more information about using CMake with Android Studio, read the
2 | # documentation: https://d.android.com/studio/projects/add-native-code.html
3 |
4 | # Sets the minimum version of CMake required to build the native library.
5 |
6 | cmake_minimum_required(VERSION 3.4.1)
7 |
8 | # Creates and names a library, sets it as either STATIC
9 | # or SHARED, and provides the relative paths to its source code.
10 | # You can define multiple libraries, and CMake builds them for you.
11 | # Gradle automatically packages shared libraries with your APK.
12 |
13 | add_library( # Sets the name of the library.
14 | trojan-lib
15 |
16 | # Sets the library as a shared library.
17 | SHARED
18 |
19 | # Provides a relative path to your source file(s).
20 | src/main/cpp/trojan-lib.cpp
21 | src/main/cpp/LogWriter.cpp
22 | src/main/cpp/ErrInfo.cpp
23 | src/main/cpp/JNIHelp.cpp
24 | src/main/cpp/tea/TEACipher.cpp
25 | src/main/cpp/tea/base64.cpp
26 | )
27 |
28 | # Searches for a specified prebuilt library and stores the path as a
29 | # variable. Because CMake includes system libraries in the search path by
30 | # default, you only need to specify the name of the public NDK library
31 | # you want to add. CMake verifies that the library exists before
32 | # completing its build.
33 |
34 | find_library( # Sets the name of the path variable.
35 | log-lib
36 |
37 | # Specifies the name of the NDK library that
38 | # you want CMake to locate.
39 | log )
40 |
41 | # Specifies libraries CMake should link to your target library. You
42 | # can link multiple libraries, such as libraries you define in this
43 | # build script, prebuilt third-party libraries, or system libraries.
44 |
45 | target_link_libraries( # Specifies the target library.
46 | trojan-lib
47 |
48 | # Links the target library to the log library
49 | # included in the NDK.
50 | ${log-lib} )
--------------------------------------------------------------------------------
/trojan/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | Properties properties = new Properties()
3 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
4 | properties.keys().each { key -> project.ext.set(key, properties.getProperty(key))
5 | }
6 | }
7 |
8 | apply plugin: 'com.android.library'
9 | apply plugin: 'com.novoda.bintray-release'
10 |
11 | def trojan_version_code = 11
12 | def trojan_version = "0.1.1"
13 |
14 | android {
15 | //这是为了debug C++而加的,后面要去掉
16 | //publishNonDefault true
17 |
18 | compileSdkVersion 23
19 | buildToolsVersion '25.0.2'
20 |
21 | defaultConfig {
22 | minSdkVersion 14
23 | targetSdkVersion 23
24 | versionCode trojan_version_code
25 | versionName "$trojan_version"
26 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
27 |
28 | externalNativeBuild {
29 | cmake {
30 | cppFlags "-std=c++11 -frtti -fexceptions"
31 | }
32 | }
33 |
34 | }
35 | buildTypes {
36 | release {
37 | minifyEnabled false
38 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
39 | }
40 | debug {
41 | minifyEnabled false
42 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
43 | debuggable true
44 | jniDebuggable true
45 | }
46 | }
47 |
48 | externalNativeBuild {
49 | cmake {
50 | path "CMakeLists.txt"
51 | }
52 | }
53 |
54 | packagingOptions {
55 | exclude 'META-INF/LICENSE.txt'
56 | exclude 'META-INF/NOTICE.txt'
57 | }
58 | lintOptions {
59 | abortOnError false
60 | checkReleaseBuilds false
61 | }
62 | }
63 |
64 | dependencies {
65 | compile fileTree(include: ['*.jar'], dir: 'libs')
66 | compile 'com.android.support:recyclerview-v7:23.4.0'
67 | compile 'com.android.support:appcompat-v7:23.4.0'
68 |
69 | provided "com.squareup.retrofit2:converter-gson:2.0.1"
70 | provided "me.ele:lancet-base:1.0.2"
71 | }
72 |
73 | def outputPath = project.rootProject.buildDir.parentFile.getPath() + "/archives/${trojan_version}"
74 | def module_name = "trojan"
75 |
76 | task copyOutputs {
77 | doLast {
78 | copy {
79 | from project.rootProject.buildDir.parentFile.getPath() + "/${module_name}/build/outputs"
80 | into outputPath
81 | }
82 | }
83 | }
84 |
85 | publish {
86 | userOrg = 'michaelzhong'
87 | groupId = 'me.ele'
88 | artifactId = 'trojan-library'
89 | publishVersion = "$trojan_version"
90 | }
91 |
--------------------------------------------------------------------------------
/trojan/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/eleme/Downloads/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 | -dontskipnonpubliclibraryclassmembers
19 | -printconfiguration
20 | -keep,allowobfuscation @interface android.support.annotation.Keep
21 | -keep @android.support.annotation.Keep class *
22 | -keepclassmembers class * {
23 | @android.support.annotation.Keep *;
24 | }
25 |
26 | -dontwarn
27 | -ignorewarnings
28 | -keepattributes Signature
29 | -keepattributes *Annotation*
30 | -renamesourcefileattribute SourceFile
31 | -keepattributes SourceFile,LineNumberTable
32 | -keepattributes EnclosingMethod
33 | -keepclassmembers enum * {*;}
34 | -keep class * implements java.io.Serializable
35 | -keep class * implements android.os.Parcelable
36 |
37 |
38 | #retrofit
39 | -dontwarn retrofit2.**
40 | -keep class retrofit2.** { *; }
41 | -keepattributes Signature
42 | -keepattributes Exceptions
43 |
44 |
45 | # rxjava
46 | -keep class rx.schedulers.Schedulers {
47 | public static ;
48 | }
49 | -keep class rx.schedulers.ImmediateScheduler {
50 | public ;
51 | }
52 | -keep class rx.schedulers.TestScheduler {
53 | public ;
54 | }
55 | -keep class rx.schedulers.Schedulers {
56 | public static ** test();
57 | }
58 | -keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
59 | long producerIndex;
60 | long consumerIndex;
61 | }
62 | -keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
63 | long producerNode;
64 | long consumerNode;
65 | }
66 |
67 |
68 | #Rxjava
69 | -dontwarn sun.misc.**
70 |
71 | -keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
72 | long producerIndex;
73 | long consumerIndex;
74 | }
75 |
76 | -keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
77 | rx.internal.util.atomic.LinkedQueueNode producerNode;
78 | }
79 |
80 | -keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {
81 | rx.internal.util.atomic.LinkedQueueNode consumerNode;
82 | }
83 |
84 | # Keep the support library
85 | -keep class android.support.v4.** { *; }
86 | -keep interface android.support.v4.** { *; }
87 | # Keep the support library
88 | -keep class android.support.v7.** { *; }
89 | -keep interface android.support.v7.** { *; }
90 |
91 | #Gson
92 | -keepattributes Signature
--------------------------------------------------------------------------------
/trojan/src/androidTest/java/me/ele/trojan/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will executeRecord on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("me.ele.trojan.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/trojan/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/ErrInfo.cpp:
--------------------------------------------------------------------------------
1 | #include "ErrInfo.h"//
2 | // Created by Allen on 2017/11/16.
3 | //
4 |
5 | ErrInfo::ErrInfo(int errCode, const char *errMsg) {
6 | this->errCode = errCode;
7 | this->errMsg = errMsg;
8 | }
--------------------------------------------------------------------------------
/trojan/src/main/cpp/ErrInfo.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/16.
3 | //
4 |
5 | #ifndef TROJAN_ERRINFO_H
6 | #define TROJAN_ERRINFO_H
7 |
8 | #define OPEN_EXIT -1
9 | #define FSTAT_EXIT -2
10 | #define LSEEK_EXIT -3
11 | #define WRITE_EXIT -4
12 | #define MMAP_EXIT -5
13 | #define UNMMAP_EXIT -6
14 | #define LOCK_EXIT -7
15 | #define UNLOCK_EXIT -8
16 | #define ACCESS_EXIT -9
17 |
18 | #define SUCCESS 0
19 |
20 | class ErrInfo {
21 |
22 | public:
23 | ErrInfo(int errCode, const char *errMsg);
24 |
25 | const char *errMsg;
26 | int errCode;
27 | };
28 |
29 | #endif //TROJAN_ERRINFO_H
30 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/JNIHelp.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/13.
3 | //
4 | #include
5 | #include
6 | #include "JNIHelp.h"
7 | #include
8 | #include
9 | #include
10 |
11 | /**
12 | * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.)
13 | */
14 | template
15 | class scoped_local_ref {
16 | public:
17 | scoped_local_ref(C_JNIEnv *env, T localRef = NULL)
18 | : mEnv(env), mLocalRef(localRef) {
19 | }
20 |
21 | ~scoped_local_ref() { reset(); }
22 |
23 | void reset(T localRef = NULL) {
24 | if (mLocalRef != NULL) {
25 | (*mEnv)->DeleteLocalRef(reinterpret_cast(mEnv), mLocalRef);
26 | mLocalRef = localRef;
27 | }
28 | }
29 |
30 | T get() const { return mLocalRef; }
31 |
32 | private:
33 | C_JNIEnv *mEnv;
34 | T mLocalRef;
35 |
36 | // Disallow copy and assignment.
37 | scoped_local_ref(const scoped_local_ref &);
38 |
39 | void operator=(const scoped_local_ref &);
40 | };
41 |
42 | /*
43 | * Returns a human-readable summary of an exception object. The buffer will
44 | * be populated with the "binary" class name and, if present, the
45 | * exception message.
46 | */
47 | static char *getExceptionSummary0(C_JNIEnv *env, jthrowable exception) {
48 | JNIEnv *e = reinterpret_cast(env);
49 |
50 | /* get the name of the exception's class */
51 | scoped_local_ref exceptionClass(env,
52 | (*env)->GetObjectClass(e, exception)); // can't fail
53 | scoped_local_ref classClass(env, (*env)->GetObjectClass(e,
54 | exceptionClass.get())); // java.lang.Class, can't fail
55 | jmethodID classGetNameMethod = (*env)->GetMethodID(e, classClass.get(), "getName",
56 | "()Ljava/lang/String;");
57 | scoped_local_ref classNameStr(env, (jstring) (*env)->CallObjectMethod(e,
58 | exceptionClass.get(),
59 | classGetNameMethod));
60 | if (classNameStr.get() == NULL) {
61 | return NULL;
62 | }
63 |
64 | /* get printable string */
65 | const char *classNameChars = (*env)->GetStringUTFChars(e, classNameStr.get(), NULL);
66 | if (classNameChars == NULL) {
67 | return NULL;
68 | }
69 |
70 | /* if the exception has a detail message, get that */
71 | jmethodID getMessage = (*env)->GetMethodID(e, exceptionClass.get(), "getMessage",
72 | "()Ljava/lang/String;");
73 | scoped_local_ref messageStr(env, (jstring) (*env)->CallObjectMethod(e, exception,
74 | getMessage));
75 | if (messageStr.get() == NULL) {
76 | return strdup(classNameChars);
77 | }
78 |
79 | char *result = NULL;
80 | const char *messageChars = (*env)->GetStringUTFChars(e, messageStr.get(), NULL);
81 | if (messageChars != NULL) {
82 | asprintf(&result, "%s: %s", classNameChars, messageChars);
83 | (*env)->ReleaseStringUTFChars(e, messageStr.get(), messageChars);
84 | } else {
85 | (*env)->ExceptionClear(e); // clear OOM
86 | asprintf(&result, "%s: ", classNameChars);
87 | }
88 | (*env)->ReleaseStringUTFChars(e, classNameStr.get(), classNameChars);
89 | return result;
90 | }
91 |
92 | static char *getExceptionSummary(C_JNIEnv *env, jthrowable exception) {
93 | JNIEnv *e = reinterpret_cast(env);
94 | char *result = getExceptionSummary0(env, exception);
95 | if (result == NULL) {
96 | (*env)->ExceptionClear(e);
97 | result = strdup("");
98 | }
99 | return result;
100 | }
101 |
102 | static jclass findClass(C_JNIEnv *env, const char *className) {
103 | JNIEnv *e = reinterpret_cast(env);
104 | return (*env)->FindClass(e, className);
105 | }
106 |
107 |
108 | extern "C" int
109 | doJniThrowException(C_JNIEnv *env, const char *className, const char *msg) {
110 | JNIEnv *e = reinterpret_cast(env);
111 |
112 | if ((*env)->ExceptionCheck(e)) {
113 | /* consider creating the new exception with this as "cause" */
114 | scoped_local_ref exception(env, (*env)->ExceptionOccurred(e));
115 | (*env)->ExceptionClear(e);
116 |
117 | if (exception.get() != NULL) {
118 | char *text = getExceptionSummary(env, exception.get());
119 | //ALOGW("Discarding pending exception (%s) to throw %s", text,className);
120 | free(text);
121 | }
122 | }
123 |
124 | scoped_local_ref exceptionClass(env, findClass(env, className));
125 | if (exceptionClass.get() == NULL) {
126 | //ALOGE("Unable to find exception class %s", className);
127 | /* ClassNotFoundException now pending */
128 | return -1;
129 | }
130 |
131 | if ((*env)->ThrowNew(e, exceptionClass.get(), msg) != JNI_OK) {
132 | //ALOGE("Failed throwing '%s' '%s'", className, msg);
133 | /* an exception, most likely OOM, will now be pending */
134 | return -1;
135 | }
136 |
137 | return 0;
138 | }
139 |
140 | void doThrowIAE(JNIEnv *env, const char *msg) {
141 | jniThrowException(env, "java/lang/IllegalArgumentException", msg);
142 | }
143 |
144 | void doThrowISE(JNIEnv *env, const char *msg) {
145 | jniThrowException(env, "java/lang/IllegalStateException", msg);
146 | }
147 |
148 | void doThrowIOE(JNIEnv *env, const char *msg) {
149 | jniThrowException(env, "java/io/IOException", msg);
150 | }
151 |
152 | void print(JNIEnv *env, const char *string) {
153 | jclass log = env->FindClass("android/util/Log");
154 | jmethodID v = env->GetStaticMethodID(log, "v", "(Ljava/lang/String;Ljava/lang/String;)I");
155 | jstring mmap = env->NewStringUTF("Mmap");
156 | jstring msg = env->NewStringUTF(string);
157 | env->CallStaticIntMethod(log, v, mmap, msg);
158 | env->DeleteLocalRef(log);
159 | env->DeleteLocalRef(mmap);
160 | env->DeleteLocalRef(msg);
161 | }
162 |
163 |
164 | void throwExceptionIfNeed(JNIEnv *env, ErrInfo *errInfo) {
165 | if (errInfo == NULL) {
166 | return;
167 | }
168 | switch (errInfo->errCode) {
169 | case OPEN_EXIT:
170 | doThrowIOE(env, errInfo->errMsg);
171 | break;
172 | case FSTAT_EXIT:
173 | doThrowIAE(env, errInfo->errMsg);
174 | break;
175 | case LSEEK_EXIT:
176 | doThrowIOE(env, errInfo->errMsg);
177 | break;
178 | case WRITE_EXIT:
179 | doThrowIOE(env, errInfo->errMsg);
180 | break;
181 | case MMAP_EXIT:
182 | doThrowIOE(env, errInfo->errMsg);
183 | break;
184 | case UNMMAP_EXIT:
185 | doThrowIOE(env, errInfo->errMsg);
186 | case LOCK_EXIT:
187 | doThrowIOE(env, errInfo->errMsg);
188 | break;
189 | case UNLOCK_EXIT:
190 | doThrowIOE(env, errInfo->errMsg);
191 | break;
192 | case ACCESS_EXIT:
193 | doThrowIOE(env, errInfo->errMsg);
194 | default:
195 | //do nothing
196 | break;
197 | }
198 | }
199 |
200 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/JNIHelp.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/13.
3 | //
4 |
5 | #ifndef TROJAN_JNIHELP_H
6 | #define TROJAN_JNIHELP_H
7 |
8 | #include
9 | #include
10 | #include "ErrInfo.h"
11 | //#include "Logger.h"
12 |
13 | #ifdef __cplusplus
14 | extern "C" {
15 | #endif
16 | /*
17 | * Throw an exception with the specified class and an optional message.
18 | *
19 | * The "className" argument will be passed directly to FindClass, which
20 | * takes strings with slashes (e.g. "java/lang/Object").
21 | *
22 | * If an exception is currently pending, we log a warning message and
23 | * clear it.
24 | *
25 | * Returns 0 on success, nonzero if something failed (e.g. the exception
26 | * class couldn't be found, so *an* exception will still be pending).
27 | *
28 | * Currently aborts the VM if it can't throw the exception.
29 | */
30 | int doJniThrowException(C_JNIEnv *env, const char *className, const char *msg);
31 |
32 | /**
33 | * 由于这个函数很短,作为内联函数即可
34 | * @param env
35 | * @param className
36 | * @param msg
37 | * @return
38 | */
39 | inline int jniThrowException(JNIEnv* env, const char* className, const char* msg) {
40 | return doJniThrowException(&env->functions, className, msg);
41 | }
42 |
43 | /**
44 | * throw java/lang/IllegalArgumentException
45 | * @param env
46 | * @param msg
47 | */
48 | void doThrowIAE(JNIEnv*env,const char*msg);
49 |
50 | /**
51 | * throw java/langa/IllegalStateException
52 | * @param env
53 | * @param msg
54 | */
55 | void doThrowISE(JNIEnv*env,const char*msg);
56 |
57 | /**
58 | * throw java/io/IOException
59 | * @param env
60 | * @param msg
61 | */
62 | void doThrowIOE(JNIEnv*env,const char*msg);
63 |
64 | void print(JNIEnv *env, const char *string);
65 |
66 | void throwExceptionIfNeed(JNIEnv *env, ErrInfo *errInfo);
67 |
68 | #ifdef __cplusplus
69 | };
70 | #endif
71 |
72 | #endif //TROJAN_JNIHELP_H
73 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/LogWriter.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/7.
3 | //
4 | #include "LogWriter.h"
5 | #include "ErrInfo.h"
6 | #include
7 | #include
8 |
9 | LogWriter::LogWriter() {
10 | this->cipherStart = strlen(CIPHER_START);
11 | this->cipherEnd = strlen(CIPHER_END);
12 | }
13 |
14 | ErrInfo *LogWriter::initMmap(JNIEnv *env, std::string basicInfo, std::string logDir) {
15 | this->basicInfo = basicInfo;
16 | this->logDir = logDir;
17 | this->buildDate = getDate();
18 | // add the suffix '-mmap', to make a distinction from common IO
19 | this->filePath = logDir + "/" + buildDate + "-mmap";
20 |
21 | this->fd = open(filePath.c_str(), O_RDWR | O_CREAT, (mode_t) 0600);
22 |
23 | if (fd == -1) {
24 | return new ErrInfo(OPEN_EXIT, "Error opening file");
25 | }
26 |
27 | this->fileStat.st_size = 0;
28 | if (fstat(fd, &fileStat) == -1) {
29 | close(fd);
30 | return new ErrInfo(FSTAT_EXIT, "Error fstat file");
31 | }
32 |
33 | this->fileSize = fileStat.st_size;
34 | this->logPageSize = static_cast(ALLOC_PAGE_NUM * sysconf(_SC_PAGE_SIZE));
35 |
36 | bool fileExists = true;
37 |
38 | // If fileSize is not an integer multiple of logPageSize, let it be complemented to an integer multiple of logPageSize
39 | if (fileSize < logPageSize || fileSize % logPageSize != 0) {
40 |
41 | fileExists = fileSize > 0;
42 |
43 | off_t increaseSize = logPageSize - (fileSize % logPageSize);
44 |
45 | if (ftruncate(fd, fileSize + increaseSize) == -1) {
46 | close(fd);
47 | return new ErrInfo(LSEEK_EXIT, "Error when calling ftruncate() to stretch the file");
48 | }
49 |
50 | fileSize += increaseSize;
51 |
52 | if (lseek(fd, fileSize - 1, SEEK_SET) == -1) {
53 | close(fd);
54 | return new ErrInfo(LSEEK_EXIT, "Error calling lseek() to stretch the file");
55 | }
56 |
57 | if (write(fd, "", sizeof(char)) == -1) {
58 | close(fd);
59 | return new ErrInfo(WRITE_EXIT, "Error writing last byte of the file");
60 | }
61 |
62 | }
63 |
64 | void *map = mmap(NULL, static_cast(logPageSize),
65 | PROT_READ | PROT_WRITE,
66 | MAP_SHARED, fd,
67 | fileSize - logPageSize);
68 | ////////////////////////////////////////////////////////////////////////////////
69 |
70 |
71 | if (map == MAP_FAILED || map == NULL) {
72 | close(fd);
73 | return new ErrInfo(MMAP_EXIT, "Error mmaping the file");
74 | }
75 |
76 | recordPtr = static_cast (map);
77 |
78 | if (recordPtr == NULL) {
79 | close(fd);
80 | return new ErrInfo(MMAP_EXIT, "Error cast char*");
81 | }
82 |
83 | ErrInfo *errInfo = checkMmapFile();
84 | if (errInfo != NULL) {
85 | unixMunmap(fd, static_cast(recordPtr), logPageSize);
86 | close(fd);
87 | return errInfo;
88 | }
89 |
90 | bool findFlag = false;
91 |
92 | for (off_t i = logPageSize - 1; i >= 0; i--) {
93 | // Find the first '\n' and stop the search, if not found, then the page is still blank, just back to the beginning of the page
94 | if (recordPtr[i] == '\n') {
95 | findFlag = true;
96 | if (i != logPageSize - 1) {
97 | recordIndex = i + 1;
98 | } else {
99 | recordIndex = logPageSize;
100 | }
101 | break;
102 | }
103 | }
104 | if (!findFlag) {
105 | recordIndex = 0;
106 | }
107 |
108 | memset(recordPtr + recordIndex, 0, static_cast(logPageSize - recordIndex));
109 |
110 | // must write basic info to log file if first create
111 | if (!fileExists) {
112 | return writeLog(env, basicInfo.c_str(), false);
113 | }
114 |
115 | return nullptr;
116 | }
117 |
118 | /**
119 | * @param basicInfo
120 | * @param logDir
121 | */
122 | ErrInfo *LogWriter::init(JNIEnv *env, std::string basicInfo, std::string logDir, std::string key) {
123 | initEncrypt(key);
124 | return initMmap(env, basicInfo, logDir);
125 | }
126 |
127 | LogWriter::~LogWriter() {
128 |
129 | //now write it to disk
130 | if (msync(recordPtr, static_cast(logPageSize), MS_SYNC) == -1) {
131 | perror("Could not sync the file to disk");
132 | }
133 |
134 | //Don't forget to free mmapped memory.
135 | if (munmap(recordPtr, static_cast(logPageSize)) == -1) {
136 | close(fd);
137 | perror("Error un-mmaping the file");
138 | exit(EXIT_FAILURE);
139 | }
140 | //Un-mapping doesn't close the file, so we still need to do that.
141 | close(fd);
142 |
143 | buildDate.shrink_to_fit();
144 | basicInfo.shrink_to_fit();
145 | logDir.shrink_to_fit();
146 | filePath.shrink_to_fit();
147 | }
148 |
149 | void LogWriter::initEncrypt(std::string key) {
150 | if (key.empty()) {
151 | teaCipher = NULL;
152 | return;
153 | }
154 | teaCipher = new TEACipher(key);
155 | }
156 |
157 | ErrInfo *LogWriter::writeLog(JNIEnv *env, const char *logMsg, bool crypt) {
158 |
159 | const size_t textSize = strlen(logMsg);
160 |
161 | if (!crypt || teaCipher == NULL) {
162 | return writeLog(env, logMsg, textSize);
163 | } else {
164 | // After obtaining the cipher text, need to add "Cipher_Start" the beginning of the cipher text, and add "Cipher_End" the end of the cipher text
165 | ErrInfo *errInfo = writeLog(env, CIPHER_START, cipherStart);
166 |
167 | if (errInfo != NULL) {
168 | return errInfo;
169 | }
170 |
171 | size_t teaSize = textSize;
172 |
173 | char *teaCiphers = new char[teaSize];
174 | memset(teaCiphers, 0, teaSize);
175 |
176 | teaCipher->encrypt(logMsg, static_cast(teaSize), teaCiphers);
177 |
178 | char *baseEncodes = b64_encode(teaCiphers, teaSize);
179 |
180 | errInfo = writeLog(env, baseEncodes, strlen(baseEncodes));
181 |
182 | free(teaCiphers);
183 | free(baseEncodes);
184 |
185 | if (errInfo != NULL) {
186 | return errInfo;
187 | }
188 | return writeLog(env, CIPHER_END, cipherEnd);
189 | }
190 | }
191 |
192 | ErrInfo *LogWriter::writeLog(JNIEnv *env, const char *logMsg, size_t textSize) {
193 | if (logMsg == NULL || textSize <= 0) {
194 | return nullptr;
195 | }
196 |
197 | if (recordPtr == NULL) {
198 | close(fd);
199 | return new ErrInfo(WRITE_EXIT, "Error writing log");
200 | }
201 |
202 | ErrInfo *errInfo = checkMmapFile();
203 | if (errInfo != NULL) {
204 | unixMunmap(fd, static_cast(recordPtr), logPageSize);
205 | close(fd);
206 | return errInfo;
207 | }
208 |
209 | size_t msgIndex = 0;
210 |
211 | while (1) {
212 |
213 | for (; msgIndex < textSize && recordIndex < logPageSize; msgIndex++) {
214 | recordPtr[recordIndex] = logMsg[msgIndex];
215 | recordIndex++;
216 | }
217 |
218 | //当开辟的mmap内存被写满时,需要再开辟一页mmap内存
219 | if (recordIndex >= logPageSize) {
220 |
221 | ErrInfo *errInfo = unixMunmap(fd, recordPtr, (size_t) logPageSize);
222 | if (errInfo != NULL) {
223 | close(fd);
224 | return errInfo;
225 | }
226 |
227 | recordPtr = NULL;
228 |
229 | if (access(filePath.c_str(), 0) != 0) {
230 | close(fd);
231 | return new ErrInfo(ACCESS_EXIT, "Error calling access file");
232 | }
233 |
234 | //扩展文件大小
235 | if (ftruncate(fd, fileSize + logPageSize) == -1) {
236 | close(fd);
237 | return new ErrInfo(LSEEK_EXIT, "Error calling ftruncate() to stretch file");
238 | }
239 |
240 | //移动到文件末尾
241 | if (lseek(fd, fileSize + logPageSize - 1, SEEK_SET) == -1) {
242 | close(fd);
243 | return new ErrInfo(LSEEK_EXIT, "Error calling lseek() to stretch the file");
244 | }
245 |
246 | //在文件末尾写入一个字符,达到扩展文件大小的目的
247 | if (write(fd, "", 1) == -1) {
248 | close(fd);
249 | return new ErrInfo(WRITE_EXIT, "Error writing last byte of the file");
250 | }
251 |
252 | this->fileStat.st_size = 0;
253 |
254 | if (fstat(fd, &fileStat) == -1) {
255 | close(fd);
256 | return new ErrInfo(FSTAT_EXIT, "Error fstat file");
257 | }
258 |
259 | if (fileStat.st_size - logPageSize != this->fileSize &&
260 | fileStat.st_size % logPageSize != 0) {
261 | close(fd);
262 | return new ErrInfo(WRITE_EXIT, "Error stretch file when writing");
263 | }
264 |
265 | this->fileSize = fileStat.st_size;
266 |
267 | void *map = mmap(NULL, static_cast(logPageSize), PROT_READ | PROT_WRITE,
268 | MAP_SHARED, fd,
269 | fileSize - logPageSize);
270 |
271 | if (map == MAP_FAILED || map == NULL) {
272 | close(fd);
273 | return new ErrInfo(MMAP_EXIT, "Error mmaping the file");
274 | }
275 |
276 | recordPtr = static_cast (map);
277 |
278 | if (recordPtr == NULL) {
279 | close(fd);
280 | return new ErrInfo(MMAP_EXIT, "Error cast char*");
281 | }
282 |
283 | memset(recordPtr, 0, static_cast(logPageSize));
284 |
285 | recordIndex = 0;
286 | } else {
287 | break;
288 | }
289 | }
290 |
291 | return nullptr;
292 | }
293 |
294 |
295 | void LogWriter::refreshBasicInfo(JNIEnv *env, std::string basicInfo) {
296 | this->basicInfo.shrink_to_fit();
297 | this->basicInfo = basicInfo;
298 | }
299 |
300 | ErrInfo *LogWriter::closeAndRenew(JNIEnv *env) {
301 |
302 | //还是改成复制一个文件出来更好,比如将2017-11-05复制出一个2017-11-05-up的文件出来
303 | //首先取消映射
304 | ErrInfo *errInfo = unixMunmap(fd, recordPtr, static_cast(logPageSize));
305 | if (errInfo != NULL) {
306 | close(fd);
307 | return errInfo;
308 | }
309 | recordPtr = NULL;
310 | //然后关闭文件
311 | close(fd);
312 | //然后重命名文件
313 | std::string upFilePath = logDir + "/" + buildDate + "-mmap-up";
314 | //为了预防文件存在的情况,所以进行一次删除操作
315 | remove(upFilePath.c_str());
316 | //为防止日志文件被删除,先检查一下日志文件是否存在
317 | if (access(filePath.c_str(), 0) == 0) {
318 | rename(filePath.c_str(), upFilePath.c_str());
319 | }
320 | upFilePath.shrink_to_fit();
321 | buildDate.shrink_to_fit();
322 | filePath.shrink_to_fit();
323 | //最后重新初始化,即新建文件并映射
324 | return initMmap(env, basicInfo, logDir);
325 | }
326 |
327 | std::string LogWriter::getDate() {
328 | time_t now = time(0);
329 | tm localTime = *localtime(&now);
330 | std::string *date;
331 | size_t bufSize = sizeof(char) * 20;
332 | char *buf = (char *) malloc(bufSize);
333 | strftime(buf, bufSize, "%Y-%m-%d", &localTime);
334 | date = new std::string(buf);
335 | free(buf);
336 | return *date;
337 | }
338 |
339 | ErrInfo *LogWriter::unixMunmap(int fd, void *map, size_t map_size) {
340 | if (msync(map, map_size, MS_SYNC) == -1) {
341 | return new ErrInfo(UNMMAP_EXIT, "Error sync the file to disk");
342 | }
343 | if (munmap(map, map_size) == -1) {
344 | return new ErrInfo(UNMMAP_EXIT, "Error un-mmapping the file");
345 | }
346 | return NULL;
347 | }
348 |
349 | ErrInfo *LogWriter::checkMmapFile() {
350 | if (access(filePath.c_str(), 0) != 0) {
351 | return new ErrInfo(WRITE_EXIT, "Error access log file");
352 | }
353 | this->fileStat.st_size = 0;
354 | if (fstat(fd, &fileStat) == -1 || this->fileStat.st_size != this->fileSize) {
355 | return new ErrInfo(FSTAT_EXIT, "Error read file size");
356 | }
357 | return NULL;
358 | }
359 |
360 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/LogWriter.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/16.
3 | //
4 |
5 | #ifndef TROJAN_WRITER_H
6 | #define TROJAN_WRITER_H
7 |
8 |
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 | #include "JNIHelp.h"
20 | #include "ErrInfo.h"
21 | #include "tea/TEACipher.h"
22 | #include "tea/base64.h"
23 |
24 | //一次性分配的页数,目前测试取值为1,2,3,4时seekOffset使用logPageSize-1可以
25 | #define ALLOC_PAGE_NUM 40
26 | //含有\n的目的是为了将Cipher_Start与密文写在不同的行,这样读取时比较方便
27 | #define CIPHER_START ""
28 | #define CIPHER_END "\n"
29 |
30 | class LogWriter {
31 | public:
32 | LogWriter();
33 |
34 | ~LogWriter();
35 |
36 | ErrInfo *init(JNIEnv *, std::string basicInfo, std::string logDir, std::string key);
37 |
38 | ErrInfo *writeLog(JNIEnv *, const char *logMsg, bool crypt);
39 |
40 | void refreshBasicInfo(JNIEnv *env, std::string basicInfo);
41 |
42 | ErrInfo *closeAndRenew(JNIEnv *env);
43 |
44 | private:
45 | struct stat fileStat;
46 |
47 | int fd;
48 |
49 | off_t fileSize;
50 |
51 | off_t logPageSize;
52 |
53 | std::string buildDate;
54 | std::string filePath;
55 |
56 | std::string basicInfo;
57 | std::string logDir;
58 |
59 | char *recordPtr = NULL;
60 |
61 | off_t recordIndex = 0;
62 |
63 |
64 | ///////////////后面还是有必要把加密相关的都放到一个类中保存,
65 | /// 并且设计一个抽象类,以及AES,DES,TEA这三种算法的实现类/////////////
66 | //对称加密对象
67 | TEACipher *teaCipher;
68 |
69 | size_t cipherStart;
70 | size_t cipherEnd;
71 | ////////////////////////////////////////////////////
72 |
73 | //工具方法,获得当前日期,格式类似2017-11-06
74 | std::string getDate();
75 |
76 | ErrInfo *initMmap(JNIEnv *, std::string basicInfo, std::string logDir);
77 |
78 | void initEncrypt(std::string key);
79 |
80 | ErrInfo *writeLog(JNIEnv *, const char *logMsg, size_t textSize);
81 |
82 | ErrInfo *unixMunmap(int fd, void *map, size_t map_size);
83 |
84 | ErrInfo *checkMmapFile();
85 |
86 | };
87 |
88 | #endif //TROJAN_WRITER_H
89 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/Logger.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/13.
3 | //
4 |
5 | #ifndef TROJAN_LOGGER_H
6 | #define TROJAN_LOGGER_H
7 |
8 | #include
9 |
10 | #ifdef __cplusplus
11 | extern "C" {
12 | #endif
13 |
14 | typedef int (*trojan_logfunc_t)(int prio, const char *tag, const char *msg);
15 |
16 | trojan_logfunc_t trojan_get_log_function();
17 | void trojan_set_log_function(trojan_logfunc_t func);
18 |
19 | int trojan_log_print(int prio, const char *tag, const char *fmt, ...)
20 | #ifdef __GNUC__
21 | __attribute__((format(printf, 3, 4)))
22 | #endif
23 | ;
24 |
25 | int trojan_log_vprint(int prio, const char *tag, const char *fmt, va_list ap);
26 |
27 | inline static int trojan_log_write(int prio, const char *tag, const char *msg) {
28 | return trojan_get_log_function()(prio, tag, msg);
29 | }
30 |
31 | #ifndef MMDB_NO_LOGX_MACRO
32 |
33 | #define LOGV(tag, fmt, args...) \
34 | trojan_log_print(ANDROID_LOG_VERBOSE, (tag), (fmt), ##args)
35 | #define LOGD(tag, fmt, args...) \
36 | trojan_log_print(ANDROID_LOG_DEBUG, (tag), (fmt), ##args)
37 | #define LOGI(tag, fmt, args...) \
38 | trojan_log_print(ANDROID_LOG_INFO, (tag), (fmt), ##args)
39 | #define LOGW(tag, fmt, args...) \
40 | trojan_log_print(ANDROID_LOG_WARN, (tag), (fmt), ##args)
41 | #define LOGE(tag, fmt, args...) \
42 | trojan_log_print(ANDROID_LOG_ERROR, (tag), (fmt), ##args)
43 |
44 | #define ALOG(priority, tag, ...) \
45 | trojan_log_print(ANDROID_##priority, (tag), __VA_ARGS__)
46 | #define ALOGV(...) ((void) LOGV(LOG_TAG, __VA_ARGS__))
47 | #define ALOGD(...) ((void) LOGD(LOG_TAG, __VA_ARGS__))
48 | #define ALOGI(...) ((void) LOGI(LOG_TAG, __VA_ARGS__))
49 | #define ALOGW(...) ((void) LOGW(LOG_TAG, __VA_ARGS__))
50 | #define ALOGE(...) ((void) LOGE(LOG_TAG, __VA_ARGS__))
51 |
52 | #define IF_ALOG(priority, tag) if (1)
53 | #define LOG_FATAL_IF(cond, ...) // do nothing
54 | #define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ##__VA_ARGS__)
55 |
56 | #endif
57 |
58 | #ifdef __cplusplus
59 | }
60 | #endif
61 |
62 |
63 |
64 | #endif //TROJAN_LOGGER_H
65 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/tea/TEACipher.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Created by michaelzhong on 2017/12/25.
3 | //
4 |
5 | #include
6 | #include "TEACipher.h"
7 |
8 | void encryptLong(uint32_t *firstChunk, uint32_t *secondChunk, uint32_t *key) {
9 | uint32_t y = *firstChunk;
10 | uint32_t z = *secondChunk;
11 | uint32_t sum = 0;
12 |
13 | uint32_t delta = 0x9e3779b9;
14 |
15 | //8轮运算(需要对应下面的解密核心函数的轮数一样)
16 | for (int i = 0; i < 32; i++) {
17 | sum += delta;
18 | y += ((z << 4) + key[0]) ^ (z + sum) ^ ((z >> 5) + key[1]);
19 | z += ((y << 4) + key[2]) ^ (y + sum) ^ ((y >> 5) + key[3]);
20 | }
21 |
22 | *firstChunk = y;
23 | *secondChunk = z;
24 | }
25 |
26 | void decryptLong(uint32_t *firstChunk, uint32_t *secondChunk, uint32_t *key) {
27 | uint32_t sum = 0;
28 | uint32_t y = *firstChunk;
29 | uint32_t z = *secondChunk;
30 | uint32_t delta = 0x9e3779b9;
31 |
32 | //32轮运算,所以是2的5次方;16轮运算,所以是2的4次方;8轮运算,所以是2的3次方
33 | sum = 0xC6EF3720;
34 |
35 | //8轮运算
36 | for (int i = 0; i < 32; i++) {
37 | z -= (y << 4) + key[2] ^ y + sum ^ (y >> 5) + key[3];
38 | y -= (z << 4) + key[0] ^ z + sum ^ (z >> 5) + key[1];
39 | sum -= delta;
40 | }
41 | *firstChunk = y;
42 | *secondChunk = z;
43 | }
44 |
45 | //buffer:输入的待加密数据buffer,在函数中直接对元数据buffer进行加密;size:buffer长度;key是密钥;
46 | void encryptChar(char *buffer, int size, uint32_t *key) {
47 | char *p = buffer;
48 | int leftSize = size;
49 | while (p < buffer + size && leftSize >= sizeof(uint32_t) * 2) {
50 | encryptLong((uint32_t *) p, (uint32_t *) (p + sizeof(uint32_t)), key);
51 | p += sizeof(uint32_t) * 2;
52 | leftSize -= sizeof(uint32_t) * 2;
53 | }
54 | }
55 |
56 | //buffer:输入的待解密数据buffer,在函数中直接对元数据buffer进行解密;size:buffer长度;key是密钥;
57 | void decryptChar(char *buffer, int size, uint32_t *key) {
58 | char *p = buffer;
59 | int leftSize = size;
60 | while (p < buffer + size && leftSize >= sizeof(uint32_t) * 2) {
61 | decryptLong((uint32_t *) p, (uint32_t *) (p + sizeof(uint32_t)), key);
62 | p += sizeof(uint32_t) * 2;
63 | leftSize -= sizeof(uint32_t) * 2;
64 | }
65 | }
66 |
67 | void TEACipher::encrypt(const char *plaint, int srcSize, char *cipher) {
68 | strcpy(cipher, plaint);
69 | encryptChar(cipher, srcSize, (uint32_t *) this->key.c_str());
70 | }
71 |
72 | void TEACipher::decrypt(const char *cipher, int srcSize, char *plaint) {
73 | strcpy(plaint, cipher);
74 | decryptChar(plaint, srcSize, (uint32_t *) this->key.c_str());
75 | }
76 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/tea/TEACipher.h:
--------------------------------------------------------------------------------
1 | //
2 | // Created by michaelzhong on 2017/12/25.
3 | //
4 |
5 | #ifndef UNTITLED1_TEACIPHER_H
6 | #define UNTITLED1_TEACIPHER_H
7 |
8 |
9 | #include
10 |
11 | class TEACipher {
12 |
13 | protected:
14 | std::string key;
15 |
16 | public:
17 | TEACipher(const std::string &key) {
18 | this->key = key;
19 | }
20 |
21 | void encrypt(const char *plaint, int srcSize, char *cipher);
22 |
23 | void decrypt(const char *cipher, int srcSize, char *plaint);
24 | };
25 |
26 |
27 | #endif //UNTITLED1_TEACIPHER_H
28 |
--------------------------------------------------------------------------------
/trojan/src/main/cpp/tea/base64.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include "base64.h"
5 |
6 | #ifdef b64_USE_CUSTOM_MALLOC
7 | extern void* b64_malloc(size_t);
8 | #endif
9 |
10 | #ifdef b64_USE_CUSTOM_REALLOC
11 | extern void* b64_realloc(void*, size_t);
12 | #endif
13 |
14 | char *b64_encode(const char *src, size_t len) {
15 | int i = 0;
16 | int j = 0;
17 | char *enc = NULL;
18 | size_t size = 0;
19 | char buf[4];
20 | char tmp[3];
21 |
22 | // alloc
23 | enc = (char *) b64_malloc(1);
24 | if (NULL == enc) { return NULL; }
25 |
26 | // parse until end of source
27 | while (len--) {
28 | // read up to 3 bytes at a time into `tmp'
29 | tmp[i++] = *(src++);
30 |
31 | // if 3 bytes read then encode into `buf'
32 | if (3 == i) {
33 | buf[0] = (char) ((tmp[0] & 0xfc) >> 2);
34 | buf[1] = (char) (((tmp[0] & 0x03) << 4) + ((tmp[1] & 0xf0) >> 4));
35 | buf[2] = (char) (((tmp[1] & 0x0f) << 2) + ((tmp[2] & 0xc0) >> 6));
36 | buf[3] = (char) (tmp[2] & 0x3f);
37 |
38 | // allocate 4 new byts for `enc` and
39 | // then translate each encoded buffer
40 | // part by index from the base 64 index table
41 | // into `enc' char array
42 | enc = (char *) b64_realloc(enc, size + 4);
43 | for (i = 0; i < 4; ++i) {
44 | enc[size++] = b64_table[buf[i]];
45 | }
46 |
47 | // reset index
48 | i = 0;
49 | }
50 | }
51 |
52 | // remainder
53 | if (i > 0) {
54 | // fill `tmp' with `\0' at most 3 times
55 | for (j = i; j < 3; ++j) {
56 | tmp[j] = '\0';
57 | }
58 |
59 | // perform same codec as above
60 | buf[0] = (char) ((tmp[0] & 0xfc) >> 2);
61 | buf[1] = (char) (((tmp[0] & 0x03) << 4) + ((tmp[1] & 0xf0) >> 4));
62 | buf[2] = (char) (((tmp[1] & 0x0f) << 2) + ((tmp[2] & 0xc0) >> 6));
63 | buf[3] = (char) (tmp[2] & 0x3f);
64 |
65 | // perform same write to `enc` with new allocation
66 | for (j = 0; (j < i + 1); ++j) {
67 | enc = (char *) b64_realloc(enc, size + 1);
68 | enc[size++] = b64_table[buf[j]];
69 | }
70 |
71 | // while there is still a remainder
72 | // append `=' to `enc'
73 | while ((i++ < 3)) {
74 | enc = (char *) b64_realloc(enc, size + 1);
75 | enc[size++] = '=';
76 | }
77 | }
78 |
79 | // Make sure we have enough space to add '\0' character at end.
80 | enc = (char *) b64_realloc(enc, size + 1);
81 | enc[size] = '\0';
82 |
83 | return enc;
84 | }
85 |
86 | char *b64_decode(const char *src, size_t len) {
87 | return b64_decode_ex(src, len, NULL);
88 | }
89 |
90 | char *b64_decode_ex(const char *src, size_t len, size_t *decsize) {
91 | int i = 0;
92 | int j = 0;
93 | int l = 0;
94 | size_t size = 0;
95 | char *dec = NULL;
96 | char buf[3];
97 | char tmp[4];
98 |
99 | // alloc
100 | dec = (char *) b64_malloc(1);
101 | if (NULL == dec) {
102 | return NULL;
103 | }
104 |
105 | // parse until end of source
106 | while (len--) {
107 | // break if char is `=' or not base64 char
108 | if ('=' == src[j]) {
109 | break;
110 | }
111 | if (!(isalnum(src[j]) || '+' == src[j] || '/' == src[j])) {
112 | break;
113 | }
114 |
115 | // read up to 4 bytes at a time into `tmp'
116 | tmp[i++] = (char) src[j++];
117 |
118 | // if 4 bytes read then decode into `buf'
119 | if (4 == i) {
120 | // translate values in `tmp' from table
121 | for (i = 0; i < 4; ++i) {
122 | // find translation char in `b64_table'
123 | for (l = 0; l < 64; ++l) {
124 | if (tmp[i] == b64_table[l]) {
125 | tmp[i] = (char) l;
126 | break;
127 | }
128 | }
129 | }
130 |
131 | // decode
132 | buf[0] = (char) ((tmp[0] << 2) + ((tmp[1] & 0x30) >> 4));
133 | buf[1] = (char) (((tmp[1] & 0xf) << 4) + ((tmp[2] & 0x3c) >> 2));
134 | buf[2] = (char) (((tmp[2] & 0x3) << 6) + tmp[3]);
135 |
136 | // write decoded buffer to `dec'
137 | dec = (char *) b64_realloc(dec, size + 3);
138 | if (dec != NULL) {
139 | for (i = 0; i < 3; ++i) {
140 | dec[size++] = buf[i];
141 | }
142 | } else {
143 | return NULL;
144 | }
145 |
146 | // reset
147 | i = 0;
148 | }
149 | }
150 |
151 | // remainder
152 | if (i > 0) {
153 | // fill `tmp' with `\0' at most 4 times
154 | for (j = i; j < 4; ++j) {
155 | tmp[j] = '\0';
156 | }
157 |
158 | // translate remainder
159 | for (j = 0; j < 4; ++j) {
160 | // find translation char in `b64_table'
161 | for (l = 0; l < 64; ++l) {
162 | if (tmp[j] == b64_table[l]) {
163 | tmp[j] = l;
164 | break;
165 | }
166 | }
167 | }
168 |
169 | // decode remainder
170 | buf[0] = (char) ((tmp[0] << 2) + ((tmp[1] & 0x30) >> 4));
171 | buf[1] = (char) (((tmp[1] & 0xf) << 4) + ((tmp[2] & 0x3c) >> 2));
172 | buf[2] = (char) (((tmp[2] & 0x3) << 6) + tmp[3]);
173 |
174 | // write remainer decoded buffer to `dec'
175 | dec = (char *) b64_realloc(dec, size + (i - 1));
176 | if (dec != NULL) {
177 | for (j = 0; (j < i - 1); ++j) {
178 | dec[size++] = buf[j];
179 | }
180 | } else {
181 | return NULL;
182 | }
183 | }
184 |
185 | // Make sure we have enough space to add '\0' character at end.
186 | dec = (char *) b64_realloc(dec, size + 1);
187 | if (dec != NULL) {
188 | dec[size] = '\0';
189 | } else {
190 | return NULL;
191 | }
192 |
193 | // Return back the size of decoded string if demanded.
194 | if (decsize != NULL) {
195 | *decsize = size;
196 | }
197 |
198 | return dec;
199 | }
--------------------------------------------------------------------------------
/trojan/src/main/cpp/tea/base64.h:
--------------------------------------------------------------------------------
1 | #ifndef B64_H
2 | #define B64_H 1
3 |
4 | /**
5 | * Memory allocation functions to use. You can define b64_malloc and
6 | * b64_realloc to custom functions if you want.
7 | */
8 |
9 | #include
10 |
11 | #ifndef b64_malloc
12 | # define b64_malloc(ptr) malloc(ptr)
13 | #endif
14 | #ifndef b64_realloc
15 | # define b64_realloc(ptr, size) realloc(ptr, size)
16 | #endif
17 |
18 | /**
19 | * Base64 index table.
20 | */
21 |
22 | static const char b64_table[] = {
23 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
24 | 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
25 | 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
26 | 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
27 | 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
28 | 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
29 | 'w', 'x', 'y', 'z', '0', '1', '2', '3',
30 | '4', '5', '6', '7', '8', '9', '+', '/'
31 | };
32 |
33 | #ifdef __cplusplus
34 | extern "C" {
35 | #endif
36 |
37 | /**
38 | * Encode `char *' source with `size_t' size.
39 | * Returns a `char *' base64 encoded string.
40 | */
41 |
42 | char *b64_encode(const char *, size_t);
43 |
44 | /**
45 | * Dencode `char *' source with `size_t' size.
46 | * Returns a `char *' base64 decoded string.
47 | */
48 | char *b64_decode(const char *, size_t);
49 |
50 | /**
51 | * Dencode `char *' source with `size_t' size.
52 | * Returns a `char *' base64 decoded string + size of decoded string.
53 | */
54 | char *b64_decode_ex(const char *, size_t, size_t *);
55 |
56 | #ifdef __cplusplus
57 | }
58 | #endif
59 |
60 | #endif
--------------------------------------------------------------------------------
/trojan/src/main/cpp/trojan-lib.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Created by Allen on 2017/11/8.
3 | //
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include "LogWriter.h"
15 |
16 | #ifndef TROJAN_LOG_WRITER_H
17 | #define TROJAN_LOG_WRITER_H
18 |
19 | #ifdef __cplusplus
20 | extern "C" {
21 | #endif
22 |
23 | std::string jstring2string(JNIEnv *env, jstring jStr) {
24 | const jclass stringClass = env->GetObjectClass(jStr);
25 | const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
26 | const jstring utf = env->NewStringUTF("UTF-8");
27 | const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes, utf);
28 |
29 | size_t length = (size_t) env->GetArrayLength(stringJbytes);
30 | jbyte *pBytes = env->GetByteArrayElements(stringJbytes, NULL);
31 |
32 | std::string ret = std::string((char *) pBytes, length);
33 |
34 | env->DeleteLocalRef(stringClass);
35 | env->DeleteLocalRef(utf);
36 | env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_COMMIT);
37 |
38 | return ret;
39 | }
40 |
41 | jlong Java_me_ele_trojan_record_impl_MmapLogWriter_nativeInit(JNIEnv *env,
42 | jobject object,
43 | jstring basic_info,
44 | jstring dir,
45 | jstring key) {
46 |
47 | //////////////////////////////////////
48 | std::string methodName = "nativeInit";
49 | print(env, methodName.c_str());
50 | ////////////////////////////////////
51 |
52 | LogWriter *logWriter = new LogWriter();
53 | std::string basicInfo;
54 | if (basic_info != NULL) {
55 | basicInfo = jstring2string(env, basic_info);
56 | env->DeleteLocalRef(basic_info);
57 | }
58 | std::string logDir;
59 | if (dir != NULL) {
60 | logDir = jstring2string(env, dir);
61 | env->DeleteLocalRef(dir);
62 | }
63 | //注意:encrypt_method和key有可能为null
64 | std::string encryptKey;
65 | if (key != NULL) {
66 | encryptKey = jstring2string(env, key);
67 | env->DeleteLocalRef(key);
68 | }
69 |
70 | ErrInfo *errInfo = logWriter->init(env, basicInfo, logDir, encryptKey);
71 | if (errInfo != NULL) {
72 | throwExceptionIfNeed(env, errInfo);
73 | delete errInfo;
74 | errInfo = NULL;
75 | }
76 |
77 | return reinterpret_cast(logWriter);
78 | }
79 |
80 | jlong Java_me_ele_trojan_record_impl_MmapLogWriter_nativeWrite(JNIEnv *env,
81 | jobject object,
82 | jlong log_writer_object,
83 | jstring msg_content,
84 | jboolean crypt) {
85 |
86 | LogWriter *logWriter = reinterpret_cast(log_writer_object);
87 | if (msg_content != NULL) {
88 | const char *msg = env->GetStringUTFChars(msg_content, JNI_FALSE);
89 | ErrInfo *errInfo = logWriter->writeLog(env, msg, static_cast(crypt));
90 | env->ReleaseStringUTFChars(msg_content, msg);
91 | if (errInfo != NULL) {
92 | throwExceptionIfNeed(env, errInfo);
93 | delete errInfo;
94 | errInfo = NULL;
95 | }
96 | }
97 | return reinterpret_cast(logWriter);
98 | }
99 |
100 | void Java_me_ele_trojan_record_impl_MmapLogWriter_nativeRefreshBasicInfo(JNIEnv *env,
101 | jobject object,
102 | jlong log_writer_object,
103 | jstring basic_info) {
104 | //////////////////////////////////////
105 | std::string methodName = "nativeRefreshBasicInfo";
106 | print(env, methodName.c_str());
107 | ////////////////////////////////////
108 |
109 | std::string basicInfo = jstring2string(env, basic_info);
110 | LogWriter *logWriter = reinterpret_cast(log_writer_object);
111 | logWriter->refreshBasicInfo(env, basicInfo);
112 | }
113 |
114 | void Java_me_ele_trojan_record_impl_MmapLogWriter_nativeCloseAndRenew(JNIEnv *env, jobject object,
115 | jlong logWriterObject) {
116 |
117 | //////////////////////////////////////
118 | std::string methodName = "nativeCloseAndRenew";
119 | print(env, methodName.c_str());
120 | ////////////////////////////////////
121 |
122 | LogWriter *logWriter = reinterpret_cast(logWriterObject);
123 | ErrInfo *errInfo = logWriter->closeAndRenew(env);
124 | if (errInfo != NULL) {
125 | throwExceptionIfNeed(env, errInfo);
126 | delete errInfo;
127 | errInfo = NULL;
128 | }
129 | }
130 |
131 | #ifdef __cplusplus
132 | };
133 | #endif
134 |
135 |
136 | #endif
137 |
138 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/Trojan.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan;
2 |
3 | import android.content.Context;
4 |
5 | import java.io.File;
6 | import java.util.List;
7 |
8 | import me.ele.trojan.config.TrojanConfig;
9 | import me.ele.trojan.listener.WaitUploadListener;
10 |
11 | /**
12 | * Created by Eric on 17/2/14.
13 | */
14 |
15 | public class Trojan {
16 |
17 | private static Context sContext;
18 |
19 | public static void init(TrojanConfig config) {
20 | sContext = config.getContext();
21 | TrojanManager.getInstance().init(config);
22 | }
23 |
24 | public static Context getContext() {
25 | if (sContext == null) {
26 | throw new IllegalArgumentException("Trojan have not init");
27 | }
28 | return sContext.getApplicationContext();
29 | }
30 |
31 | /**
32 | * 更新用户信息时,应该使用这个方法来记录最新的用户信息
33 | *
34 | * @param user
35 | */
36 | public static void refreshUser(String user) {
37 | TrojanManager.getInstance().refreshUser(user);
38 | }
39 |
40 | public static void log(String tag, String msg) {
41 | TrojanManager.getInstance().log(tag, msg);
42 | }
43 |
44 | public static void log(String tag, int version, String msg) {
45 | TrojanManager.getInstance().log(tag, version, msg, false);
46 | }
47 |
48 | public static void log(String tag, int version, String msg, boolean encryptFlag) {
49 | TrojanManager.getInstance().log(tag, version, msg, encryptFlag);
50 | }
51 |
52 | public static void log(String tag, List msgList) {
53 | TrojanManager.getInstance().log(tag, msgList);
54 | }
55 |
56 | public static void log(String tag, int version, List msgList) {
57 | TrojanManager.getInstance().log(tag, version, msgList, false);
58 | }
59 |
60 | public static void log(String tag, int version, List msgList, boolean encryptFlag) {
61 | TrojanManager.getInstance().log(tag, version, msgList, encryptFlag);
62 | }
63 |
64 | public static void logToJson(String tag, int version, Object src) {
65 | TrojanManager.getInstance().logToJson(tag, version, src, false);
66 | }
67 |
68 | public static void logToJson(String tag, int version, Object src, boolean encryptFlag) {
69 | TrojanManager.getInstance().logToJson(tag, version, src, encryptFlag);
70 | }
71 |
72 | public static void prepareUploadLogFileAsync(WaitUploadListener waitUploadListener) {
73 | TrojanManager.getInstance().prepareUploadLogFileAsync(waitUploadListener);
74 | }
75 |
76 | public static File prepareUploadLogFileSync(final String dateTime) {
77 | return TrojanManager.getInstance().prepareUploadLogFileSync(dateTime);
78 | }
79 |
80 | public static void destroy() {
81 | TrojanManager.getInstance().destroy();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/TrojanManager.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.content.IntentFilter;
6 | import android.net.ConnectivityManager;
7 | import android.text.TextUtils;
8 |
9 | import java.io.File;
10 | import java.util.List;
11 |
12 | import me.ele.trojan.config.TrojanConfig;
13 | import me.ele.trojan.internal.ActivityLife;
14 | import me.ele.trojan.internal.ExceptionHandler;
15 | import me.ele.trojan.listener.WaitUploadListener;
16 | import me.ele.trojan.log.Logger;
17 | import me.ele.trojan.receiver.TrojanReceiver;
18 | import me.ele.trojan.record.ILogRecorder;
19 | import me.ele.trojan.record.impl.LogRecorder;
20 | import me.ele.trojan.upload.ILogUploader;
21 | import me.ele.trojan.upload.impl.LogUploader;
22 | import me.ele.trojan.utils.TagUtil;
23 |
24 | /**
25 | * Created by michaelzhong on 2017/11/7.
26 | */
27 | public class TrojanManager {
28 |
29 | private static volatile TrojanManager sInstance;
30 |
31 | private Context context;
32 |
33 | private TrojanConfig trojanConfig;
34 |
35 | private TrojanReceiver trojanReceiver;
36 |
37 | private ILogRecorder logRecorder;
38 |
39 | private ILogUploader logUploader;
40 |
41 | private TrojanManager() {
42 |
43 | }
44 |
45 | public static TrojanManager getInstance() {
46 | if (sInstance == null) {
47 | synchronized (TrojanManager.class) {
48 | if (sInstance == null) {
49 | sInstance = new TrojanManager();
50 | }
51 | }
52 | }
53 | return sInstance;
54 | }
55 |
56 | public void init(TrojanConfig trojanConfig) {
57 | Logger.i("TrojanManager-->init");
58 | if (trojanConfig == null) {
59 | throw new IllegalArgumentException("TrojanManager trojanConfig is null");
60 | }
61 |
62 | this.destroy();
63 | Logger.setLog(trojanConfig.isEnableLog());
64 |
65 | this.context = trojanConfig.getContext();
66 | this.trojanConfig = trojanConfig;
67 |
68 | // register activity life callback
69 | ActivityLife.init(this.context);
70 | // init exception collector
71 | ExceptionHandler.init();
72 | // register batter receiver
73 | this.registerBatteryReceiver(this.context);
74 |
75 | // init recorder module
76 | this.logRecorder = new LogRecorder(this.trojanConfig);
77 |
78 | // init uploader module
79 | this.logUploader = new LogUploader(this.trojanConfig, this.logRecorder);
80 | }
81 |
82 | public void refreshUser(String user) {
83 | if (trojanConfig != null) {
84 | trojanConfig.setUserInfo(user);
85 | }
86 | if (logRecorder != null) {
87 | logRecorder.refreshUser(user);
88 | }
89 | }
90 |
91 | public void log(String tag, String msg) {
92 | log(tag, TagUtil.getVersionByTag(tag), msg, false);
93 | }
94 |
95 | public void log(String tag, int version, String msg) {
96 | log(tag, version, msg, false);
97 | }
98 |
99 | public void log(String tag, int version, String msg, boolean cryptFlag) {
100 | if (logRecorder != null && !TextUtils.isEmpty(tag) && !TextUtils.isEmpty(msg)) {
101 | logRecorder.log(tag, version, msg, cryptFlag);
102 | }
103 | }
104 |
105 | public void log(String tag, List msgList) {
106 | log(tag, TagUtil.getVersionByTag(tag), msgList, false);
107 | }
108 |
109 | public void log(String tag, int version, List msgList) {
110 | log(tag, version, msgList, false);
111 | }
112 |
113 | public void log(String tag, int version, List msgList, boolean cryptFlag) {
114 | if (logRecorder != null && !TextUtils.isEmpty(tag) && msgList != null && msgList.size() > 0) {
115 | logRecorder.log(tag, version, msgList, cryptFlag);
116 | }
117 | }
118 |
119 | public void logToJson(String tag, int version, Object obj) {
120 | logToJson(tag, version, obj, false);
121 | }
122 |
123 | public void logToJson(String tag, int version, Object obj, boolean encryptFlag) {
124 | if (logRecorder != null && !TextUtils.isEmpty(tag) && obj != null) {
125 | logRecorder.logToJson(tag, version, obj, encryptFlag);
126 | }
127 | }
128 |
129 | public void prepareUploadLogFileAsync(final WaitUploadListener listener) {
130 | if (logUploader != null && listener != null) {
131 | logUploader.prepareUploadLogFileAsync(listener);
132 | }
133 | }
134 |
135 | public File prepareUploadLogFileSync(final String dateTime) {
136 | if (logUploader != null && !TextUtils.isEmpty(dateTime)) {
137 | return logUploader.prepareUploadLogFileSync(dateTime);
138 | }
139 | return null;
140 | }
141 |
142 | public void destroy() {
143 | if (this.context != null && this.trojanReceiver != null) {
144 | this.context.unregisterReceiver(this.trojanReceiver);
145 | this.trojanReceiver = null;
146 | }
147 | }
148 |
149 | private void registerBatteryReceiver(Context context) {
150 | if (context == null) {
151 | throw new IllegalArgumentException("TrojanManager have not init");
152 | }
153 | if (this.trojanReceiver != null) {
154 | return;
155 | }
156 | this.trojanReceiver = new TrojanReceiver();
157 | IntentFilter filter = new IntentFilter();
158 | filter.addAction(Intent.ACTION_BATTERY_CHANGED);
159 | filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
160 | filter.addAction(Intent.ACTION_TIME_TICK);
161 | context.registerReceiver(this.trojanReceiver, filter);
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/config/LogConstants.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.config;
2 |
3 | /**
4 | * Created by michaelzhong on 2017/4/7.
5 | */
6 |
7 | public final class LogConstants {
8 |
9 | public static final int LOG_VERSION1 = 1;
10 |
11 | public static final int LOG_VERSION2 = 2;
12 |
13 | public static final String FIELD_SEPERATOR = "#!";
14 |
15 | public static final String INTERNAL_SEPERATOR = "#*";
16 |
17 |
18 | public static final String BASIC_TAG = "Basic";
19 |
20 | public static final String KLOG_TAG = "KLog";
21 |
22 | public static final String VIEW_CLICK_TAG = "Click";
23 |
24 | public static final String HTTP_TAG = "Http";
25 | public static final String HTTP_REQUEST_TAG = "THttpReq";
26 | public static final String HTTP_RESPONSE_TAG = "THttpRes";
27 |
28 | //Activity ActivityLife cycle
29 | public static final String ACTIVITY_LIFE_TAG = "ALife";
30 |
31 | //Fragment ActivityLife cycle
32 | public static final String FRAGMENT_LIFE_TAG = "FLife";
33 |
34 | //Dialog
35 | public static final String DIALOG_TAG = "Dialog";
36 |
37 | //Network type
38 | public static final String NETWORK_TAG = "Net";
39 |
40 | //Battery state
41 | public static final String BATTERY_TAG = "Bat";
42 |
43 | public static final String EXCEPTION_TAG = "Exception";
44 |
45 | //operate replay
46 | public static final String MOTION_TAG = "TMotion";
47 |
48 | public static final String KEY_TAG = "TKey";
49 |
50 | public static final String EDIT_TAG = "TEdit";
51 |
52 | public static final String MEMORY_TAG = "Mem";
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/config/TrojanConfig.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.config;
2 |
3 | import android.content.Context;
4 | import android.text.TextUtils;
5 |
6 | import java.io.File;
7 |
8 | import me.ele.trojan.helper.FileHelper;
9 | import me.ele.trojan.utils.AppUtils;
10 |
11 | /**
12 | * Created by michaelzhong on 2017/4/6.
13 | */
14 |
15 | public final class TrojanConfig {
16 | private Context context;
17 | private String userInfo;
18 | private String deviceId;
19 | private boolean enableLog;
20 | private boolean enableBackup;
21 | private String logDir;
22 | private String cipherKey;
23 |
24 | private TrojanConfig(final Builder builder) {
25 | this.context = builder.context;
26 | this.userInfo = builder.userInfo;
27 | this.deviceId = builder.deviceId;
28 | this.logDir = builder.logDir;
29 | this.enableLog = builder.enableLog;
30 | this.enableBackup = builder.enableBackup;
31 | this.cipherKey = builder.cipherKey;
32 | }
33 |
34 | public String getUserInfo() {
35 | return userInfo;
36 | }
37 |
38 | public void setUserInfo(String userInfo) {
39 | this.userInfo = userInfo;
40 | }
41 |
42 | public String getDeviceId() {
43 | return deviceId;
44 | }
45 |
46 | public String getLogDir() {
47 | File dirFile = new File(logDir);
48 | if (!dirFile.exists() || !dirFile.isDirectory()) {
49 | dirFile.mkdirs();
50 | }
51 | return logDir;
52 | }
53 |
54 | public Context getContext() {
55 | return context;
56 | }
57 |
58 | public boolean isEnableLog() {
59 | return enableLog;
60 | }
61 |
62 | public boolean isEnableBackup() {
63 | return enableBackup;
64 | }
65 |
66 | public String getCipherKey() {
67 | return cipherKey;
68 | }
69 |
70 | public static class Builder {
71 | private Context context;
72 | private String userInfo;
73 | private String deviceId;
74 | private String logDir;
75 | private boolean enableLog = true;
76 | private boolean enableBackup = false;
77 | private String cipherKey;
78 |
79 | public Builder(Context context) {
80 | if (null == context) {
81 | throw new IllegalArgumentException("context == null");
82 | }
83 | this.context = context;
84 | }
85 |
86 | public Builder userInfo(String userInfo) {
87 | this.userInfo = userInfo;
88 | return this;
89 | }
90 |
91 | public Builder deviceId(String deviceId) {
92 | this.deviceId = deviceId;
93 | return this;
94 | }
95 |
96 | public Builder logDir(String logDir) {
97 | this.logDir = logDir;
98 | return this;
99 | }
100 |
101 | public Builder enableLog(boolean enableLog) {
102 | this.enableLog = enableLog;
103 | return this;
104 | }
105 |
106 | public Builder enableBackup(boolean enableBackup) {
107 | this.enableBackup = enableBackup;
108 | return this;
109 | }
110 |
111 | public Builder cipherKey(String cipherKey) {
112 | if (cipherKey == null || cipherKey.length() < 16) {
113 | throw new IllegalArgumentException("the length of cipherKey must be greater than 16");
114 | }
115 | this.cipherKey = cipherKey;
116 | return this;
117 | }
118 |
119 | public TrojanConfig build() {
120 | initWithDefaultValues();
121 | return new TrojanConfig(this);
122 | }
123 |
124 | private void initWithDefaultValues() {
125 | if (userInfo == null) {
126 | userInfo = "";
127 | }
128 | if (TextUtils.isEmpty(logDir)) {
129 | logDir = FileHelper.getLogDir(context).getAbsolutePath();
130 | } else {
131 | logDir = logDir + File.separator + AppUtils.getCurProcessName(context);
132 | }
133 | }
134 | }
135 |
136 | }
137 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/config/TrojanConstants.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.config;
2 |
3 | /**
4 | * Created by michaelzhong on 2017/11/8.
5 | */
6 |
7 | public class TrojanConstants {
8 |
9 | public static final long FIVE_DAY_MILLS = 5 * 24 * 3600 * 1000L;
10 |
11 | public static final long MIN_SDCARD_FREE_SPACE_MB = 50;
12 |
13 | public static final String UP = "-up";
14 |
15 | public static final String GZ = ".gz";
16 |
17 | public static final String LOG_DIR = "trojan_log";
18 |
19 | public static final String MMAP = "-mmap";
20 |
21 | public static final String TAG_THREAD = "Threads";
22 |
23 | public static final int MIN_THREAD_NUM = 10;
24 |
25 | public static final String MB = "MB";
26 |
27 | public static int FORMAT_KB = 1024;
28 |
29 | public static int FORMAT_MB = 1024 * 1024;
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/executor/TrojanExecutor.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.executor;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | /**
7 | * Created by michaelzhong on 2017/11/7.
8 | */
9 |
10 | public class TrojanExecutor {
11 |
12 | private static volatile TrojanExecutor sInstance;
13 |
14 | private ExecutorService recordExecutor;
15 |
16 | private ExecutorService uploadExecutor;
17 |
18 | private TrojanExecutor() {
19 | recordExecutor = Executors.newSingleThreadExecutor();
20 | uploadExecutor = Executors.newSingleThreadExecutor();
21 | }
22 |
23 | public static TrojanExecutor getInstance() {
24 | if (sInstance == null) {
25 | synchronized (TrojanExecutor.class) {
26 | if (sInstance == null) {
27 | sInstance = new TrojanExecutor();
28 | }
29 | }
30 | }
31 | return sInstance;
32 | }
33 |
34 | public void executeRecord(Runnable runnable) {
35 | if (runnable == null) {
36 | return;
37 | }
38 | recordExecutor.execute(runnable);
39 | }
40 |
41 |
42 | public void executeUpload(Runnable runnable) {
43 | if (runnable == null) {
44 | return;
45 | }
46 | uploadExecutor.execute(runnable);
47 | }
48 |
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/helper/PerformanceHelper.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.helper;
2 |
3 | import android.os.Build;
4 | import android.os.Debug;
5 |
6 | import java.text.DecimalFormat;
7 | import java.util.LinkedHashMap;
8 | import java.util.LinkedList;
9 | import java.util.List;
10 | import java.util.Map;
11 | import java.util.Set;
12 |
13 | import me.ele.trojan.Trojan;
14 | import me.ele.trojan.config.LogConstants;
15 | import me.ele.trojan.config.TrojanConstants;
16 |
17 | /**
18 | * Created by michaelzhong on 2018/3/16.
19 | */
20 | public class PerformanceHelper {
21 |
22 | private static final DecimalFormat decimalFormat = new DecimalFormat("######0.00");
23 |
24 | public static void recordThread() {
25 | Map threadNumMap = new LinkedHashMap<>();
26 | Set threadSet = Thread.getAllStackTraces().keySet();
27 | for (Thread thread : threadSet) {
28 | String threadName = thread.getName().replaceAll("#?_?-?\\d+", "");
29 | if (threadNumMap.containsKey(threadName)) {
30 | threadNumMap.put(threadName, threadNumMap.get(threadName) + 1);
31 | } else {
32 | threadNumMap.put(threadName, 1);
33 | }
34 | }
35 | List msgList = new LinkedList<>();
36 | msgList.add(String.valueOf(threadSet.size()));
37 | for (Map.Entry entry : threadNumMap.entrySet()) {
38 | if (entry.getValue() >= TrojanConstants.MIN_THREAD_NUM) {
39 | msgList.add(entry.getKey() + ":" + entry.getValue());
40 | }
41 | }
42 | Trojan.log(TrojanConstants.TAG_THREAD, msgList);
43 | }
44 |
45 | public static void recordMemory() {
46 | Runtime runtime = Runtime.getRuntime();
47 | float dalvikMem = (float) ((runtime.totalMemory() - runtime.freeMemory()) * 1.0 / TrojanConstants.FORMAT_MB);
48 | float nativeMem = (float) (Debug.getNativeHeapAllocatedSize() * 1.0 / TrojanConstants.FORMAT_MB);
49 |
50 | List msgList = new LinkedList<>();
51 | msgList.add(String.valueOf(decimalFormat.format(dalvikMem + nativeMem)) + TrojanConstants.MB);
52 | msgList.add(String.valueOf(decimalFormat.format(dalvikMem)) + TrojanConstants.MB);
53 | msgList.add(String.valueOf(decimalFormat.format(nativeMem)) + TrojanConstants.MB);
54 | try {
55 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
56 | Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
57 | Debug.getMemoryInfo(memoryInfo);
58 | float stackSize = Float.parseFloat(memoryInfo.getMemoryStat("summary.stack"));
59 | msgList.add(String.valueOf(decimalFormat.format(stackSize / TrojanConstants.FORMAT_KB)) + TrojanConstants.MB);
60 | }
61 | } catch (Exception e) {
62 | e.printStackTrace();
63 | }
64 | Trojan.log(LogConstants.MEMORY_TAG, msgList);
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/helper/PermissionHelper.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.helper;
2 |
3 | import android.Manifest;
4 | import android.content.Context;
5 | import android.content.pm.PackageManager;
6 | import android.os.Build;
7 | import android.support.v4.content.ContextCompat;
8 |
9 | /**
10 | * Created by allen on 2017/11/10.
11 | */
12 |
13 | public class PermissionHelper {
14 |
15 | private PermissionHelper() {
16 | }
17 |
18 | private static boolean hasStoragePermission = false;
19 |
20 | public static boolean hasWriteAndReadStoragePermission(Context context) {
21 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
22 | return true;
23 | }
24 | //如果已经有权限了,就不再检查
25 | if (hasStoragePermission) {
26 | return true;
27 | }
28 | if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
29 | != PackageManager.PERMISSION_GRANTED) {
30 | hasStoragePermission = false;
31 | return false;
32 | }
33 | hasStoragePermission = true;
34 | return true;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/internal/ActivityLife.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.internal;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.content.Context;
6 | import android.os.Bundle;
7 |
8 | import me.ele.trojan.Trojan;
9 | import me.ele.trojan.config.LogConstants;
10 |
11 | /**
12 | * Created by michaelzhong on 17/1/20.
13 | */
14 |
15 | public class ActivityLife {
16 |
17 | public static void init(Context context) {
18 | ((Application) context.getApplicationContext()).registerActivityLifecycleCallbacks(
19 | new Application.ActivityLifecycleCallbacks() {
20 | @Override
21 | public void onActivityCreated(Activity activity, Bundle bundle) {
22 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onCreate:" + activity.getClass().getName() + " Bundle = " + bundle);
23 | }
24 |
25 | @Override
26 | public void onActivityStarted(Activity activity) {
27 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onStart:" + activity.getClass().getName());
28 | }
29 |
30 | @Override
31 | public void onActivityResumed(Activity activity) {
32 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onResume:" + activity.getClass().getName());
33 | }
34 |
35 | @Override
36 | public void onActivityPaused(Activity activity) {
37 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onPause:" + activity.getClass().getName());
38 | }
39 |
40 | @Override
41 | public void onActivityStopped(Activity activity) {
42 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onStop:" + activity.getClass().getName());
43 | }
44 |
45 | @Override
46 | public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
47 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onSaveInstanceState:" + activity.getClass().getName());
48 | }
49 |
50 | @Override
51 | public void onActivityDestroyed(Activity activity) {
52 | Trojan.log(LogConstants.ACTIVITY_LIFE_TAG, "onDestroy:" + activity.getClass().getName());
53 | }
54 | }
55 | );
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/internal/ExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.internal;
2 |
3 | import me.ele.trojan.Trojan;
4 | import me.ele.trojan.config.LogConstants;
5 |
6 | /**
7 | * Created by Eric on 17/1/20.
8 | */
9 |
10 | public class ExceptionHandler {
11 |
12 | public static void init() {
13 | final Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
14 | Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
15 | @Override
16 | public void uncaughtException(Thread thread, Throwable throwable) {
17 | Trojan.log(LogConstants.EXCEPTION_TAG, "Exception occurred in Thread " + thread.getName());
18 | Trojan.log(LogConstants.EXCEPTION_TAG, "Exception type: " + throwable.getClass().getName());
19 | Trojan.log(LogConstants.EXCEPTION_TAG, "Exception message: " + throwable.getMessage());
20 | StackTraceElement[] stackTraceElements = throwable.getStackTrace();
21 | for (StackTraceElement stackTraceElement : stackTraceElements) {
22 | StringBuilder stackBuilder = new StringBuilder();
23 | stackBuilder.append(" ")
24 | .append(stackTraceElement.getClassName())
25 | .append(" ")
26 | .append(stackTraceElement.getMethodName())
27 | .append("(")
28 | .append(stackTraceElement.getFileName())
29 | .append(":")
30 | .append(stackTraceElement.getLineNumber())
31 | .append(")");
32 | Trojan.log(LogConstants.EXCEPTION_TAG, stackBuilder.toString());
33 | }
34 | handler.uncaughtException(thread, throwable);
35 | }
36 | });
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/listener/PrepareUploadListener.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.listener;
2 |
3 | import java.io.File;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by allen on 2017/11/8.
8 | */
9 |
10 | public interface PrepareUploadListener {
11 |
12 | void readyToUpload();
13 |
14 | void failToReady();
15 | }
16 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/listener/WaitUploadListener.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.listener;
2 |
3 | import java.io.File;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by allen on 17/6/16.
8 | */
9 |
10 | public interface WaitUploadListener {
11 |
12 | void onReadyToUpload(String user, String device, List waitUploadFileList);
13 |
14 | void onReadyFail();
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/log/Logger.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.log;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * Created by allen on 17/6/29.
7 | */
8 |
9 | public class Logger {
10 | private static final String TAG = "Trojan";
11 | private static boolean sLogOn = false;
12 |
13 | public static void setLog(boolean on) {
14 | sLogOn = on;
15 | }
16 |
17 | public static void e(String msg) {
18 | if (sLogOn) {
19 | Log.e(TAG, msg);
20 | }
21 | }
22 |
23 | public static void i(String msg) {
24 | if (sLogOn) {
25 | Log.i(TAG, msg);
26 | }
27 | }
28 |
29 | public static void e(String tag, String msg) {
30 | if (sLogOn) {
31 | Log.e(tag, msg);
32 | }
33 | }
34 |
35 | public static void i(String tag, String msg) {
36 | if (sLogOn) {
37 | Log.e(tag, msg);
38 | }
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/receiver/TrojanReceiver.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.receiver;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.net.ConnectivityManager;
7 | import android.os.BatteryManager;
8 |
9 | import java.util.LinkedList;
10 | import java.util.List;
11 |
12 | import me.ele.trojan.Trojan;
13 | import me.ele.trojan.config.LogConstants;
14 | import me.ele.trojan.executor.TrojanExecutor;
15 | import me.ele.trojan.helper.PerformanceHelper;
16 | import me.ele.trojan.log.Logger;
17 | import me.ele.trojan.utils.NetworkUtils;
18 |
19 | /**
20 | * Created by wangallen on 2017/3/29.
21 | */
22 |
23 | public class TrojanReceiver extends BroadcastReceiver {
24 |
25 | @Override
26 | public void onReceive(Context context, Intent intent) {
27 | final String action = intent.getAction();
28 | Logger.i("TrojanReceiver-->action:" + action);
29 | if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
30 | showBatteryState(intent);
31 | } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
32 | showNetworkType(context);
33 | } else if (Intent.ACTION_TIME_TICK.equals(action)) {
34 | TrojanExecutor.getInstance().executeUpload(new Runnable() {
35 | @Override
36 | public void run() {
37 | PerformanceHelper.recordMemory();
38 | PerformanceHelper.recordThread();
39 | }
40 | });
41 | }
42 | }
43 |
44 | private void showNetworkType(Context context) {
45 | int networkType = NetworkUtils.getNetworkType(context.getApplicationContext());
46 | Trojan.log(LogConstants.NETWORK_TAG, networkType + "");
47 | }
48 |
49 | private void showBatteryState(Intent intent) {
50 | int status = intent.getIntExtra("status", 0);
51 | int level = intent.getIntExtra("level", 0);
52 | String statusResult = "discharging";
53 | switch (status) {
54 | case BatteryManager.BATTERY_STATUS_UNKNOWN:
55 | statusResult = "discharging";
56 | break;
57 | case BatteryManager.BATTERY_STATUS_CHARGING:
58 | statusResult = "charging";
59 | break;
60 | case BatteryManager.BATTERY_STATUS_DISCHARGING:
61 | statusResult = "discharging";
62 | break;
63 | case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
64 | statusResult = "discharging";
65 | break;
66 | case BatteryManager.BATTERY_STATUS_FULL:
67 | statusResult = "charging";
68 | break;
69 | }
70 |
71 | List msgList = new LinkedList<>();
72 | msgList.add(String.valueOf((level * 1.00 / 100)));
73 | msgList.add(statusResult);
74 | Trojan.log(LogConstants.BATTERY_TAG, msgList);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/ILogFormatter.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * Created by allen on 2017/11/7.
7 | */
8 |
9 | public interface ILogFormatter {
10 |
11 | String format(String tag, int version, String msg, boolean crypt);
12 |
13 | String format(String tag, int version, List msgFieldList, boolean crypt);
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/ILogRecorder.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record;
2 |
3 | import java.io.File;
4 | import java.util.List;
5 |
6 | import me.ele.trojan.listener.PrepareUploadListener;
7 |
8 | /**
9 | * Created by michaelzhong on 2017/11/7.
10 | */
11 |
12 | public interface ILogRecorder {
13 |
14 | void refreshUser(String user);
15 |
16 | void prepareUploadAsync(PrepareUploadListener listener);
17 |
18 | File prepareUploadSync(String dateTime);
19 |
20 | void log(String tag, int version, String msg, boolean cryptFlag);
21 |
22 | void log(String tag, int version, List msgFieldList, boolean cryptFlag);
23 |
24 | void logToJson(String tag, int version, Object o, boolean encryptFlag);
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/ILogWriter.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * Created by allen on 2017/11/7.
7 | */
8 |
9 | public interface ILogWriter {
10 |
11 | void init(Context context, String basicInfo, String dir, String key) throws Throwable;
12 |
13 | void write(String content, boolean cryptFlag) throws Throwable;
14 |
15 | void refreshBasicInfo(String basicInfo);
16 |
17 | //为上传做准备,需要做三件事:第一是关闭当前文件,如果有映射的话,需要取消映射;第二是新建一个文件;第三是对于新文件重新打开输入流或者重新映射
18 | void closeAndRenew();
19 |
20 | boolean isLogFileExist();
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/impl/LogFormatter.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record.impl;
2 |
3 | import java.text.SimpleDateFormat;
4 | import java.util.Calendar;
5 | import java.util.List;
6 | import java.util.Locale;
7 |
8 | import me.ele.trojan.config.LogConstants;
9 | import me.ele.trojan.record.ILogFormatter;
10 |
11 | /**
12 | * Created by allen on 2017/11/7.
13 | */
14 |
15 | public class LogFormatter implements ILogFormatter {
16 |
17 | private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
18 |
19 | private final StringBuilder content = new StringBuilder();
20 |
21 | @Override
22 | public String format(String tag, int version, String msg, boolean crypt) {
23 | if (content.length() > 0) {
24 | content.delete(0, content.length());
25 | }
26 | content.append(tag);
27 | content.append(LogConstants.FIELD_SEPERATOR);
28 | content.append(getTime());
29 | content.append(LogConstants.FIELD_SEPERATOR);
30 | content.append("v");
31 | content.append(version);
32 | content.append(LogConstants.FIELD_SEPERATOR);
33 | content.append(msg);
34 | if (!crypt) {
35 | content.append('\n');
36 | }
37 | return content.toString();
38 | }
39 |
40 | @Override
41 | public String format(String tag, int version, List msgFieldList, boolean crypt) {
42 | if (content.length() > 0) {
43 | content.delete(0, content.length());
44 | }
45 | content.append(tag);
46 | content.append(LogConstants.FIELD_SEPERATOR);
47 | content.append(getTime());
48 | content.append(LogConstants.FIELD_SEPERATOR);
49 | content.append("v");
50 | content.append(version);
51 | content.append(LogConstants.FIELD_SEPERATOR);
52 |
53 | int size = msgFieldList.size();
54 | for (int i = 0; i < size; ++i) {
55 | content.append(msgFieldList.get(i));
56 | if (i < size - 1) {
57 | content.append(LogConstants.INTERNAL_SEPERATOR);
58 | }
59 | }
60 | if (!crypt) {
61 | content.append('\n');
62 | }
63 | return content.toString();
64 | }
65 |
66 | private String getTime() {
67 | return sdf.format(Calendar.getInstance().getTime());
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/impl/LogRecorder.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record.impl;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 | import android.os.Looper;
6 | import android.text.TextUtils;
7 |
8 | import java.io.File;
9 | import java.util.List;
10 |
11 | import me.ele.trojan.config.LogConstants;
12 | import me.ele.trojan.config.TrojanConfig;
13 | import me.ele.trojan.config.TrojanConstants;
14 | import me.ele.trojan.executor.TrojanExecutor;
15 | import me.ele.trojan.helper.FileHelper;
16 | import me.ele.trojan.helper.PermissionHelper;
17 | import me.ele.trojan.listener.PrepareUploadListener;
18 | import me.ele.trojan.log.Logger;
19 | import me.ele.trojan.record.ILogFormatter;
20 | import me.ele.trojan.record.ILogRecorder;
21 | import me.ele.trojan.record.ILogWriter;
22 | import me.ele.trojan.utils.AppUtils;
23 | import me.ele.trojan.utils.DateUtils;
24 | import me.ele.trojan.utils.DeviceUtils;
25 | import me.ele.trojan.utils.GsonUtils;
26 | import me.ele.trojan.utils.TagUtil;
27 |
28 | /**
29 | * Created by michaelzhong on 2017/11/7.
30 | */
31 | public class LogRecorder implements ILogRecorder {
32 |
33 | private ILogFormatter logFormatter;
34 |
35 | /**
36 | * If the MmapLogWriter's initialization have problem, change to use NormalLogWriter
37 | */
38 | private ILogWriter logWriter;
39 |
40 | private Handler handler = new Handler(Looper.getMainLooper());
41 |
42 | private Context context;
43 |
44 | private TrojanConfig config;
45 | private String dirPath;
46 | private String cipherKey;
47 |
48 | public LogRecorder(final TrojanConfig config) {
49 | this.logFormatter = new LogFormatter();
50 | this.config = config;
51 | this.context = config.getContext();
52 | this.cipherKey = config.getCipherKey();
53 |
54 | TrojanExecutor.getInstance().executeRecord(new Runnable() {
55 | @Override
56 | public void run() {
57 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
58 | Logger.e("no permission for init");
59 | return;
60 | }
61 | tryInitLogWriter();
62 | }
63 | });
64 | }
65 |
66 |
67 | private synchronized void tryInitLogWriter() {
68 | if (null != logWriter) {
69 | return;
70 | }
71 | dirPath = FileHelper.getTempDir(context).getAbsolutePath();
72 | Logger.i("LogRecorder-->tryInitLogWriter,dirPath:" + dirPath);
73 |
74 | if (!config.isEnableBackup()) {
75 | try {
76 | MmapLogWriter mmapLogWriter = new MmapLogWriter();
77 | String basicInfo = logFormatter.format(LogConstants.BASIC_TAG, TagUtil.getVersionByTag(LogConstants.BASIC_TAG), getBasicInfo(config), false);
78 | mmapLogWriter.init(context, basicInfo, dirPath, cipherKey);
79 | logWriter = mmapLogWriter;
80 | } catch (Throwable ex) {
81 | ex.printStackTrace();
82 | initNormalLogWriter();
83 | }
84 | } else {
85 | initNormalLogWriter();
86 | }
87 |
88 | }
89 |
90 | @Override
91 | public void refreshUser(String user) {
92 | config.setUserInfo(user);
93 | TrojanExecutor.getInstance().executeRecord(new Runnable() {
94 | @Override
95 | public void run() {
96 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
97 | Logger.e("no permission for refreshUser");
98 | return;
99 | }
100 | String basicInfo = logFormatter.format(LogConstants.BASIC_TAG, TagUtil.getVersionByTag(LogConstants.BASIC_TAG), getBasicInfo(config), false);
101 | try {
102 | tryInitLogWriter();
103 | logWriter.refreshBasicInfo(basicInfo);
104 | logWriter.write(basicInfo, false);
105 | } catch (Throwable ex) {
106 | ex.printStackTrace();
107 | if (!(logWriter instanceof NormalLogWriter)) {
108 | initNormalLogWriter();
109 | logWriter.refreshBasicInfo(basicInfo);
110 | tryWriteLog(basicInfo, false);
111 | }
112 | }
113 |
114 | }
115 | });
116 | }
117 |
118 | @Override
119 | public void log(final String tag, final int version, final String msg, final boolean encryptFlag) {
120 | if (TextUtils.isEmpty(tag) || TextUtils.isEmpty(msg)) {
121 | return;
122 | }
123 | TrojanExecutor.getInstance().executeRecord(new Runnable() {
124 | @Override
125 | public void run() {
126 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
127 | Logger.e("no permission for log");
128 | return;
129 | }
130 | checkInitAndRecordSync(logFormatter.format(tag, version, msg, encryptFlag), encryptFlag);
131 | }
132 | });
133 | }
134 |
135 | @Override
136 | public void log(final String tag, final int version, final List msgFieldList, final boolean encryptFlag) {
137 | if (TextUtils.isEmpty(tag) || msgFieldList == null || msgFieldList.size() == 0) {
138 | return;
139 | }
140 | TrojanExecutor.getInstance().executeRecord(new Runnable() {
141 | @Override
142 | public void run() {
143 | //然后要判断是否logWriter是否已经初始化(因为可能在这之前都没权限),如果还没初始化的话,需要先初始化
144 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
145 | Logger.e("no permission for log msgFieldList");
146 | return;
147 | }
148 | checkInitAndRecordSync(logFormatter.format(tag, version, msgFieldList, encryptFlag), encryptFlag);
149 | }
150 | });
151 | }
152 |
153 | @Override
154 | public void logToJson(final String tag, final int version, final Object obj, final boolean encryptFlag) {
155 | if (TextUtils.isEmpty(tag) || obj == null) {
156 | return;
157 | }
158 | TrojanExecutor.getInstance().executeRecord(new Runnable() {
159 | @Override
160 | public void run() {
161 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
162 | Logger.e("no permission for logToJson");
163 | return;
164 | }
165 | checkInitAndRecordSync(logFormatter.format(tag, version, GsonUtils.toJson(obj), encryptFlag), encryptFlag);
166 | }
167 | });
168 | }
169 |
170 | @Override
171 | public void prepareUploadAsync(final PrepareUploadListener listener) {
172 | if (listener == null) {
173 | return;
174 | }
175 | TrojanExecutor.getInstance().executeRecord(new Runnable() {
176 | @Override
177 | public void run() {
178 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
179 | Logger.e("no permission for prepareUploadAsync");
180 | handler.post(new Runnable() {
181 | @Override
182 | public void run() {
183 | listener.failToReady();
184 | }
185 | });
186 | return;
187 | }
188 | tryInitLogWriter();
189 | logWriter.closeAndRenew();
190 |
191 | final String writeFileName = DateUtils.getDate() + (logWriter instanceof MmapLogWriter ? TrojanConstants.MMAP : "");
192 | // avoid to block write operation, we just rename except the writing log file, have not compress log file
193 | FileHelper.renameToUpAllIfNeed(config.getContext(), writeFileName, config.getLogDir());
194 |
195 | handler.post(new Runnable() {
196 | @Override
197 | public void run() {
198 | listener.readyToUpload();
199 | }
200 | });
201 | }
202 | });
203 | }
204 |
205 | @Override
206 | public File prepareUploadSync(String dateTime) {
207 | if (TextUtils.isEmpty(dateTime) || !PermissionHelper.hasWriteAndReadStoragePermission(context)) {
208 | return null;
209 | }
210 | if (dateTime.equals(DateUtils.getDate())) {
211 | tryInitLogWriter();
212 | logWriter.closeAndRenew();
213 | }
214 | return FileHelper.getLogFileByDate(context, config.getLogDir(), dateTime);
215 | }
216 |
217 | private void initNormalLogWriter() {
218 | Logger.e("initNormalLogWriter");
219 | try {
220 | NormalLogWriter normalLogWriter = new NormalLogWriter();
221 | String basicInfo = logFormatter.format(LogConstants.BASIC_TAG, TagUtil.getVersionByTag(LogConstants.BASIC_TAG), getBasicInfo(config), false);
222 | normalLogWriter.init(context, basicInfo, dirPath, cipherKey);
223 | logWriter = normalLogWriter;
224 | } catch (Throwable e) {
225 | e.printStackTrace();
226 | }
227 | }
228 |
229 | private void tryWriteLog(String content, boolean encryptFlag) {
230 | try {
231 | logWriter.write(content, encryptFlag);
232 | } catch (Throwable e) {
233 | e.printStackTrace();
234 | }
235 | }
236 |
237 | private String getBasicInfo(TrojanConfig config) {
238 | StringBuilder stringBuilder = new StringBuilder();
239 | stringBuilder.append("Android")
240 | .append(LogConstants.INTERNAL_SEPERATOR)
241 | .append(AppUtils.getCurProcessName(context))
242 | .append(LogConstants.INTERNAL_SEPERATOR)
243 | .append(AppUtils.getVersionName(context))
244 | .append(LogConstants.INTERNAL_SEPERATOR)
245 | .append("~")
246 | .append(LogConstants.INTERNAL_SEPERATOR)
247 | .append(config.getUserInfo())
248 | .append(LogConstants.INTERNAL_SEPERATOR)
249 | .append(config.getDeviceId())
250 | .append(LogConstants.INTERNAL_SEPERATOR)
251 | .append(DeviceUtils.getDeviceInfo())
252 | .append(LogConstants.INTERNAL_SEPERATOR)
253 | .append(DeviceUtils.isRoot() ? 1 : 0);
254 | return stringBuilder.toString();
255 | }
256 |
257 | /**
258 | * check whether logWriter is initialized or not firstly.
259 | * then write the content to log file.
260 | *
261 | * @param msgContent
262 | * @param encryptFlag
263 | */
264 | private void checkInitAndRecordSync(String msgContent, boolean encryptFlag) {
265 | if (TextUtils.isEmpty(msgContent)) {
266 | return;
267 | }
268 | tryInitLogWriter();
269 | try {
270 | logWriter.write(msgContent, encryptFlag);
271 | } catch (Throwable ex) {
272 | ex.printStackTrace();
273 | if (!(logWriter instanceof NormalLogWriter)) {
274 | initNormalLogWriter();
275 | tryWriteLog(msgContent, encryptFlag);
276 | }
277 | }
278 | }
279 |
280 | }
281 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/impl/MmapLogWriter.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record.impl;
2 |
3 | import android.content.Context;
4 |
5 | import java.io.File;
6 | import java.util.concurrent.atomic.AtomicBoolean;
7 |
8 | import me.ele.trojan.config.TrojanConstants;
9 | import me.ele.trojan.log.Logger;
10 | import me.ele.trojan.record.ILogWriter;
11 | import me.ele.trojan.utils.DateUtils;
12 |
13 | /**
14 | * mmap方式写入,主要是封装了jni操作
15 | * Created by allen on 2017/11/7.
16 | */
17 |
18 | public class MmapLogWriter implements ILogWriter {
19 |
20 | static {
21 | try {
22 | System.loadLibrary("trojan-lib");
23 | } catch (Throwable throwable) {
24 | throwable.printStackTrace();
25 | }
26 | }
27 |
28 | private native long nativeInit(String basicInfo, String dir, String key);
29 |
30 | private native long nativeWrite(long logWriterObject, String msgContent, boolean encryptFlag);
31 |
32 | //刷新用户后,需要更新基础信息
33 | private native void nativeRefreshBasicInfo(long logWriterObject, String basicInfo);
34 |
35 | private native void nativeCloseAndRenew(long logWriterObject);
36 |
37 | private final AtomicBoolean initFlag = new AtomicBoolean(false);
38 |
39 | //C++ LogWriter对象的句柄
40 | private long nativeLogWriter;
41 |
42 | private String logFileDir;
43 | private String buildDate;
44 | private File logFile;
45 |
46 | @Override
47 | public void init(Context context, final String basicInfoContent, final String dir, String key) throws Throwable {
48 | Logger.i("MmapWriter", "MMapLogWriter-->init");
49 | logFileDir = dir;
50 | buildDate = DateUtils.getDate();
51 | nativeLogWriter = nativeInit(basicInfoContent, dir, key);
52 | initFlag.set(true);
53 | logFile = new File(logFileDir + File.separator + buildDate + TrojanConstants.MMAP);
54 | }
55 |
56 | @Override
57 | public void write(String content, boolean encryptFlag) throws Exception {
58 | if (nativeLogWriter <= 0) {
59 | Logger.i("nativeLogWriter is null,return");
60 | return;
61 | }
62 | if (!initFlag.get()) {
63 | Logger.i("has not been init");
64 | return;
65 | }
66 | // 判断写入的时候日期是否是当天,判断日志文件是否存在
67 | if (!DateUtils.getDate().equals(buildDate) || !isLogFileExist()) {
68 | // 确保文件目录存在,以防被手动删除
69 | File dir = new File(logFileDir);
70 | if (!dir.exists()) {
71 | dir.mkdirs();
72 | }
73 |
74 | buildDate = DateUtils.getDate();
75 | closeAndRenew();
76 | logFile = new File(logFileDir + File.separator + buildDate + TrojanConstants.MMAP);
77 | }
78 | nativeWrite(nativeLogWriter, content, encryptFlag);
79 | }
80 |
81 |
82 | @Override
83 | public void refreshBasicInfo(String basicInfo) {
84 | Logger.i("MmapWriter", "MmapLogWriter-->refreshBasicInfo");
85 | if (nativeLogWriter <= 0) {
86 | return;
87 | }
88 | nativeRefreshBasicInfo(nativeLogWriter, basicInfo);
89 | }
90 |
91 | /**
92 | * 这个其实是有两个用处,第一个用处当然是上传时;
93 | * 第二个用处是如果发现当前日期和现在日期不一样,也要进行这样的操作。
94 | */
95 | @Override
96 | public void closeAndRenew() {
97 | if (nativeLogWriter <= 0) {
98 | return;
99 | }
100 | nativeCloseAndRenew(nativeLogWriter);
101 | }
102 |
103 | @Override
104 | public boolean isLogFileExist() {
105 | return logFile != null && logFile.exists();
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/record/impl/NormalLogWriter.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.record.impl;
2 |
3 | import android.content.Context;
4 |
5 | import java.io.BufferedWriter;
6 | import java.io.File;
7 | import java.io.FileOutputStream;
8 | import java.io.IOException;
9 | import java.io.OutputStreamWriter;
10 | import java.util.concurrent.atomic.AtomicBoolean;
11 |
12 | import me.ele.trojan.config.TrojanConstants;
13 | import me.ele.trojan.log.Logger;
14 | import me.ele.trojan.record.ILogWriter;
15 | import me.ele.trojan.utils.DateUtils;
16 | import me.ele.trojan.utils.IOUtil;
17 |
18 | /**
19 | * Created by allen on 2017/11/7.
20 | */
21 |
22 | /**
23 | * 这个类的加密还没实现
24 | */
25 | public class NormalLogWriter implements ILogWriter {
26 |
27 | private Context context;
28 | private String basicInfoContent;
29 | private String logFileDir;
30 | private String buildDate;
31 | private File logFile;
32 |
33 | private final AtomicBoolean initFlag = new AtomicBoolean(false);
34 |
35 | private BufferedWriter bufferedWriter;
36 |
37 | @Override
38 | public void init(Context context, String basicInfoContent, String dir, String key) {
39 | Logger.i("NormalLogWriter-->init");
40 | this.context = context;
41 | this.basicInfoContent = basicInfoContent;
42 | this.logFileDir = dir;
43 | buildStream();
44 | initFlag.set(true);
45 | }
46 |
47 | @Override
48 | public void write(String content, boolean encryptFlag) {
49 | try {
50 | if (null == bufferedWriter) {
51 | return;
52 | }
53 | // 判断写入的时候日期是否是当天,判断日志文件是否存在
54 | if (!DateUtils.getDate().equals(buildDate) || !isLogFileExist()) {
55 | // 确保文件目录存在,以防被手动删除
56 | File dir = new File(logFileDir);
57 | if (!dir.exists()) {
58 | dir.mkdirs();
59 | }
60 |
61 | closeAndRenew();
62 | }
63 | bufferedWriter.write(content);
64 | bufferedWriter.flush();
65 |
66 | } catch (IOException e) {
67 | e.printStackTrace();
68 | Logger.e("write exception:" + e.getMessage());
69 | }
70 | }
71 |
72 | @Override
73 | public void refreshBasicInfo(String basicInfo) {
74 | this.basicInfoContent = basicInfo;
75 | }
76 |
77 | @Override
78 | public void closeAndRenew() {
79 | //首先关闭文件
80 | IOUtil.closeQuietly(bufferedWriter);
81 | //然后重命名文件
82 | String upFilePath = logFileDir + File.separator + buildDate + TrojanConstants.UP;
83 | File upFile = new File(upFilePath);
84 | if (upFile.exists()) {
85 | upFile.delete();
86 | }
87 |
88 | File file = new File(logFileDir, buildDate);
89 | file.renameTo(upFile);
90 | //最后新建输入流
91 | buildStream();
92 | }
93 |
94 | @Override
95 | public boolean isLogFileExist() {
96 | return logFile != null && logFile.exists();
97 | }
98 |
99 | private void buildStream() {
100 | Logger.i("buildStream");
101 | File dir = new File(logFileDir);
102 | if (!dir.exists()) {
103 | dir.mkdirs();
104 | }
105 | String date = DateUtils.getDate();
106 | File file = new File(dir, date);
107 | boolean exist = file.exists();
108 | try {
109 | if (!exist) {
110 | file.createNewFile();
111 | }
112 | logFile = file;
113 | FileOutputStream fos = new FileOutputStream(file, exist);
114 | OutputStreamWriter writer = new OutputStreamWriter(fos);
115 | bufferedWriter = new BufferedWriter(writer);
116 | buildDate = date;
117 |
118 | if (!exist) {
119 | writeBasicInfo();
120 | }
121 | } catch (IOException e) {
122 | Logger.e("buildStream exception:" + e.getMessage());
123 | e.printStackTrace();
124 | }
125 | }
126 |
127 | private void writeBasicInfo() {
128 | try {
129 | bufferedWriter.write(basicInfoContent);
130 | bufferedWriter.flush();
131 | } catch (IOException ex) {
132 | ex.printStackTrace();
133 | Logger.e("writeBasicInfo exception:" + ex.getMessage());
134 | }
135 | }
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/upload/ILogUploader.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.upload;
2 |
3 | import java.io.File;
4 |
5 | import me.ele.trojan.listener.WaitUploadListener;
6 |
7 | /**
8 | * Created by michaelzhong on 2017/11/7.
9 | */
10 |
11 | public interface ILogUploader {
12 |
13 | void prepareUploadLogFileAsync(final WaitUploadListener waitUploadListener);
14 |
15 | File prepareUploadLogFileSync(final String dateTime);
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/upload/impl/LogUploader.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.upload.impl;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 | import android.os.Looper;
6 |
7 | import java.io.File;
8 | import java.util.List;
9 |
10 | import me.ele.trojan.config.TrojanConfig;
11 | import me.ele.trojan.executor.TrojanExecutor;
12 | import me.ele.trojan.helper.FileHelper;
13 | import me.ele.trojan.helper.PermissionHelper;
14 | import me.ele.trojan.listener.PrepareUploadListener;
15 | import me.ele.trojan.listener.WaitUploadListener;
16 | import me.ele.trojan.log.Logger;
17 | import me.ele.trojan.record.ILogRecorder;
18 | import me.ele.trojan.upload.ILogUploader;
19 |
20 | /**
21 | * Created by michaelzhong on 2017/11/7.
22 | */
23 |
24 | public class LogUploader implements ILogUploader {
25 |
26 | private final Handler handler = new Handler(Looper.getMainLooper());
27 |
28 | private Context context;
29 |
30 | private TrojanConfig trojanConfig;
31 |
32 | private ILogRecorder logRecorder;
33 |
34 | public LogUploader(final TrojanConfig trojanConfig, ILogRecorder logRecorder) {
35 | if (trojanConfig == null || logRecorder == null) {
36 | throw new IllegalArgumentException("trojanConfig or logRecorder can not be null");
37 | }
38 | this.context = trojanConfig.getContext();
39 | this.trojanConfig = trojanConfig;
40 | this.logRecorder = logRecorder;
41 |
42 | // should check upload file when init
43 | TrojanExecutor.getInstance().executeUpload(new Runnable() {
44 | @Override
45 | public void run() {
46 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
47 | Logger.e("no permission for cleanUp");
48 | return;
49 | }
50 | FileHelper.cleanUpLogFile(context, trojanConfig.getLogDir());
51 | }
52 | });
53 | }
54 |
55 | @Override
56 | public void prepareUploadLogFileAsync(final WaitUploadListener waitUploadListener) {
57 | if (logRecorder == null || waitUploadListener == null) {
58 | Logger.e("LogUploader-->prepareUploadLogFileAsync,waitUploadListener null");
59 | return;
60 | }
61 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
62 | Logger.e("LogUploader-->prepareUploadLogFileAsync,no permission");
63 | waitUploadListener.onReadyFail();
64 | return;
65 | }
66 | // execute upload task after notify the LogRecorder module to close log file
67 | logRecorder.prepareUploadAsync(new PrepareUploadListener() {
68 | @Override
69 | public void readyToUpload() {
70 | Logger.i("LogUploader-->readyToUpload");
71 | TrojanExecutor.getInstance().executeUpload(new Runnable() {
72 | @Override
73 | public void run() {
74 | final List gzFileList = FileHelper.cleanUpLogFile(context, trojanConfig.getLogDir());
75 | notifyPrepareListener(waitUploadListener, true, gzFileList);
76 | }
77 | });
78 |
79 | }
80 |
81 | @Override
82 | public void failToReady() {
83 | Logger.e("LogUploader-->failToReady");
84 | waitUploadListener.onReadyFail();
85 | }
86 | });
87 | }
88 |
89 | @Override
90 | public File prepareUploadLogFileSync(String dateTime) {
91 | if (logRecorder == null) {
92 | return null;
93 | }
94 | if (!PermissionHelper.hasWriteAndReadStoragePermission(context)) {
95 | Logger.e("LogUploader-->prepareUploadLogFileSync,no permission");
96 | return null;
97 | }
98 | return logRecorder.prepareUploadSync(dateTime);
99 | }
100 |
101 | private void notifyPrepareListener(final WaitUploadListener waitUploadListener, final boolean isSuccess, final List gzFileList) {
102 | if (waitUploadListener == null) {
103 | return;
104 | }
105 | handler.post(new Runnable() {
106 | @Override
107 | public void run() {
108 | if (isSuccess && gzFileList != null && gzFileList.size() > 0) {
109 | waitUploadListener.onReadyToUpload(trojanConfig.getUserInfo(), trojanConfig.getDeviceId(), gzFileList);
110 | } else {
111 | waitUploadListener.onReadyFail();
112 | }
113 | }
114 | });
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/AppUtils.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import android.app.ActivityManager;
4 | import android.content.Context;
5 | import android.content.pm.PackageInfo;
6 | import android.content.pm.PackageManager;
7 | import android.os.Build;
8 |
9 | /**
10 | * Created by michaelzhong on 2017/12/22.
11 | */
12 |
13 | public class AppUtils {
14 |
15 | public static final String getDeviceModel() {
16 | return Build.MODEL;
17 | }
18 |
19 | public static final int getSDKInt() {
20 | return Build.VERSION.SDK_INT;
21 | }
22 |
23 | public static final String getVersionName(Context context) {
24 | try {
25 | PackageManager packageManager = context.getPackageManager();
26 | PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
27 | return packageInfo.versionName;
28 | } catch (Exception ex) {
29 | ex.printStackTrace();
30 | return "UNKNOWN";
31 | }
32 | }
33 |
34 | /**
35 | * get the process name of the current process considering mutiprocess
36 | *
37 | * @param context
38 | * @return String
39 | */
40 | public static final String getCurProcessName(Context context) {
41 | if (context != null) {
42 | int pid = android.os.Process.myPid();
43 | ActivityManager mActivityManager = (ActivityManager) context
44 | .getSystemService(Context.ACTIVITY_SERVICE);
45 | for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
46 | .getRunningAppProcesses()) {
47 | if (appProcess.pid == pid) {
48 | return appProcess.processName;
49 | }
50 | }
51 | }
52 | return "UNKNOWN";
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/DateUtils.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import java.text.SimpleDateFormat;
4 | import java.util.Calendar;
5 | import java.util.Locale;
6 |
7 | /**
8 | * Created by michaelzhong on 2017/11/7.
9 | */
10 |
11 | public class DateUtils {
12 |
13 | private static final SimpleDateFormat dfYMD = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
14 |
15 | public static String getDate() {
16 | return dfYMD.format(Calendar.getInstance().getTime());
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/DeviceUtils.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import android.os.Build;
4 |
5 | import java.io.BufferedReader;
6 | import java.io.File;
7 | import java.io.IOException;
8 | import java.io.InputStreamReader;
9 |
10 | /**
11 | * Created by wangallen on 2017/3/29.
12 | */
13 |
14 | public class DeviceUtils {
15 |
16 | public static String getDeviceModel() {
17 | return Build.MODEL;
18 | }
19 |
20 | public static final int getSDKInt() {
21 | return Build.VERSION.SDK_INT;
22 | }
23 |
24 | public static final String getDeviceInfo() {
25 | return DeviceUtils.getDeviceModel() + "," + DeviceUtils.getSDKInt();
26 | }
27 |
28 | /**
29 | * To get whether the device is root or not
30 | */
31 | public static boolean isRoot() {
32 | String binPath = "/system/bin/su";
33 | String xBinPath = "/system/xbin/su";
34 | return (new File(binPath)).exists() && isExecutable(binPath) || (new File(xBinPath)).exists() && isExecutable(xBinPath);
35 | }
36 |
37 | private static boolean isExecutable(String filePath) {
38 | Process p = null;
39 | BufferedReader in = null;
40 |
41 | try {
42 | p = Runtime.getRuntime().exec("ls -l " + filePath);
43 | in = new BufferedReader(new InputStreamReader(p.getInputStream()));
44 | String e = in.readLine();
45 | if (e == null || e.length() < 4) {
46 | return false;
47 | }
48 | char flag = e.charAt(3);
49 | if (flag != 115 && flag != 120) {
50 | return false;
51 | }
52 | return true;
53 | } catch (IOException var16) {
54 | var16.printStackTrace();
55 | return false;
56 | } finally {
57 | if (p != null) {
58 | p.destroy();
59 | }
60 | IOUtil.closeQuietly(in);
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/GsonUtils.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import com.google.gson.Gson;
4 |
5 | import java.lang.reflect.Type;
6 |
7 | /**
8 | * Created by michaelzhong on 2017/8/18.
9 | */
10 |
11 | public class GsonUtils {
12 |
13 | private static final Gson GSON = new Gson();
14 |
15 | public static String toJson(Object obj) {
16 | if (null == obj) {
17 | return "";
18 | }
19 | return GSON.toJson(obj);
20 | }
21 |
22 | public static Object fromJson(String json, Type classType) {
23 | if (null == json) {
24 | return null;
25 | }
26 | return GSON.fromJson(json, classType);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/IOUtil.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import java.io.Closeable;
4 |
5 | /**
6 | * Created by michaelzhong on 2017/4/11.
7 | */
8 |
9 | public final class IOUtil {
10 |
11 | public static void closeQuietly(Closeable closeable) {
12 | if (closeable != null) {
13 | try {
14 | closeable.close();
15 | } catch (RuntimeException ex) {
16 | throw ex;
17 | } catch (Exception ignored) {
18 |
19 | }
20 | }
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/NetworkUtils.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import android.content.Context;
4 | import android.net.ConnectivityManager;
5 | import android.net.NetworkInfo;
6 | import android.telephony.TelephonyManager;
7 |
8 | /**
9 | * Created by michaelzhong on 2017/3/29.
10 | */
11 |
12 | public class NetworkUtils {
13 |
14 | public static final int NETWORK_NONE = 0;
15 | public static final int NETWORK_WIFI = 1;
16 | public static final int NETWORK_2G = 2;
17 | public static final int NETWORK_3G = 3;
18 | public static final int NETWORK_4G = 4;
19 | public static final int NETWORK_UNKNOWN_MOBILE = 5;
20 |
21 | public static int getNetworkType(Context context) {
22 | if (null == context) {
23 | return NETWORK_NONE;
24 | }
25 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
26 | if (null == connectivityManager) {
27 | return NETWORK_NONE;
28 | }
29 |
30 | final NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
31 | if (null == activeNetInfo || !activeNetInfo.isAvailable()) {
32 | return NETWORK_NONE;
33 | } else if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
34 | return NETWORK_WIFI;
35 | } else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
36 | final NetworkInfo.State state = activeNetInfo.getState();
37 | final String subTypeName = activeNetInfo.getSubtypeName();
38 | if (null != state) {
39 | switch (activeNetInfo.getSubtype()) {
40 | case TelephonyManager.NETWORK_TYPE_GPRS:
41 | case TelephonyManager.NETWORK_TYPE_CDMA:
42 | case TelephonyManager.NETWORK_TYPE_EDGE:
43 | case TelephonyManager.NETWORK_TYPE_1xRTT:
44 | case TelephonyManager.NETWORK_TYPE_IDEN:
45 | return NETWORK_2G;
46 | case TelephonyManager.NETWORK_TYPE_EVDO_A:
47 | case TelephonyManager.NETWORK_TYPE_UMTS:
48 | case TelephonyManager.NETWORK_TYPE_EVDO_0:
49 | case TelephonyManager.NETWORK_TYPE_HSDPA:
50 | case TelephonyManager.NETWORK_TYPE_HSUPA:
51 | case TelephonyManager.NETWORK_TYPE_HSPA:
52 | case TelephonyManager.NETWORK_TYPE_EVDO_B:
53 | case TelephonyManager.NETWORK_TYPE_EHRPD:
54 | case TelephonyManager.NETWORK_TYPE_HSPAP:
55 | return NETWORK_3G;
56 | case TelephonyManager.NETWORK_TYPE_LTE:
57 | return NETWORK_4G;
58 | default:
59 | if (subTypeName.equalsIgnoreCase("TD-SCDMA")
60 | || subTypeName.equalsIgnoreCase("WCDMA")
61 | || subTypeName.equalsIgnoreCase("CDMA2000")) {
62 | return NETWORK_3G;
63 | } else {
64 | return NETWORK_UNKNOWN_MOBILE;
65 | }
66 | }
67 | }
68 | }
69 | return NETWORK_NONE;
70 | }
71 |
72 | /**
73 | * @param context
74 | * @return
75 | */
76 | public static boolean isNetworkAvailable(Context context) {
77 | if (context == null) {
78 | return false;
79 | }
80 | ConnectivityManager connectivityManager = (ConnectivityManager) context
81 | .getApplicationContext().getSystemService(
82 | Context.CONNECTIVITY_SERVICE);
83 | if (connectivityManager == null) {
84 | return false;
85 | }
86 |
87 | NetworkInfo networkinfo = connectivityManager.getActiveNetworkInfo();
88 |
89 | return networkinfo != null && networkinfo.isAvailable();
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/StringUtils.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | /**
4 | * Created by michaelzhong on 17/6/14.
5 | */
6 |
7 | public final class StringUtils {
8 |
9 | public static boolean equals(String str1, String str2) {
10 | if (null == str1) {
11 | if (null == str2) {
12 | return true;
13 | }
14 | return false;
15 | } else {
16 | return str1.equals(str2);
17 | }
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/trojan/src/main/java/me/ele/trojan/utils/TagUtil.java:
--------------------------------------------------------------------------------
1 | package me.ele.trojan.utils;
2 |
3 | import me.ele.trojan.config.LogConstants;
4 |
5 | /**
6 | * Created by michaelzhong on 2018/3/30.
7 | */
8 |
9 | public class TagUtil {
10 |
11 | public static int getVersionByTag(String tag) {
12 | if (tag != null) {
13 | switch (tag) {
14 | case LogConstants.BASIC_TAG:
15 | case LogConstants.KLOG_TAG:
16 | case LogConstants.HTTP_TAG:
17 | case LogConstants.VIEW_CLICK_TAG:
18 | case LogConstants.HTTP_REQUEST_TAG:
19 | case LogConstants.HTTP_RESPONSE_TAG:
20 | case LogConstants.ACTIVITY_LIFE_TAG:
21 | case LogConstants.FRAGMENT_LIFE_TAG:
22 | case LogConstants.DIALOG_TAG:
23 | case LogConstants.NETWORK_TAG:
24 | case LogConstants.BATTERY_TAG:
25 | case LogConstants.EXCEPTION_TAG:
26 | case LogConstants.MOTION_TAG:
27 | case LogConstants.KEY_TAG:
28 | case LogConstants.EDIT_TAG:
29 | return LogConstants.LOG_VERSION1;
30 | case LogConstants.MEMORY_TAG:
31 | return LogConstants.LOG_VERSION2;
32 | }
33 | }
34 | return LogConstants.LOG_VERSION1;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/trojan/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Trojan
3 |
4 |
--------------------------------------------------------------------------------