├── .github └── workflows │ └── docker-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── asset ├── 1.png ├── 2.png ├── Dockerfile ├── asset.go ├── clash-rules.yaml ├── client.json ├── jetbrains.svg ├── trojan-install.sh └── trojan-web.service ├── build.sh ├── cmd ├── add.go ├── clean.go ├── completion.go ├── del.go ├── export.go ├── import.go ├── info.go ├── log.go ├── port.go ├── restart.go ├── root.go ├── start.go ├── status.go ├── stop.go ├── tls.go ├── update.go ├── updateWeb.go ├── upgrade.go ├── version.go └── web.go ├── core ├── base.go ├── client.go ├── leveldb.go ├── mysql.go ├── server.go └── tools.go ├── go.mod ├── go.sum ├── install.sh ├── main.go ├── trojan ├── client.go ├── info.go ├── install.go ├── trojan.go ├── user.go └── web.go ├── util ├── bytefmt.go ├── command.go ├── linux.go ├── string.go └── websocket.go └── web ├── auth.go ├── controller ├── common.go ├── data.go ├── trojan.go └── user.go └── web.go /.github/workflows/docker-publish.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | # This workflow uses actions that are not certified by GitHub. 4 | # They are provided by a third-party and are governed by 5 | # separate terms of service, privacy policy, and support 6 | # documentation. 7 | 8 | on: 9 | workflow_dispatch: #github页面手动触发 10 | push: 11 | tags: [ 'v*' ] 12 | 13 | env: 14 | # github.repository as / 15 | IMAGE_NAME: jrohy/trojan 16 | 17 | 18 | jobs: 19 | buildx: 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Checkout repository 23 | uses: actions/checkout@v2 24 | 25 | - name: Set up QEMU 26 | uses: docker/setup-qemu-action@v1 27 | 28 | - name: Set up Docker Buildx 29 | id: buildx 30 | uses: docker/setup-buildx-action@v1 31 | 32 | - name: Get latest tag 33 | uses: oprypin/find-latest-tag@v1 34 | id: octokit # The step ID to refer to later. 35 | with: 36 | repository: ${{ github.repository }} # The repository to scan. 37 | 38 | # https://github.com/docker/login-action 39 | - name: Login 40 | uses: docker/login-action@v1 41 | with: 42 | username: ${{ secrets.DOCKERHUB_USERNAME }} 43 | password: ${{ secrets.DOCKERHUB_TOKEN }} 44 | 45 | # https://github.com/docker/build-push-action 46 | - name: Build & Push 47 | uses: docker/build-push-action@v2 48 | with: 49 | context: . 50 | file: ./asset/Dockerfile 51 | platforms: linux/amd64,linux/arm64/v8 52 | push: true 53 | tags: | 54 | ${{ env.IMAGE_NAME }}:${{ steps.octokit.outputs.tag }} 55 | ${{ env.IMAGE_NAME }}:latest 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # trojan 2 | ![](https://img.shields.io/github/v/release/Jrohy/trojan.svg) 3 | ![](https://img.shields.io/docker/pulls/jrohy/trojan.svg) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/Jrohy/trojan)](https://goreportcard.com/report/github.com/Jrohy/trojan) 5 | [![Downloads](https://img.shields.io/github/downloads/Jrohy/trojan/total.svg)](https://img.shields.io/github/downloads/Jrohy/trojan/total.svg) 6 | [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html) 7 | 8 | 9 | trojan多用户管理部署程序 10 | 11 | ## 功能 12 | - 在线web页面和命令行两种方式管理trojan多用户 13 | - 启动 / 停止 / 重启 trojan 服务端 14 | - 支持流量统计和流量限制 15 | - 命令行模式管理, 支持命令补全 16 | - 集成acme.sh证书申请 17 | - 生成客户端配置文件 18 | - 在线实时查看trojan日志 19 | - 在线trojan和trojan-go随时切换 20 | - 支持trojan://分享链接和二维码分享(仅限web页面) 21 | - 支持转化为clash订阅地址并导入到[clash_for_windows](https://github.com/Fndroid/clash_for_windows_pkg/releases)(仅限web页面) 22 | - 限制用户使用期限 23 | 24 | ## 安装方式 25 | *trojan使用请提前准备好服务器可用的域名* 26 | 27 | ### a. 一键脚本安装 28 | ``` 29 | #安装/更新 30 | source <(curl -sL https://git.io/trojan-install) 31 | 32 | #卸载 33 | source <(curl -sL https://git.io/trojan-install) --remove 34 | 35 | ``` 36 | 安装完后输入'trojan'可进入管理程序 37 | 浏览器访问 https://域名 可在线web页面管理trojan用户 38 | 前端页面源码地址: [trojan-web](https://github.com/Jrohy/trojan-web) 39 | 40 | ### b. docker运行 41 | 1. 安装mysql 42 | 43 | 因为mariadb内存使用比mysql至少减少一半, 所以推荐使用mariadb数据库 44 | ``` 45 | docker run --name trojan-mariadb --restart=always -p 3306:3306 -v /home/mariadb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=trojan -e MYSQL_ROOT_HOST=% -e MYSQL_DATABASE=trojan -d mariadb:10.2 46 | ``` 47 | 端口和root密码以及持久化目录都可以改成其他的 48 | 49 | 2. 安装trojan 50 | ``` 51 | docker run -it -d --name trojan --net=host --restart=always --privileged jrohy/trojan init 52 | ``` 53 | 运行完后进入容器 `docker exec -it trojan bash`, 然后输入'trojan'即可进行初始化安装 54 | 55 | 启动web服务: `systemctl start trojan-web` 56 | 57 | 设置自启动: `systemctl enable trojan-web` 58 | 59 | 更新管理程序: `source <(curl -sL https://git.io/trojan-install)` 60 | 61 | ## 运行截图 62 | ![avatar](asset/1.png) 63 | ![avatar](asset/2.png) 64 | 65 | ## 命令行 66 | ``` 67 | Usage: 68 | trojan [flags] 69 | trojan [command] 70 | 71 | Available Commands: 72 | add 添加用户 73 | clean 清空指定用户流量 74 | completion 自动命令补全(支持bash和zsh) 75 | del 删除用户 76 | help Help about any command 77 | info 用户信息列表 78 | log 查看trojan日志 79 | port 修改trojan端口 80 | restart 重启trojan 81 | start 启动trojan 82 | status 查看trojan状态 83 | stop 停止trojan 84 | tls 证书安装 85 | update 更新trojan 86 | updateWeb 更新trojan管理程序 87 | version 显示版本号 88 | import [path] 导入sql文件 89 | export [path] 导出sql文件 90 | web 以web方式启动 91 | 92 | Flags: 93 | -h, --help help for trojan 94 | ``` 95 | 96 | ## 注意 97 | 安装完trojan后强烈建议开启BBR等加速: [one_click_script](https://github.com/jinwyp/one_click_script) 98 | 99 | ## Thanks 100 | 感谢JetBrains提供的免费GoLand 101 | [![avatar](asset/jetbrains.svg)](https://jb.gg/OpenSource) 102 | -------------------------------------------------------------------------------- /asset/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jrohy/trojan/b7a7054a3a2cff35805c6f7afaafa502973e0873/asset/1.png -------------------------------------------------------------------------------- /asset/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jrohy/trojan/b7a7054a3a2cff35805c6f7afaafa502973e0873/asset/2.png -------------------------------------------------------------------------------- /asset/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=$TARGETPLATFORM centos:7 2 | 3 | LABEL maintainer="Jrohy " 4 | 5 | ARG TARGETARCH 6 | 7 | ARG VERSION_CHECK="https://api.github.com/repos/Jrohy/trojan/releases/latest" 8 | 9 | ARG DOWNLAOD_URL="https://github.com/Jrohy/trojan/releases/download/" 10 | 11 | ARG SERVICE_URL="https://raw.githubusercontent.com/Jrohy/trojan/master/asset/trojan-web.service" 12 | 13 | ARG SYSTEMCTL_URL="https://raw.githubusercontent.com/gdraheim/docker-systemctl-replacement/master/files/docker/systemctl.py" 14 | 15 | RUN yum install socat bash-completion crontabs iptables openssl unzip -y && \ 16 | LATEST_VERSION=`curl -H 'Cache-Control: no-cache' -s "$VERSION_CHECK" | grep 'tag_name' | cut -d\" -f4` && \ 17 | [[ $TARGETARCH =~ "arm64" ]] && ARCH="arm64" || ARCH="amd64" && \ 18 | curl -fL "$DOWNLAOD_URL/$LATEST_VERSION/trojan-linux-$ARCH" -o /usr/local/bin/trojan && \ 19 | curl -L $SERVICE_URL -o /etc/systemd/system/trojan-web.service && \ 20 | curl -L $SYSTEMCTL_URL -o /usr/bin/systemctl && \ 21 | chmod +x /usr/local/bin/trojan /usr/bin/systemctl && \ 22 | echo "source <(trojan completion bash)" >> ~/.bashrc && \ 23 | yum clean all 24 | -------------------------------------------------------------------------------- /asset/asset.go: -------------------------------------------------------------------------------- 1 | package asset 2 | 3 | import "embed" 4 | 5 | //go:embed trojan-install.sh client.json clash-rules.yaml 6 | var f embed.FS 7 | 8 | // GetAsset 获取资源[]byte 9 | func GetAsset(name string) []byte { 10 | data, _ := f.ReadFile(name) 11 | return data 12 | } 13 | -------------------------------------------------------------------------------- /asset/clash-rules.yaml: -------------------------------------------------------------------------------- 1 | # Source: https://github.com/Loyalsoldier/clash-rules 2 | rules: 3 | - RULE-SET,applications,DIRECT 4 | - DOMAIN,clash.razord.top,DIRECT 5 | - DOMAIN,yacd.haishan.me,DIRECT 6 | - RULE-SET,private,DIRECT 7 | - RULE-SET,reject,REJECT 8 | - RULE-SET,icloud,DIRECT 9 | - RULE-SET,apple,DIRECT 10 | - RULE-SET,google,DIRECT 11 | - RULE-SET,proxy,PROXY 12 | - RULE-SET,direct,DIRECT 13 | - RULE-SET,lancidr,DIRECT 14 | - RULE-SET,cncidr,DIRECT 15 | - RULE-SET,telegramcidr,PROXY 16 | - GEOIP,LAN,DIRECT 17 | - GEOIP,CN,DIRECT 18 | - MATCH,PROXY 19 | 20 | rule-providers: 21 | reject: 22 | type: http 23 | behavior: domain 24 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/reject.txt" 25 | path: ./ruleset/reject.yaml 26 | interval: 86400 27 | 28 | icloud: 29 | type: http 30 | behavior: domain 31 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/icloud.txt" 32 | path: ./ruleset/icloud.yaml 33 | interval: 86400 34 | 35 | apple: 36 | type: http 37 | behavior: domain 38 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/apple.txt" 39 | path: ./ruleset/apple.yaml 40 | interval: 86400 41 | 42 | google: 43 | type: http 44 | behavior: domain 45 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/google.txt" 46 | path: ./ruleset/google.yaml 47 | interval: 86400 48 | 49 | proxy: 50 | type: http 51 | behavior: domain 52 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/proxy.txt" 53 | path: ./ruleset/proxy.yaml 54 | interval: 86400 55 | 56 | direct: 57 | type: http 58 | behavior: domain 59 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/direct.txt" 60 | path: ./ruleset/direct.yaml 61 | interval: 86400 62 | 63 | private: 64 | type: http 65 | behavior: domain 66 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/private.txt" 67 | path: ./ruleset/private.yaml 68 | interval: 86400 69 | 70 | gfw: 71 | type: http 72 | behavior: domain 73 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/gfw.txt" 74 | path: ./ruleset/gfw.yaml 75 | interval: 86400 76 | 77 | greatfire: 78 | type: http 79 | behavior: domain 80 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/greatfire.txt" 81 | path: ./ruleset/greatfire.yaml 82 | interval: 86400 83 | 84 | tld-not-cn: 85 | type: http 86 | behavior: domain 87 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/tld-not-cn.txt" 88 | path: ./ruleset/tld-not-cn.yaml 89 | interval: 86400 90 | 91 | telegramcidr: 92 | type: http 93 | behavior: ipcidr 94 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/telegramcidr.txt" 95 | path: ./ruleset/telegramcidr.yaml 96 | interval: 86400 97 | 98 | cncidr: 99 | type: http 100 | behavior: ipcidr 101 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/cncidr.txt" 102 | path: ./ruleset/cncidr.yaml 103 | interval: 86400 104 | 105 | lancidr: 106 | type: http 107 | behavior: ipcidr 108 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/lancidr.txt" 109 | path: ./ruleset/lancidr.yaml 110 | interval: 86400 111 | 112 | applications: 113 | type: http 114 | behavior: classical 115 | url: "https://cdn.jsdelivr.net/gh/Loyalsoldier/clash-rules@release/applications.txt" 116 | path: ./ruleset/applications.yaml 117 | interval: 86400 -------------------------------------------------------------------------------- /asset/client.json: -------------------------------------------------------------------------------- 1 | { 2 | "run_type": "client", 3 | "local_addr": "127.0.0.1", 4 | "local_port": 1080, 5 | "remote_addr": "example.com", 6 | "remote_port": 443, 7 | "password": [ 8 | "password1" 9 | ], 10 | "log_level": 1, 11 | "ssl": { 12 | "verify": true, 13 | "verify_hostname": true, 14 | "cert": "", 15 | "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA", 16 | "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", 17 | "sni": "", 18 | "alpn": [ 19 | "h2", 20 | "http/1.1" 21 | ], 22 | "reuse_session": true, 23 | "session_ticket": false, 24 | "curves": "" 25 | }, 26 | "tcp": { 27 | "no_delay": true, 28 | "keep_alive": true, 29 | "reuse_port": false, 30 | "fast_open": false, 31 | "fast_open_qlen": 20 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /asset/jetbrains.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 31 | 32 | 33 | 34 | 35 | 36 | 39 | 40 | 41 | 42 | 43 | 45 | 47 | 48 | 51 | 54 | 56 | 57 | 59 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /asset/trojan-install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # source: https://github.com/trojan-gfw/trojan-quickstart 3 | set -eo pipefail 4 | 5 | # trojan: 0, trojan-go: 1 6 | TYPE=0 7 | 8 | INSTALL_VERSION="" 9 | 10 | while [[ $# > 0 ]];do 11 | KEY="$1" 12 | case $KEY in 13 | -v|--version) 14 | INSTALL_VERSION="$2" 15 | echo -e "prepare install $INSTALL_VERSION version..\n" 16 | shift 17 | ;; 18 | -g|--go) 19 | TYPE=1 20 | ;; 21 | *) 22 | # unknown option 23 | ;; 24 | esac 25 | shift # past argument or value 26 | done 27 | ############################# 28 | 29 | function prompt() { 30 | while true; do 31 | read -p "$1 [y/N] " yn 32 | case $yn in 33 | [Yy] ) return 0;; 34 | [Nn]|"" ) return 1;; 35 | esac 36 | done 37 | } 38 | 39 | if [[ $(id -u) != 0 ]]; then 40 | echo Please run this script as root. 41 | exit 1 42 | fi 43 | 44 | ARCH=$(uname -m 2> /dev/null) 45 | if [[ $ARCH != x86_64 && $ARCH != aarch64 ]];then 46 | echo "not support $ARCH machine". 47 | exit 1 48 | fi 49 | if [[ $TYPE == 0 && $ARCH != x86_64 ]];then 50 | echo "trojan not support $ARCH machine" 51 | exit 1 52 | fi 53 | 54 | if [[ $TYPE == 0 ]];then 55 | CHECKVERSION="https://api.github.com/repos/trojan-gfw/trojan/releases/latest" 56 | else 57 | CHECKVERSION="https://api.github.com/repos/p4gefau1t/trojan-go/releases" 58 | fi 59 | NAME=trojan 60 | if [[ -z $INSTALL_VERSION ]];then 61 | VERSION=$(curl -H 'Cache-Control: no-cache' -s "$CHECKVERSION" | grep 'tag_name' | cut -d\" -f4 | sed 's/v//g' | head -n 1) 62 | else 63 | if [[ -z `curl -H 'Cache-Control: no-cache' -s "$CHECKVERSION"|grep 'tag_name'|grep $INSTALL_VERSION` ]];then 64 | echo "no $INSTALL_VERSION version file!" 65 | exit 1 66 | fi 67 | VERSION=`echo "$INSTALL_VERSION"|sed 's/v//g'` 68 | fi 69 | if [[ $TYPE == 0 ]];then 70 | TARBALL="$NAME-$VERSION-linux-amd64.tar.xz" 71 | DOWNLOADURL="https://github.com/trojan-gfw/$NAME/releases/download/v$VERSION/$TARBALL" 72 | else 73 | [[ $ARCH == x86_64 ]] && TARBALL="trojan-go-linux-amd64.zip" || TARBALL="trojan-go-linux-armv8.zip" 74 | DOWNLOADURL="https://github.com/p4gefau1t/trojan-go/releases/download/v$VERSION/$TARBALL" 75 | fi 76 | 77 | TMPDIR="$(mktemp -d)" 78 | INSTALLPREFIX="/usr/bin/$NAME" 79 | SYSTEMDPREFIX=/etc/systemd/system 80 | 81 | BINARYPATH="$INSTALLPREFIX/$NAME" 82 | CONFIGPATH="/usr/local/etc/$NAME/config.json" 83 | SYSTEMDPATH="$SYSTEMDPREFIX/$NAME.service" 84 | 85 | echo Creating $NAME install directory 86 | mkdir -p $INSTALLPREFIX /usr/local/etc/$NAME 87 | 88 | echo Entering temp directory $TMPDIR... 89 | cd "$TMPDIR" 90 | 91 | echo Downloading $NAME $VERSION... 92 | curl -LO --progress-bar "$DOWNLOADURL" || wget -q --show-progress "$DOWNLOADURL" 93 | 94 | echo Unpacking $NAME $VERSION... 95 | if [[ $TYPE == 0 ]];then 96 | tar xf "$TARBALL" 97 | cd "$NAME" 98 | else 99 | if [[ -z `command -v unzip` ]];then 100 | if [[ `command -v dnf` ]];then 101 | dnf install unzip -y 102 | elif [[ `command -v yum` ]];then 103 | yum install unzip -y 104 | elif [[ `command -v apt-get` ]];then 105 | apt-get install unzip -y 106 | fi 107 | fi 108 | unzip "$TARBALL" 109 | mv trojan-go trojan 110 | fi 111 | 112 | echo Installing $NAME $VERSION to $BINARYPATH... 113 | install -Dm755 "$NAME" "$BINARYPATH" 114 | 115 | echo Installing $NAME server config to $CONFIGPATH... 116 | if ! [[ -f "$CONFIGPATH" ]] || prompt "The server config already exists in $CONFIGPATH, overwrite?"; then 117 | cat > "$CONFIGPATH" << EOF 118 | { 119 | "run_type": "server", 120 | "local_addr": "0.0.0.0", 121 | "local_port": 443, 122 | "remote_addr": "127.0.0.1", 123 | "remote_port": 80, 124 | "password": [ 125 | "password1", 126 | "password2" 127 | ], 128 | "log_level": 1, 129 | "ssl": { 130 | "cert": "/path/to/certificate.crt", 131 | "key": "/path/to/private.key", 132 | "key_password": "", 133 | "cipher": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384", 134 | "cipher_tls13": "TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384", 135 | "prefer_server_cipher": true, 136 | "alpn": [ 137 | "http/1.1" 138 | ], 139 | "alpn_port_override": { 140 | "h2": 81 141 | }, 142 | "reuse_session": true, 143 | "session_ticket": false, 144 | "session_timeout": 600, 145 | "plain_http_response": "", 146 | "curves": "", 147 | "dhparam": "" 148 | }, 149 | "tcp": { 150 | "prefer_ipv4": false, 151 | "no_delay": true, 152 | "keep_alive": true, 153 | "reuse_port": false, 154 | "fast_open": false, 155 | "fast_open_qlen": 20 156 | }, 157 | "mysql": { 158 | "enabled": false, 159 | "server_addr": "127.0.0.1", 160 | "server_port": 3306, 161 | "database": "trojan", 162 | "username": "trojan", 163 | "password": "", 164 | "key": "", 165 | "cert": "", 166 | "ca": "" 167 | } 168 | } 169 | EOF 170 | else 171 | echo Skipping installing $NAME server config... 172 | fi 173 | 174 | if [[ -d "$SYSTEMDPREFIX" ]]; then 175 | echo Installing $NAME systemd service to $SYSTEMDPATH... 176 | [[ $TYPE == 1 ]] && { NAME="trojan-go"; FLAG="-config"; } 177 | cat > "$SYSTEMDPATH" << EOF 178 | [Unit] 179 | Description=$NAME 180 | After=network.target network-online.target nss-lookup.target mysql.service mariadb.service mysqld.service 181 | 182 | [Service] 183 | Type=simple 184 | StandardError=journal 185 | ExecStart=$BINARYPATH $FLAG $CONFIGPATH 186 | ExecReload=/bin/kill -HUP \$MAINPID 187 | Restart=on-failure 188 | RestartSec=3s 189 | 190 | [Install] 191 | WantedBy=multi-user.target 192 | EOF 193 | echo Reloading systemd daemon... 194 | systemctl daemon-reload 195 | fi 196 | 197 | echo Deleting temp directory $TMPDIR... 198 | rm -rf "$TMPDIR" 199 | 200 | echo Done! -------------------------------------------------------------------------------- /asset/trojan-web.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=trojan-web 3 | Documentation=https://github.com/Jrohy/trojan 4 | After=network.target network-online.target nss-lookup.target mysql.service mariadb.service mysqld.service docker.service 5 | 6 | [Service] 7 | Type=simple 8 | StandardError=journal 9 | ExecStart=/usr/local/bin/trojan web 10 | ExecReload=/bin/kill -HUP $MAINPID 11 | Restart=on-failure 12 | RestartSec=3s 13 | 14 | [Install] 15 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | github_token="" 4 | 5 | project="Jrohy/trojan" 6 | 7 | #获取当前的这个脚本所在绝对路径 8 | shell_path=$(cd `dirname $0`; pwd) 9 | 10 | function uploadfile() { 11 | file=$1 12 | ctype=$(file -b --mime-type $file) 13 | 14 | curl -H "Authorization: token ${github_token}" -H "Content-Type: ${ctype}" --data-binary @$file "https://uploads.github.com/repos/$project/releases/${release_id}/assets?name=$(basename $file)" 15 | 16 | echo "" 17 | } 18 | 19 | function upload() { 20 | file=$1 21 | dgst=$1.dgst 22 | openssl dgst -md5 $file | sed 's/([^)]*)//g' >> $dgst 23 | openssl dgst -sha1 $file | sed 's/([^)]*)//g' >> $dgst 24 | openssl dgst -sha256 $file | sed 's/([^)]*)//g' >> $dgst 25 | openssl dgst -sha512 $file | sed 's/([^)]*)//g' >> $dgst 26 | uploadfile $file 27 | uploadfile $dgst 28 | } 29 | 30 | cd $shell_path 31 | 32 | version=`git describe --tags $(git rev-list --tags --max-count=1)` 33 | now=`TZ=Asia/Shanghai date "+%Y%m%d-%H%M"` 34 | go_version=`go version|awk '{print $3,$4}'` 35 | git_version=`git rev-parse HEAD` 36 | ldflags="-w -s -X 'trojan/trojan.MVersion=$version' -X 'trojan/trojan.BuildDate=$now' -X 'trojan/trojan.GoVersion=$go_version' -X 'trojan/trojan.GitVersion=$git_version'" 37 | 38 | GOOS=linux GOARCH=amd64 go build -ldflags "$ldflags" -o "result/trojan-linux-amd64" . 39 | GOOS=linux GOARCH=arm64 go build -ldflags "$ldflags" -o "result/trojan-linux-arm64" . 40 | 41 | if [[ $# == 0 ]];then 42 | cd result 43 | 44 | upload_item=($(ls -l|awk '{print $9}'|xargs -r)) 45 | 46 | curl -X POST -H "Authorization: token ${github_token}" -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/$project/releases -d '{"tag_name":"'$version'", "name":"'$version'"}' 47 | 48 | sleep 2 49 | 50 | release_id=`curl -H 'Cache-Control: no-cache' -s https://api.github.com/repos/$project/releases/latest|grep id|awk 'NR==1{print $2}'|sed 's/,//'` 51 | 52 | for item in ${upload_item[@]} 53 | do 54 | upload $item 55 | done 56 | 57 | echo "upload completed!" 58 | 59 | cd $shell_path 60 | 61 | rm -rf result 62 | fi 63 | -------------------------------------------------------------------------------- /cmd/add.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // addCmd represents the add command 9 | var addCmd = &cobra.Command{ 10 | Use: "add", 11 | Short: "添加用户", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | trojan.AddUser() 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(addCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/clean.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // cleanCmd represents the clean command 9 | var cleanCmd = &cobra.Command{ 10 | Use: "clean", 11 | Short: "清空指定用户流量", 12 | Long: `传入指定用户名来清空用户流量, 多个用户名空格隔开, 例如: 13 | trojan clean zhangsan lisi 14 | `, 15 | Args: cobra.MinimumNArgs(1), 16 | Run: func(cmd *cobra.Command, args []string) { 17 | trojan.CleanDataByName(args) 18 | }, 19 | } 20 | 21 | func init() { 22 | rootCmd.AddCommand(cleanCmd) 23 | } 24 | -------------------------------------------------------------------------------- /cmd/completion.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "os" 6 | ) 7 | 8 | // completionCmd represents the completion command 9 | var completionCmd = &cobra.Command{ 10 | Use: "completion", 11 | Short: "自动命令补全(支持bash和zsh)", 12 | Long: ` 13 | 支持bash和zsh的命令补全 14 | a. bash环境添加下面命令到 ~/.bashrc 15 | source <(trojan completion bash) 16 | 17 | b. zsh环境添加以下命令到~/.zshrc 18 | source <(trojan completion zsh) 19 | `, 20 | } 21 | 22 | func init() { 23 | rootCmd.AddCommand(completionCmd) 24 | completionCmd.AddCommand(&cobra.Command{Use: "bash", Short: "bash命令补全", Run: func(cmd *cobra.Command, args []string) { 25 | rootCmd.GenBashCompletion(os.Stdout) 26 | }}) 27 | completionCmd.AddCommand(&cobra.Command{Use: "zsh", Short: "zsh命令补全", Run: func(cmd *cobra.Command, args []string) { 28 | rootCmd.GenZshCompletion(os.Stdout) 29 | }}) 30 | } 31 | -------------------------------------------------------------------------------- /cmd/del.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // delCmd represents the del command 9 | var delCmd = &cobra.Command{ 10 | Use: "del", 11 | Short: "删除用户", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | trojan.DelUser() 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(delCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/export.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "trojan/core" 7 | "trojan/util" 8 | ) 9 | 10 | // exportCmd represents the export command 11 | var exportCmd = &cobra.Command{ 12 | Use: "export", 13 | Short: "导出数据库sql文件", 14 | Args: cobra.ExactArgs(1), 15 | Run: func(cmd *cobra.Command, args []string) { 16 | mysql := core.GetMysql() 17 | if err := mysql.DumpSql(args[0]); err != nil { 18 | fmt.Println(util.Red(err.Error())) 19 | } else { 20 | fmt.Println(util.Green("导出sql成功!")) 21 | } 22 | }, 23 | } 24 | 25 | func init() { 26 | rootCmd.AddCommand(exportCmd) 27 | } 28 | -------------------------------------------------------------------------------- /cmd/import.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "trojan/core" 7 | "trojan/util" 8 | ) 9 | 10 | // importCmd represents the import command 11 | var importCmd = &cobra.Command{ 12 | Use: "import", 13 | Short: "导入数据库sql文件", 14 | Args: cobra.ExactArgs(1), 15 | Run: func(cmd *cobra.Command, args []string) { 16 | mysql := core.GetMysql() 17 | if err := mysql.ExecSql(args[0]); err != nil { 18 | fmt.Println(util.Red(err.Error())) 19 | } else { 20 | fmt.Println(util.Green("导入sql成功!")) 21 | } 22 | }, 23 | } 24 | 25 | func init() { 26 | rootCmd.AddCommand(importCmd) 27 | } 28 | -------------------------------------------------------------------------------- /cmd/info.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "trojan/trojan" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | // infoCmd represents the info command 10 | var infoCmd = &cobra.Command{ 11 | Use: "info", 12 | Short: "用户信息列表", 13 | Run: func(cmd *cobra.Command, args []string) { 14 | trojan.UserList() 15 | }, 16 | } 17 | 18 | func init() { 19 | rootCmd.AddCommand(infoCmd) 20 | } 21 | -------------------------------------------------------------------------------- /cmd/log.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "trojan/util" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | var line int 10 | 11 | // logCmd represents the log command 12 | var logCmd = &cobra.Command{ 13 | Use: "log", 14 | Short: "查看trojan日志", 15 | Run: func(cmd *cobra.Command, args []string) { 16 | util.Log("trojan", line) 17 | }, 18 | } 19 | 20 | func init() { 21 | logCmd.Flags().IntVarP(&line, "line", "n", 300, "查看日志行数") 22 | rootCmd.AddCommand(logCmd) 23 | } 24 | -------------------------------------------------------------------------------- /cmd/port.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "trojan/trojan" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | // portCmd represents the info command 10 | var portCmd = &cobra.Command{ 11 | Use: "port", 12 | Short: "修改trojan端口", 13 | Run: func(cmd *cobra.Command, args []string) { 14 | trojan.ChangePort() 15 | }, 16 | } 17 | 18 | func init() { 19 | rootCmd.AddCommand(portCmd) 20 | } 21 | -------------------------------------------------------------------------------- /cmd/restart.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // restartCmd represents the restart command 9 | var restartCmd = &cobra.Command{ 10 | Use: "restart", 11 | Short: "重启trojan", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | trojan.Restart() 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(restartCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "os" 7 | "trojan/core" 8 | "trojan/trojan" 9 | "trojan/util" 10 | ) 11 | 12 | // rootCmd represents the base command when called without any subcommands 13 | var rootCmd = &cobra.Command{ 14 | Use: "trojan", 15 | Run: func(cmd *cobra.Command, args []string) { 16 | mainMenu() 17 | }, 18 | } 19 | 20 | // Execute adds all child commands to the root command and sets flags appropriately. 21 | // This is called by main.main(). It only needs to happen once to the rootCmd. 22 | func Execute() { 23 | if err := rootCmd.Execute(); err != nil { 24 | fmt.Println(err) 25 | os.Exit(1) 26 | } 27 | } 28 | 29 | func check() { 30 | if !util.IsExists("/usr/local/etc/trojan/config.json") { 31 | fmt.Println("本机未安装trojan, 正在自动安装...") 32 | trojan.InstallTrojan("") 33 | core.WritePassword(nil) 34 | trojan.InstallTls() 35 | trojan.InstallMysql() 36 | util.SystemctlRestart("trojan-web") 37 | } 38 | } 39 | 40 | func mainMenu() { 41 | check() 42 | exit: 43 | for { 44 | fmt.Println() 45 | fmt.Println(util.Cyan("欢迎使用trojan管理程序")) 46 | fmt.Println() 47 | menuList := []string{"trojan管理", "用户管理", "安装管理", "web管理", "查看配置", "生成json"} 48 | switch util.LoopInput("请选择: ", menuList, false) { 49 | case 1: 50 | trojan.ControlMenu() 51 | case 2: 52 | trojan.UserMenu() 53 | case 3: 54 | trojan.InstallMenu() 55 | case 4: 56 | trojan.WebMenu() 57 | case 5: 58 | trojan.UserList() 59 | case 6: 60 | trojan.GenClientJson() 61 | default: 62 | break exit 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /cmd/start.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // startCmd represents the start command 9 | var startCmd = &cobra.Command{ 10 | Use: "start", 11 | Short: "启动trojan", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | trojan.Start() 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(startCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/status.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "trojan/trojan" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | // statusCmd represents the status command 10 | var statusCmd = &cobra.Command{ 11 | Use: "status", 12 | Short: "查看trojan状态", 13 | Run: func(cmd *cobra.Command, args []string) { 14 | trojan.Status(true) 15 | }, 16 | } 17 | 18 | func init() { 19 | rootCmd.AddCommand(statusCmd) 20 | } 21 | -------------------------------------------------------------------------------- /cmd/stop.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // stopCmd represents the stop command 9 | var stopCmd = &cobra.Command{ 10 | Use: "stop", 11 | Short: "停止trojan", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | trojan.Stop() 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(stopCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/tls.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // tlsCmd represents the tls command 9 | var tlsCmd = &cobra.Command{ 10 | Use: "tls", 11 | Short: "证书安装", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | trojan.InstallTls() 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(tlsCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/update.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/trojan" 6 | ) 7 | 8 | // upgradeCmd represents the update command 9 | var updateCmd = &cobra.Command{ 10 | Use: "update", 11 | Short: "更新trojan", 12 | Long: "可添加版本号更新特定版本, 比如'trojan update v0.10.0', 不添加版本号则安装最新版", 13 | Args: cobra.MaximumNArgs(1), 14 | Run: func(cmd *cobra.Command, args []string) { 15 | version := "" 16 | if len(args) == 1 { 17 | version = args[0] 18 | } 19 | trojan.InstallTrojan(version) 20 | }, 21 | } 22 | 23 | func init() { 24 | rootCmd.AddCommand(updateCmd) 25 | } 26 | -------------------------------------------------------------------------------- /cmd/updateWeb.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | "trojan/util" 6 | ) 7 | 8 | // updateWebCmd represents the update command 9 | var updateWebCmd = &cobra.Command{ 10 | Use: "updateWeb", 11 | Short: "更新trojan管理程序", 12 | Run: func(cmd *cobra.Command, args []string) { 13 | util.RunWebShell("https://git.io/trojan-install") 14 | }, 15 | } 16 | 17 | func init() { 18 | rootCmd.AddCommand(updateWebCmd) 19 | } 20 | -------------------------------------------------------------------------------- /cmd/upgrade.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "trojan/core" 7 | "trojan/trojan" 8 | ) 9 | 10 | // upgradeCmd represents the update command 11 | var upgradeCmd = &cobra.Command{ 12 | Use: "upgrade", 13 | Short: "升级数据库和trojan配置文件", 14 | } 15 | 16 | func upgradeConfig() { 17 | domain, _ := core.GetValue("domain") 18 | if domain == "" { 19 | return 20 | } 21 | core.WriteDomain(domain) 22 | trojan.Restart() 23 | } 24 | 25 | func init() { 26 | rootCmd.AddCommand(upgradeCmd) 27 | upgradeCmd.AddCommand(&cobra.Command{Use: "db", Short: "升级数据库", Run: func(cmd *cobra.Command, args []string) { 28 | if err := core.GetMysql().UpgradeDB(); err != nil { 29 | fmt.Println(err) 30 | } 31 | }}) 32 | upgradeCmd.AddCommand(&cobra.Command{Use: "config", Short: "升级配置文件", Run: func(cmd *cobra.Command, args []string) { 33 | upgradeConfig() 34 | }}) 35 | } 36 | -------------------------------------------------------------------------------- /cmd/version.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "trojan/trojan" 6 | "trojan/util" 7 | 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | // versionCmd represents the Version command 12 | var versionCmd = &cobra.Command{ 13 | Use: "version", 14 | Short: "显示版本号", 15 | Run: func(cmd *cobra.Command, args []string) { 16 | upTime := trojan.UpTime() 17 | trojanVersion := trojan.Version() 18 | fmt.Println() 19 | fmt.Printf("Version: %s\n\n", util.Cyan(trojan.MVersion)) 20 | fmt.Printf("BuildDate: %s\n\n", util.Cyan(trojan.BuildDate)) 21 | fmt.Printf("GoVersion: %s\n\n", util.Cyan(trojan.GoVersion)) 22 | fmt.Printf("GitVersion: %s\n\n", util.Cyan(trojan.GitVersion)) 23 | fmt.Printf("TrojanVersion: %s\n\n", util.Cyan(trojanVersion)) 24 | fmt.Printf("TrojanUpTime: %s\n\n", util.Cyan(upTime)) 25 | }, 26 | } 27 | 28 | func init() { 29 | rootCmd.AddCommand(versionCmd) 30 | } 31 | -------------------------------------------------------------------------------- /cmd/web.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "trojan/util" 7 | "trojan/web" 8 | ) 9 | 10 | var ( 11 | host string 12 | port int 13 | ssl bool 14 | timeout int 15 | ) 16 | 17 | // webCmd represents the web command 18 | var webCmd = &cobra.Command{ 19 | Use: "web", 20 | Short: "以web方式启动", 21 | Run: func(cmd *cobra.Command, args []string) { 22 | web.Start(host, port, timeout, ssl) 23 | }, 24 | } 25 | 26 | func init() { 27 | webCmd.Flags().StringVarP(&host, "host", "", "0.0.0.0", "web服务监听地址") 28 | webCmd.Flags().IntVarP(&port, "port", "p", 80, "web服务启动端口") 29 | webCmd.Flags().BoolVarP(&ssl, "ssl", "", false, "web服务是否以https方式运行") 30 | webCmd.Flags().IntVarP(&timeout, "timeout", "t", 120, "登录超时时间(min)") 31 | webCmd.AddCommand(&cobra.Command{Use: "stop", Short: "停止trojan-web", Run: func(cmd *cobra.Command, args []string) { 32 | util.SystemctlStop("trojan-web") 33 | }}) 34 | webCmd.AddCommand(&cobra.Command{Use: "start", Short: "启动trojan-web", Run: func(cmd *cobra.Command, args []string) { 35 | util.SystemctlStart("trojan-web") 36 | }}) 37 | webCmd.AddCommand(&cobra.Command{Use: "restart", Short: "重启trojan-web", Run: func(cmd *cobra.Command, args []string) { 38 | util.SystemctlRestart("trojan-web") 39 | }}) 40 | webCmd.AddCommand(&cobra.Command{Use: "status", Short: "查看trojan-web状态", Run: func(cmd *cobra.Command, args []string) { 41 | fmt.Println(util.SystemctlStatus("trojan-web")) 42 | }}) 43 | webCmd.AddCommand(&cobra.Command{Use: "log", Short: "查看trojan-web日志", Run: func(cmd *cobra.Command, args []string) { 44 | util.Log("trojan-web", 300) 45 | }}) 46 | rootCmd.AddCommand(webCmd) 47 | } 48 | -------------------------------------------------------------------------------- /core/base.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | // Config 结构体 4 | type Config struct { 5 | RunType string `json:"run_type"` 6 | LocalAddr string `json:"local_addr"` 7 | LocalPort int `json:"local_port"` 8 | RemoteAddr string `json:"remote_addr"` 9 | RemotePort int `json:"remote_port"` 10 | Password []string `json:"password"` 11 | LogLevel int `json:"log_level"` 12 | } 13 | 14 | // SSL 结构体 15 | type SSL struct { 16 | Cert string `json:"cert"` 17 | Cipher string `json:"cipher"` 18 | CipherTls13 string `json:"cipher_tls13"` 19 | Alpn []string `json:"alpn"` 20 | ReuseSession bool `json:"reuse_session"` 21 | SessionTicket bool `json:"session_ticket"` 22 | Curves string `json:"curves"` 23 | Sni string `json:"sni"` 24 | } 25 | 26 | // TCP 结构体 27 | type TCP struct { 28 | NoDelay bool `json:"no_delay"` 29 | KeepAlive bool `json:"keep_alive"` 30 | ReusePort bool `json:"reuse_port"` 31 | FastOpen bool `json:"fast_open"` 32 | FastOpenQlen int `json:"fast_open_qlen"` 33 | } 34 | -------------------------------------------------------------------------------- /core/client.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | "trojan/asset" 8 | ) 9 | 10 | // ClientConfig 结构体 11 | type ClientConfig struct { 12 | Config 13 | SSl ClientSSL `json:"ssl"` 14 | Tcp ClientTCP `json:"tcp"` 15 | } 16 | 17 | // ClientSSL 结构体 18 | type ClientSSL struct { 19 | SSL 20 | Verify bool `json:"verify"` 21 | VerifyHostname bool `json:"verify_hostname"` 22 | } 23 | 24 | // ClientTCP 结构体 25 | type ClientTCP struct { 26 | TCP 27 | } 28 | 29 | // WriteClient 生成客户端json 30 | func WriteClient(port int, password, domain, writePath string) bool { 31 | data := asset.GetAsset("client.json") 32 | config := ClientConfig{} 33 | if err := json.Unmarshal(data, &config); err != nil { 34 | fmt.Println(err) 35 | return false 36 | } 37 | config.RemoteAddr = domain 38 | config.RemotePort = port 39 | config.Password = []string{password} 40 | outData, err := json.MarshalIndent(config, "", " ") 41 | if err != nil { 42 | fmt.Println(err) 43 | return false 44 | } 45 | if err = os.WriteFile(writePath, outData, 0644); err != nil { 46 | fmt.Println(err) 47 | return false 48 | } 49 | return true 50 | } 51 | -------------------------------------------------------------------------------- /core/leveldb.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "github.com/syndtr/goleveldb/leveldb" 5 | ) 6 | 7 | var dbPath = "/var/lib/trojan-manager" 8 | 9 | // GetValue 获取leveldb值 10 | func GetValue(key string) (string, error) { 11 | db, err := leveldb.OpenFile(dbPath, nil) 12 | if err != nil { 13 | return "", err 14 | } 15 | defer db.Close() 16 | result, err := db.Get([]byte(key), nil) 17 | if err != nil { 18 | return "", err 19 | } 20 | return string(result), nil 21 | } 22 | 23 | // SetValue 设置leveldb值 24 | func SetValue(key string, value string) error { 25 | db, err := leveldb.OpenFile(dbPath, nil) 26 | if err != nil { 27 | return err 28 | } 29 | defer db.Close() 30 | return db.Put([]byte(key), []byte(value), nil) 31 | } 32 | 33 | // DelValue 删除值 34 | func DelValue(key string) error { 35 | db, err := leveldb.OpenFile(dbPath, nil) 36 | if err != nil { 37 | return err 38 | } 39 | defer db.Close() 40 | return db.Delete([]byte(key), nil) 41 | } 42 | -------------------------------------------------------------------------------- /core/mysql.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "crypto/sha256" 5 | "database/sql" 6 | "errors" 7 | "fmt" 8 | mysqlDriver "github.com/go-sql-driver/mysql" 9 | "io" 10 | "log" 11 | "time" 12 | 13 | "strconv" 14 | "strings" 15 | 16 | // mysql sql驱动 17 | _ "github.com/go-sql-driver/mysql" 18 | ) 19 | 20 | // Mysql 结构体 21 | type Mysql struct { 22 | Enabled bool `json:"enabled"` 23 | ServerAddr string `json:"server_addr"` 24 | ServerPort int `json:"server_port"` 25 | Database string `json:"database"` 26 | Username string `json:"username"` 27 | Password string `json:"password"` 28 | Cafile string `json:"cafile"` 29 | } 30 | 31 | // User 用户表记录结构体 32 | type User struct { 33 | ID uint 34 | Username string 35 | Password string 36 | EncryptPass string 37 | Quota int64 38 | Download uint64 39 | Upload uint64 40 | UseDays uint 41 | ExpiryDate string 42 | } 43 | 44 | // PageQuery 分页查询的结构体 45 | type PageQuery struct { 46 | PageNum int 47 | CurPage int 48 | Total int 49 | PageSize int 50 | DataList []*User 51 | } 52 | 53 | // CreateTableSql 创表sql 54 | var CreateTableSql = ` 55 | CREATE TABLE IF NOT EXISTS users ( 56 | id INT UNSIGNED NOT NULL AUTO_INCREMENT, 57 | username VARCHAR(64) NOT NULL, 58 | password CHAR(56) NOT NULL, 59 | passwordShow VARCHAR(255) NOT NULL, 60 | quota BIGINT NOT NULL DEFAULT 0, 61 | download BIGINT UNSIGNED NOT NULL DEFAULT 0, 62 | upload BIGINT UNSIGNED NOT NULL DEFAULT 0, 63 | useDays int(10) DEFAULT 0, 64 | expiryDate char(10) DEFAULT '', 65 | PRIMARY KEY (id), 66 | INDEX (password) 67 | ) DEFAULT CHARSET=utf8mb4; 68 | ` 69 | 70 | // GetDB 获取mysql数据库连接 71 | func (mysql *Mysql) GetDB() *sql.DB { 72 | // 屏蔽mysql驱动包的日志输出 73 | mysqlDriver.SetLogger(log.New(io.Discard, "", 0)) 74 | conn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mysql.Username, mysql.Password, mysql.ServerAddr, mysql.ServerPort, mysql.Database) 75 | db, err := sql.Open("mysql", conn) 76 | if err != nil { 77 | fmt.Println(err.Error()) 78 | return nil 79 | } 80 | return db 81 | } 82 | 83 | // CreateTable 不存在trojan user表则自动创建 84 | func (mysql *Mysql) CreateTable() { 85 | db := mysql.GetDB() 86 | defer db.Close() 87 | if _, err := db.Exec(CreateTableSql); err != nil { 88 | fmt.Println(err) 89 | } 90 | } 91 | 92 | func queryUserList(db *sql.DB, sql string) ([]*User, error) { 93 | var ( 94 | username string 95 | encryptPass string 96 | passShow string 97 | download uint64 98 | upload uint64 99 | quota int64 100 | id uint 101 | useDays uint 102 | expiryDate string 103 | ) 104 | var userList []*User 105 | rows, err := db.Query(sql) 106 | if err != nil { 107 | return nil, err 108 | } 109 | defer rows.Close() 110 | for rows.Next() { 111 | if err := rows.Scan(&id, &username, &encryptPass, &passShow, "a, &download, &upload, &useDays, &expiryDate); err != nil { 112 | return nil, err 113 | } 114 | userList = append(userList, &User{ 115 | ID: id, 116 | Username: username, 117 | Password: passShow, 118 | EncryptPass: encryptPass, 119 | Download: download, 120 | Upload: upload, 121 | Quota: quota, 122 | UseDays: useDays, 123 | ExpiryDate: expiryDate, 124 | }) 125 | } 126 | return userList, nil 127 | } 128 | 129 | func queryUser(db *sql.DB, sql string) (*User, error) { 130 | var ( 131 | username string 132 | encryptPass string 133 | passShow string 134 | download uint64 135 | upload uint64 136 | quota int64 137 | id uint 138 | useDays uint 139 | expiryDate string 140 | ) 141 | row := db.QueryRow(sql) 142 | if err := row.Scan(&id, &username, &encryptPass, &passShow, "a, &download, &upload, &useDays, &expiryDate); err != nil { 143 | return nil, err 144 | } 145 | return &User{ID: id, Username: username, Password: passShow, EncryptPass: encryptPass, Download: download, Upload: upload, Quota: quota, UseDays: useDays, ExpiryDate: expiryDate}, nil 146 | } 147 | 148 | // CreateUser 创建Trojan用户 149 | func (mysql *Mysql) CreateUser(username string, base64Pass string, originPass string) error { 150 | db := mysql.GetDB() 151 | if db == nil { 152 | return errors.New("can't connect mysql") 153 | } 154 | defer db.Close() 155 | encryPass := sha256.Sum224([]byte(originPass)) 156 | if _, err := db.Exec(fmt.Sprintf("INSERT INTO users(username, password, passwordShow, quota) VALUES ('%s', '%x', '%s', -1);", username, encryPass, base64Pass)); err != nil { 157 | fmt.Println(err) 158 | return err 159 | } 160 | return nil 161 | } 162 | 163 | // UpdateUser 更新Trojan用户名和密码 164 | func (mysql *Mysql) UpdateUser(id uint, username string, base64Pass string, originPass string) error { 165 | db := mysql.GetDB() 166 | if db == nil { 167 | return errors.New("can't connect mysql") 168 | } 169 | defer db.Close() 170 | encryPass := sha256.Sum224([]byte(originPass)) 171 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET username='%s', password='%x', passwordShow='%s' WHERE id=%d;", username, encryPass, base64Pass, id)); err != nil { 172 | fmt.Println(err) 173 | return err 174 | } 175 | return nil 176 | } 177 | 178 | // DeleteUser 删除用户 179 | func (mysql *Mysql) DeleteUser(id uint) error { 180 | db := mysql.GetDB() 181 | if db == nil { 182 | return errors.New("can't connect mysql") 183 | } 184 | defer db.Close() 185 | if userList, err := mysql.GetData(strconv.Itoa(int(id))); err != nil { 186 | return err 187 | } else if userList != nil && len(userList) == 0 { 188 | return fmt.Errorf("不存在id为%d的用户", id) 189 | } 190 | if _, err := db.Exec(fmt.Sprintf("DELETE FROM users WHERE id=%d;", id)); err != nil { 191 | fmt.Println(err) 192 | return err 193 | } 194 | return nil 195 | } 196 | 197 | // MonthlyResetData 设置了过期时间的用户,每月定时清空使用流量 198 | func (mysql *Mysql) MonthlyResetData() error { 199 | db := mysql.GetDB() 200 | if db == nil { 201 | return errors.New("can't connect mysql") 202 | } 203 | defer db.Close() 204 | userList, err := queryUserList(db, "SELECT * FROM users WHERE useDays != 0 AND quota != 0") 205 | if err != nil { 206 | return err 207 | } 208 | for _, user := range userList { 209 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET download=0, upload=0 WHERE id=%d;", user.ID)); err != nil { 210 | return err 211 | } 212 | } 213 | return nil 214 | } 215 | 216 | // DailyCheckExpire 检查是否有过期,过期了设置流量上限为0 217 | func (mysql *Mysql) DailyCheckExpire() (bool, error) { 218 | needRestart := false 219 | now := time.Now() 220 | utc, err := time.LoadLocation("Asia/Shanghai") 221 | if err != nil { 222 | return false, err 223 | } 224 | addDay, _ := time.ParseDuration("-24h") 225 | yesterdayStr := now.Add(addDay).In(utc).Format("2006-01-02") 226 | yesterday, _ := time.Parse("2006-01-02", yesterdayStr) 227 | db := mysql.GetDB() 228 | if db == nil { 229 | return false, errors.New("can't connect mysql") 230 | } 231 | defer db.Close() 232 | userList, err := queryUserList(db, "SELECT * FROM users WHERE quota != 0") 233 | if err != nil { 234 | return false, err 235 | } 236 | for _, user := range userList { 237 | if expireDate, err := time.Parse("2006-01-02", user.ExpiryDate); err == nil { 238 | if yesterday.Sub(expireDate).Seconds() >= 0 { 239 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET quota=0 WHERE id=%d;", user.ID)); err != nil { 240 | return false, err 241 | } 242 | if !needRestart { 243 | needRestart = true 244 | } 245 | } 246 | } 247 | } 248 | return needRestart, nil 249 | } 250 | 251 | // CancelExpire 取消过期时间 252 | func (mysql *Mysql) CancelExpire(id uint) error { 253 | db := mysql.GetDB() 254 | if db == nil { 255 | return errors.New("can't connect mysql") 256 | } 257 | defer db.Close() 258 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET useDays=0, expiryDate='' WHERE id=%d;", id)); err != nil { 259 | fmt.Println(err) 260 | return err 261 | } 262 | return nil 263 | } 264 | 265 | // SetExpire 设置过期时间 266 | func (mysql *Mysql) SetExpire(id uint, useDays uint) error { 267 | now := time.Now() 268 | utc, err := time.LoadLocation("Asia/Shanghai") 269 | if err != nil { 270 | fmt.Println(err) 271 | return err 272 | } 273 | addDay, _ := time.ParseDuration(strconv.Itoa(int(24*useDays)) + "h") 274 | expiryDate := now.Add(addDay).In(utc).Format("2006-01-02") 275 | 276 | db := mysql.GetDB() 277 | if db == nil { 278 | return errors.New("can't connect mysql") 279 | } 280 | defer db.Close() 281 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET useDays=%d, expiryDate='%s' WHERE id=%d;", useDays, expiryDate, id)); err != nil { 282 | fmt.Println(err) 283 | return err 284 | } 285 | return nil 286 | } 287 | 288 | // SetQuota 限制流量 289 | func (mysql *Mysql) SetQuota(id uint, quota int) error { 290 | db := mysql.GetDB() 291 | if db == nil { 292 | return errors.New("can't connect mysql") 293 | } 294 | defer db.Close() 295 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET quota=%d WHERE id=%d;", quota, id)); err != nil { 296 | fmt.Println(err) 297 | return err 298 | } 299 | return nil 300 | } 301 | 302 | // CleanData 清空流量统计 303 | func (mysql *Mysql) CleanData(id uint) error { 304 | db := mysql.GetDB() 305 | if db == nil { 306 | return errors.New("can't connect mysql") 307 | } 308 | defer db.Close() 309 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET download=0, upload=0 WHERE id=%d;", id)); err != nil { 310 | fmt.Println(err) 311 | return err 312 | } 313 | return nil 314 | } 315 | 316 | // CleanDataByName 清空指定用户名流量统计数据 317 | func (mysql *Mysql) CleanDataByName(usernames []string) error { 318 | db := mysql.GetDB() 319 | if db == nil { 320 | return errors.New("can't connect mysql") 321 | } 322 | defer db.Close() 323 | runSql := "UPDATE users SET download=0, upload=0 WHERE BINARY username in (" 324 | for i, name := range usernames { 325 | runSql = runSql + "'" + name + "'" 326 | if i == len(usernames)-1 { 327 | runSql = runSql + ")" 328 | } else { 329 | runSql = runSql + "," 330 | } 331 | } 332 | if _, err := db.Exec(runSql); err != nil { 333 | fmt.Println(err) 334 | return err 335 | } 336 | return nil 337 | } 338 | 339 | // GetUserByName 通过用户名来获取用户 340 | func (mysql *Mysql) GetUserByName(name string) *User { 341 | db := mysql.GetDB() 342 | if db == nil { 343 | return nil 344 | } 345 | defer db.Close() 346 | user, err := queryUser(db, fmt.Sprintf("SELECT * FROM users WHERE BINARY username='%s'", name)) 347 | if err != nil { 348 | return nil 349 | } 350 | return user 351 | } 352 | 353 | // GetUserByPass 通过密码来获取用户 354 | func (mysql *Mysql) GetUserByPass(pass string) *User { 355 | db := mysql.GetDB() 356 | if db == nil { 357 | return nil 358 | } 359 | defer db.Close() 360 | user, err := queryUser(db, fmt.Sprintf("SELECT * FROM users WHERE BINARY passwordShow='%s'", pass)) 361 | if err != nil { 362 | return nil 363 | } 364 | return user 365 | } 366 | 367 | // PageList 通过分页获取用户记录 368 | func (mysql *Mysql) PageList(curPage int, pageSize int) (*PageQuery, error) { 369 | var ( 370 | total int 371 | ) 372 | 373 | db := mysql.GetDB() 374 | if db == nil { 375 | return nil, errors.New("连接mysql失败") 376 | } 377 | defer db.Close() 378 | offset := (curPage - 1) * pageSize 379 | querySQL := fmt.Sprintf("SELECT * FROM users LIMIT %d, %d", offset, pageSize) 380 | userList, err := queryUserList(db, querySQL) 381 | if err != nil { 382 | fmt.Println(err) 383 | return nil, err 384 | } 385 | db.QueryRow("SELECT COUNT(id) FROM users").Scan(&total) 386 | return &PageQuery{ 387 | CurPage: curPage, 388 | PageSize: pageSize, 389 | Total: total, 390 | DataList: userList, 391 | PageNum: (total + pageSize - 1) / pageSize, 392 | }, nil 393 | } 394 | 395 | // GetData 获取用户记录 396 | func (mysql *Mysql) GetData(ids ...string) ([]*User, error) { 397 | querySQL := "SELECT * FROM users" 398 | db := mysql.GetDB() 399 | if db == nil { 400 | return nil, errors.New("连接mysql失败") 401 | } 402 | defer db.Close() 403 | if len(ids) > 0 { 404 | querySQL = querySQL + " WHERE id in (" + strings.Join(ids, ",") + ")" 405 | } 406 | userList, err := queryUserList(db, querySQL) 407 | if err != nil { 408 | fmt.Println(err) 409 | return nil, err 410 | } 411 | return userList, nil 412 | } 413 | -------------------------------------------------------------------------------- /core/server.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/tidwall/pretty" 7 | "github.com/tidwall/sjson" 8 | "os" 9 | ) 10 | 11 | var configPath = "/usr/local/etc/trojan/config.json" 12 | 13 | // ServerConfig 结构体 14 | type ServerConfig struct { 15 | Config 16 | SSl ServerSSL `json:"ssl"` 17 | Tcp ServerTCP `json:"tcp"` 18 | Mysql Mysql `json:"mysql"` 19 | } 20 | 21 | // ServerSSL 结构体 22 | type ServerSSL struct { 23 | SSL 24 | Key string `json:"key"` 25 | KeyPassword string `json:"key_password"` 26 | PreferServerCipher bool `json:"prefer_server_cipher"` 27 | SessionTimeout int `json:"session_timeout"` 28 | PlainHttpResponse string `json:"plain_http_response"` 29 | Dhparam string `json:"dhparam"` 30 | } 31 | 32 | // ServerTCP 结构体 33 | type ServerTCP struct { 34 | TCP 35 | PreferIPv4 bool `json:"prefer_ipv4"` 36 | } 37 | 38 | // Load 加载服务端配置文件 39 | func Load(path string) []byte { 40 | if path == "" { 41 | path = configPath 42 | } 43 | data, err := os.ReadFile(path) 44 | if err != nil { 45 | fmt.Println(err) 46 | return nil 47 | } 48 | return data 49 | } 50 | 51 | // Save 保存服务端配置文件 52 | func Save(data []byte, path string) bool { 53 | if path == "" { 54 | path = configPath 55 | } 56 | if err := os.WriteFile(path, pretty.Pretty(data), 0644); err != nil { 57 | fmt.Println(err) 58 | return false 59 | } 60 | return true 61 | } 62 | 63 | // GetConfig 获取config配置 64 | func GetConfig() *ServerConfig { 65 | data := Load("") 66 | config := ServerConfig{} 67 | if err := json.Unmarshal(data, &config); err != nil { 68 | fmt.Println(err) 69 | return nil 70 | } 71 | return &config 72 | } 73 | 74 | // GetMysql 获取mysql连接 75 | func GetMysql() *Mysql { 76 | return &GetConfig().Mysql 77 | } 78 | 79 | // WriteMysql 写mysql配置 80 | func WriteMysql(mysql *Mysql) bool { 81 | mysql.Enabled = true 82 | data := Load("") 83 | result, _ := sjson.SetBytes(data, "mysql", mysql) 84 | return Save(result, "") 85 | } 86 | 87 | // WriteTls 写tls配置 88 | func WriteTls(cert, key, domain string) bool { 89 | data := Load("") 90 | data, _ = sjson.SetBytes(data, "ssl.cert", cert) 91 | data, _ = sjson.SetBytes(data, "ssl.key", key) 92 | data, _ = sjson.SetBytes(data, "ssl.sni", domain) 93 | return Save(data, "") 94 | } 95 | 96 | // WriteDomain 写域名 97 | func WriteDomain(domain string) bool { 98 | data := Load("") 99 | data, _ = sjson.SetBytes(data, "ssl.sni", domain) 100 | return Save(data, "") 101 | } 102 | 103 | // WritePassword 写密码 104 | func WritePassword(pass []string) bool { 105 | data := Load("") 106 | data, _ = sjson.SetBytes(data, "password", pass) 107 | return Save(data, "") 108 | } 109 | 110 | // WritePort 写trojan端口 111 | func WritePort(port int) bool { 112 | data := Load("") 113 | data, _ = sjson.SetBytes(data, "local_port", port) 114 | return Save(data, "") 115 | } 116 | 117 | // WriteLogLevel 写日志等级 118 | func WriteLogLevel(level int) bool { 119 | data := Load("") 120 | data, _ = sjson.SetBytes(data, "log_level", level) 121 | return Save(data, "") 122 | } 123 | -------------------------------------------------------------------------------- /core/tools.go: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | import ( 4 | "bufio" 5 | "database/sql" 6 | "encoding/base64" 7 | "errors" 8 | "fmt" 9 | "os" 10 | "strings" 11 | "trojan/util" 12 | ) 13 | 14 | // UpgradeDB 升级数据库表结构以及迁移数据 15 | func (mysql *Mysql) UpgradeDB() error { 16 | db := mysql.GetDB() 17 | if db == nil { 18 | return errors.New("can't connect mysql") 19 | } 20 | var field string 21 | err := db.QueryRow("SHOW COLUMNS FROM users LIKE 'passwordShow';").Scan(&field) 22 | if err == sql.ErrNoRows { 23 | fmt.Println(util.Yellow("正在进行数据库升级, 请稍等..")) 24 | if _, err := db.Exec("ALTER TABLE users ADD COLUMN passwordShow VARCHAR(255) NOT NULL AFTER password;"); err != nil { 25 | fmt.Println(err) 26 | return err 27 | } 28 | userList, err := mysql.GetData() 29 | if err != nil { 30 | fmt.Println(err) 31 | return err 32 | } 33 | for _, user := range userList { 34 | pass, _ := GetValue(fmt.Sprintf("%s_pass", user.Username)) 35 | if pass != "" { 36 | base64Pass := base64.StdEncoding.EncodeToString([]byte(pass)) 37 | if _, err := db.Exec(fmt.Sprintf("UPDATE users SET passwordShow='%s' WHERE id=%d;", base64Pass, user.ID)); err != nil { 38 | fmt.Println(err) 39 | return err 40 | } 41 | DelValue(fmt.Sprintf("%s_pass", user.Username)) 42 | } 43 | } 44 | } 45 | err = db.QueryRow("SHOW COLUMNS FROM users LIKE 'useDays';").Scan(&field) 46 | if err == sql.ErrNoRows { 47 | fmt.Println(util.Yellow("正在进行数据库升级, 请稍等..")) 48 | if _, err := db.Exec(` 49 | ALTER TABLE users 50 | ADD COLUMN useDays int(10) DEFAULT 0, 51 | ADD COLUMN expiryDate char(10) DEFAULT ''; 52 | `); err != nil { 53 | fmt.Println(err) 54 | return err 55 | } 56 | } 57 | var tableName string 58 | err = db.QueryRow(fmt.Sprintf( 59 | "SELECT * FROM information_schema.TABLES WHERE TABLE_NAME = 'users' AND TABLE_SCHEMA = '%s' ", 60 | mysql.Database) + " AND TABLE_COLLATION LIKE 'utf8%';").Scan(&tableName) 61 | if err == sql.ErrNoRows { 62 | tempFile := "temp.sql" 63 | mysql.DumpSql(tempFile) 64 | mysql.ExecSql(tempFile) 65 | os.Remove(tempFile) 66 | } 67 | return nil 68 | } 69 | 70 | // DumpSql 导出sql 71 | func (mysql *Mysql) DumpSql(filePath string) error { 72 | file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) 73 | if err != nil { 74 | return err 75 | } 76 | defer file.Close() 77 | writer := bufio.NewWriter(file) 78 | writer.WriteString("DROP TABLE IF EXISTS users;") 79 | writer.WriteString(CreateTableSql) 80 | db := mysql.GetDB() 81 | userList, err := queryUserList(db, "SELECT * FROM users;") 82 | if err != nil { 83 | return err 84 | } 85 | for _, user := range userList { 86 | writer.WriteString(fmt.Sprintf(` 87 | INSERT INTO users(username, password, passwordShow, quota, download, upload, useDays, expiryDate) VALUES ('%s','%s','%s', %d, %d, %d, %d, '%s');`, 88 | user.Username, user.EncryptPass, user.Password, user.Quota, user.Download, user.Upload, user.UseDays, user.ExpiryDate)) 89 | } 90 | writer.WriteString("\n") 91 | writer.Flush() 92 | return nil 93 | } 94 | 95 | // ExecSql 执行sql 96 | func (mysql *Mysql) ExecSql(filePath string) error { 97 | db := mysql.GetDB() 98 | fileByte, err := os.ReadFile(filePath) 99 | if err != nil { 100 | return err 101 | } 102 | sqlStr := string(fileByte) 103 | sqls := strings.Split(strings.Replace(sqlStr, "\r\n", "\n", -1), ";\n") 104 | for _, s := range sqls { 105 | s = strings.TrimSpace(s) 106 | if s != "" { 107 | if _, err = db.Exec(s); err != nil { 108 | return err 109 | } 110 | } 111 | } 112 | return nil 113 | } 114 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module trojan 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/appleboy/gin-jwt/v2 v2.9.1 7 | github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 8 | github.com/gin-contrib/gzip v0.0.6 9 | github.com/gin-gonic/gin v1.9.1 10 | github.com/go-ole/go-ole v1.3.0 // indirect 11 | github.com/go-sql-driver/mysql v1.7.1 12 | github.com/gorilla/websocket v1.5.0 13 | github.com/robfig/cron/v3 v3.0.1 14 | github.com/shirou/gopsutil v3.21.11+incompatible 15 | github.com/spf13/cobra v1.7.0 16 | github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 17 | github.com/tidwall/gjson v1.17.0 18 | github.com/tidwall/pretty v1.2.1 19 | github.com/tidwall/sjson v1.2.5 20 | github.com/tklauser/go-sysconf v0.3.12 // indirect 21 | ) 22 | 23 | require ( 24 | github.com/bytedance/sonic v1.10.1 // indirect 25 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect 26 | github.com/chenzhuoyu/iasm v0.9.0 // indirect 27 | github.com/gabriel-vasile/mimetype v1.4.2 // indirect 28 | github.com/gin-contrib/sse v0.1.0 // indirect 29 | github.com/go-playground/locales v0.14.1 // indirect 30 | github.com/go-playground/universal-translator v0.18.1 // indirect 31 | github.com/go-playground/validator/v10 v10.15.4 // indirect 32 | github.com/goccy/go-json v0.10.2 // indirect 33 | github.com/golang-jwt/jwt/v4 v4.5.0 // indirect 34 | github.com/golang/snappy v0.0.4 // indirect 35 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 36 | github.com/json-iterator/go v1.1.12 // indirect 37 | github.com/klauspost/cpuid/v2 v2.2.5 // indirect 38 | github.com/leodido/go-urn v1.2.4 // indirect 39 | github.com/mattn/go-isatty v0.0.19 // indirect 40 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 41 | github.com/modern-go/reflect2 v1.0.2 // indirect 42 | github.com/pelletier/go-toml/v2 v2.1.0 // indirect 43 | github.com/spf13/pflag v1.0.5 // indirect 44 | github.com/tidwall/match v1.1.1 // indirect 45 | github.com/tklauser/numcpus v0.6.1 // indirect 46 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 47 | github.com/ugorji/go/codec v1.2.11 // indirect 48 | github.com/yusufpapurcu/wmi v1.2.3 // indirect 49 | golang.org/x/arch v0.5.0 // indirect 50 | golang.org/x/crypto v0.13.0 // indirect 51 | golang.org/x/net v0.15.0 // indirect 52 | golang.org/x/sys v0.12.0 // indirect 53 | golang.org/x/text v0.13.0 // indirect 54 | google.golang.org/protobuf v1.31.0 // indirect 55 | gopkg.in/yaml.v3 v3.0.1 // indirect 56 | ) 57 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/appleboy/gin-jwt/v2 v2.9.1 h1:l29et8iLW6omcHltsOP6LLk4s3v4g2FbFs0koxGWVZs= 2 | github.com/appleboy/gin-jwt/v2 v2.9.1/go.mod h1:jwcPZJ92uoC9nOUTOKWoN/f6JZOgMSKlFSHw5/FrRUk= 3 | github.com/appleboy/gofight/v2 v2.1.2 h1:VOy3jow4vIK8BRQJoC/I9muxyYlJ2yb9ht2hZoS3rf4= 4 | github.com/appleboy/gofight/v2 v2.1.2/go.mod h1:frW+U1QZEdDgixycTj4CygQ48yLTUhplt43+Wczp3rw= 5 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= 6 | github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= 7 | github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc= 8 | github.com/bytedance/sonic v1.10.1/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= 9 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= 10 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= 11 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= 12 | github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= 13 | github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo= 14 | github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= 15 | github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 16 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 17 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 18 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 19 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 20 | github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 h1:XBBHcIb256gUJtLmY22n99HaZTz+r2Z51xUPi01m3wg= 21 | github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203/go.mod h1:E1jcSv8FaEny+OP/5k9UxZVw9YFWGj7eI4KR/iOBqCg= 22 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 23 | github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= 24 | github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= 25 | github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= 26 | github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= 27 | github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= 28 | github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= 29 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 30 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 31 | github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk= 32 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= 33 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= 34 | github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= 35 | github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= 36 | github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= 37 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 38 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 39 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 40 | github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= 41 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= 42 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= 43 | github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= 44 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= 45 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= 46 | github.com/go-playground/validator/v10 v10.10.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos= 47 | github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU= 48 | github.com/go-playground/validator/v10 v10.15.4 h1:zMXza4EpOdooxPel5xDqXEdXG5r+WggpvnAKMsalBjs= 49 | github.com/go-playground/validator/v10 v10.15.4/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= 50 | github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= 51 | github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= 52 | github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 53 | github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 54 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= 55 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 56 | github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= 57 | github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= 58 | github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= 59 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 60 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= 61 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= 62 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= 63 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= 64 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= 65 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= 66 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 67 | github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= 68 | github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 69 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 70 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 71 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 72 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 73 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 74 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 75 | github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= 76 | github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 77 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 78 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 79 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 80 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 81 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 82 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 83 | github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= 84 | github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= 85 | github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= 86 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 87 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 88 | github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= 89 | github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= 90 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 91 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 92 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 93 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 94 | github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= 95 | github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= 96 | github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= 97 | github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= 98 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 99 | github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= 100 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 101 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 102 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 103 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 104 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 105 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 106 | github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= 107 | github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= 108 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 109 | github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= 110 | github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= 111 | github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= 112 | github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= 113 | github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= 114 | github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= 115 | github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= 116 | github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= 117 | github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= 118 | github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= 119 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 120 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 121 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 122 | github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= 123 | github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= 124 | github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= 125 | github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= 126 | github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= 127 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 128 | github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= 129 | github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= 130 | github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= 131 | github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= 132 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 133 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 134 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 135 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 136 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 137 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 138 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 139 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 140 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 141 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 142 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 143 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 144 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 145 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 146 | github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= 147 | github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= 148 | github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 149 | github.com/tidwall/gjson v1.14.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 150 | github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= 151 | github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= 152 | github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= 153 | github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= 154 | github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 155 | github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= 156 | github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= 157 | github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= 158 | github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= 159 | github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU= 160 | github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI= 161 | github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk= 162 | github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= 163 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= 164 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= 165 | github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= 166 | github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= 167 | github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= 168 | github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 169 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 170 | github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw= 171 | github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= 172 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 173 | golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y= 174 | golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 175 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 176 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 177 | golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 178 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 179 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 180 | golang.org/x/crypto v0.4.0/go.mod h1:3quD/ATkf6oY+rnes5c3ExXTbLc8mueNue5/DoinL80= 181 | golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck= 182 | golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= 183 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 184 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 185 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 186 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 187 | golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= 188 | golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= 189 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 190 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 191 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 192 | golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= 193 | golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= 194 | golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8= 195 | golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= 196 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 197 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 198 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 199 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 200 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 201 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 202 | golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 203 | golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 204 | golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 205 | golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 206 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 207 | golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 208 | golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 209 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 210 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 211 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 212 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 213 | golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 214 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 215 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 216 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 217 | golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 218 | golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 219 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 220 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 221 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 222 | golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 223 | golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= 224 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 225 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 226 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 227 | golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= 228 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 229 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 230 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 231 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 232 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 233 | golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 234 | golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= 235 | golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= 236 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 237 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 238 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 239 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 240 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 241 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 242 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 243 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= 244 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= 245 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= 246 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= 247 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= 248 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= 249 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 250 | google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 251 | google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 252 | google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= 253 | google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 254 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 255 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 256 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 257 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 258 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= 259 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 260 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= 261 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 262 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 263 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 264 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 265 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 266 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 267 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 268 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 269 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 270 | nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= 271 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= 272 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Author: Jrohy 3 | # github: https://github.com/Jrohy/trojan 4 | 5 | #定义操作变量, 0为否, 1为是 6 | help=0 7 | 8 | remove=0 9 | 10 | update=0 11 | 12 | download_url="https://github.com/Jrohy/trojan/releases/download/" 13 | 14 | version_check="https://api.github.com/repos/Jrohy/trojan/releases/latest" 15 | 16 | service_url="https://raw.githubusercontent.com/Jrohy/trojan/master/asset/trojan-web.service" 17 | 18 | [[ -e /var/lib/trojan-manager ]] && update=1 19 | 20 | #Centos 临时取消别名 21 | [[ -f /etc/redhat-release && -z $(echo $SHELL|grep zsh) ]] && unalias -a 22 | 23 | [[ -z $(echo $SHELL|grep zsh) ]] && shell_way="bash" || shell_way="zsh" 24 | 25 | #######color code######## 26 | red="31m" 27 | green="32m" 28 | yellow="33m" 29 | blue="36m" 30 | fuchsia="35m" 31 | 32 | colorEcho(){ 33 | color=$1 34 | echo -e "\033[${color}${@:2}\033[0m" 35 | } 36 | 37 | #######get params######### 38 | while [[ $# > 0 ]];do 39 | key="$1" 40 | case $key in 41 | --remove) 42 | remove=1 43 | ;; 44 | -h|--help) 45 | help=1 46 | ;; 47 | *) 48 | # unknown option 49 | ;; 50 | esac 51 | shift # past argument or value 52 | done 53 | ############################# 54 | 55 | help(){ 56 | echo "bash $0 [-h|--help] [--remove]" 57 | echo " -h, --help Show help" 58 | echo " --remove remove trojan" 59 | return 0 60 | } 61 | 62 | removeTrojan() { 63 | #移除trojan 64 | rm -rf /usr/bin/trojan >/dev/null 2>&1 65 | rm -rf /usr/local/etc/trojan >/dev/null 2>&1 66 | rm -f /etc/systemd/system/trojan.service >/dev/null 2>&1 67 | 68 | #移除trojan管理程序 69 | rm -f /usr/local/bin/trojan >/dev/null 2>&1 70 | rm -rf /var/lib/trojan-manager >/dev/null 2>&1 71 | rm -f /etc/systemd/system/trojan-web.service >/dev/null 2>&1 72 | 73 | systemctl daemon-reload 74 | 75 | #移除trojan的专用db 76 | docker rm -f trojan-mysql trojan-mariadb >/dev/null 2>&1 77 | rm -rf /home/mysql /home/mariadb >/dev/null 2>&1 78 | 79 | #移除环境变量 80 | sed -i '/trojan/d' ~/.${shell_way}rc 81 | source ~/.${shell_way}rc 82 | 83 | colorEcho ${green} "uninstall success!" 84 | } 85 | 86 | checkSys() { 87 | #检查是否为Root 88 | [ $(id -u) != "0" ] && { colorEcho ${red} "Error: You must be root to run this script"; exit 1; } 89 | 90 | arch=$(uname -m 2> /dev/null) 91 | if [[ $arch != x86_64 && $arch != aarch64 ]];then 92 | colorEcho $yellow "not support $arch machine". 93 | exit 1 94 | fi 95 | 96 | if [[ `command -v apt-get` ]];then 97 | package_manager='apt-get' 98 | elif [[ `command -v dnf` ]];then 99 | package_manager='dnf' 100 | elif [[ `command -v yum` ]];then 101 | package_manager='yum' 102 | else 103 | colorEcho $red "Not support OS!" 104 | exit 1 105 | fi 106 | 107 | # 缺失/usr/local/bin路径时自动添加 108 | [[ -z `echo $PATH|grep /usr/local/bin` ]] && { echo 'export PATH=$PATH:/usr/local/bin' >> /etc/bashrc; source /etc/bashrc; } 109 | } 110 | 111 | #安装依赖 112 | installDependent(){ 113 | if [[ ${package_manager} == 'dnf' || ${package_manager} == 'yum' ]];then 114 | ${package_manager} install socat crontabs bash-completion -y 115 | else 116 | ${package_manager} update 117 | ${package_manager} install socat cron bash-completion xz-utils -y 118 | fi 119 | } 120 | 121 | setupCron() { 122 | if [[ `crontab -l 2>/dev/null|grep acme` ]]; then 123 | if [[ -z `crontab -l 2>/dev/null|grep trojan-web` || `crontab -l 2>/dev/null|grep trojan-web|grep "&"` ]]; then 124 | #计算北京时间早上3点时VPS的实际时间 125 | origin_time_zone=$(date -R|awk '{printf"%d",$6}') 126 | local_time_zone=${origin_time_zone%00} 127 | beijing_zone=8 128 | beijing_update_time=3 129 | diff_zone=$[$beijing_zone-$local_time_zone] 130 | local_time=$[$beijing_update_time-$diff_zone] 131 | if [ $local_time -lt 0 ];then 132 | local_time=$[24+$local_time] 133 | elif [ $local_time -ge 24 ];then 134 | local_time=$[$local_time-24] 135 | fi 136 | crontab -l 2>/dev/null|sed '/acme.sh/d' > crontab.txt 137 | echo "0 ${local_time}"' * * * systemctl stop trojan-web; "/root/.acme.sh"/acme.sh --cron --home "/root/.acme.sh" > /dev/null; systemctl start trojan-web' >> crontab.txt 138 | crontab crontab.txt 139 | rm -f crontab.txt 140 | fi 141 | fi 142 | } 143 | 144 | installTrojan(){ 145 | local show_tip=0 146 | if [[ $update == 1 ]];then 147 | systemctl stop trojan-web >/dev/null 2>&1 148 | rm -f /usr/local/bin/trojan 149 | fi 150 | lastest_version=$(curl -H 'Cache-Control: no-cache' -s "$version_check" | grep 'tag_name' | cut -d\" -f4) 151 | echo "正在下载管理程序`colorEcho $blue $lastest_version`版本..." 152 | [[ $arch == x86_64 ]] && bin="trojan-linux-amd64" || bin="trojan-linux-arm64" 153 | curl -L "$download_url/$lastest_version/$bin" -o /usr/local/bin/trojan 154 | chmod +x /usr/local/bin/trojan 155 | if [[ ! -e /etc/systemd/system/trojan-web.service ]];then 156 | show_tip=1 157 | curl -L $service_url -o /etc/systemd/system/trojan-web.service 158 | systemctl daemon-reload 159 | systemctl enable trojan-web 160 | fi 161 | #命令补全环境变量 162 | [[ -z $(grep trojan ~/.${shell_way}rc) ]] && echo "source <(trojan completion ${shell_way})" >> ~/.${shell_way}rc 163 | source ~/.${shell_way}rc 164 | if [[ $update == 0 ]];then 165 | colorEcho $green "安装trojan管理程序成功!\n" 166 | echo -e "运行命令`colorEcho $blue trojan`可进行trojan管理\n" 167 | /usr/local/bin/trojan 168 | else 169 | if [[ `cat /usr/local/etc/trojan/config.json|grep -w "\"db\""` ]];then 170 | sed -i "s/\"db\"/\"database\"/g" /usr/local/etc/trojan/config.json 171 | systemctl restart trojan 172 | fi 173 | /usr/local/bin/trojan upgrade db 174 | if [[ -z `cat /usr/local/etc/trojan/config.json|grep sni` ]];then 175 | /usr/local/bin/trojan upgrade config 176 | fi 177 | systemctl restart trojan-web 178 | colorEcho $green "更新trojan管理程序成功!\n" 179 | fi 180 | setupCron 181 | [[ $show_tip == 1 ]] && echo "浏览器访问'`colorEcho $blue https://域名`'可在线trojan多用户管理" 182 | } 183 | 184 | main(){ 185 | [[ ${help} == 1 ]] && help && return 186 | [[ ${remove} == 1 ]] && removeTrojan && return 187 | [[ $update == 0 ]] && echo "正在安装trojan管理程序.." || echo "正在更新trojan管理程序.." 188 | checkSys 189 | [[ $update == 0 ]] && installDependent 190 | installTrojan 191 | } 192 | 193 | main 194 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "trojan/cmd" 4 | 5 | func main() { 6 | cmd.Execute() 7 | } 8 | -------------------------------------------------------------------------------- /trojan/client.go: -------------------------------------------------------------------------------- 1 | package trojan 2 | 3 | import ( 4 | "encoding/base64" 5 | "fmt" 6 | "trojan/core" 7 | "trojan/util" 8 | ) 9 | 10 | var clientPath = "/root/config.json" 11 | 12 | // GenClientJson 生成客户端json 13 | func GenClientJson() { 14 | fmt.Println() 15 | var user core.User 16 | domain, port := GetDomainAndPort() 17 | mysql := core.GetMysql() 18 | userList, err := mysql.GetData() 19 | if err != nil { 20 | fmt.Println(err.Error()) 21 | return 22 | } 23 | if len(userList) == 1 { 24 | user = *userList[0] 25 | } else { 26 | UserList() 27 | choice := util.LoopInput("请选择要生成配置文件的用户序号: ", userList, true) 28 | if choice < 0 { 29 | return 30 | } 31 | user = *userList[choice-1] 32 | } 33 | pass, err := base64.StdEncoding.DecodeString(user.Password) 34 | if err != nil { 35 | fmt.Println(util.Red("Base64解码失败: " + err.Error())) 36 | return 37 | } 38 | if !core.WriteClient(port, string(pass), domain, clientPath) { 39 | fmt.Println(util.Red("生成配置文件失败!")) 40 | } else { 41 | fmt.Println("成功生成配置文件: " + util.Green(clientPath)) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /trojan/info.go: -------------------------------------------------------------------------------- 1 | package trojan 2 | 3 | var ( 4 | // MVersion 程序版本号 5 | MVersion string 6 | // BuildDate 编译时间 7 | BuildDate string 8 | // GoVersion go版本 9 | GoVersion string 10 | // GitVersion git版本 11 | GitVersion string 12 | ) 13 | -------------------------------------------------------------------------------- /trojan/install.go: -------------------------------------------------------------------------------- 1 | package trojan 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "runtime" 7 | "strconv" 8 | "strings" 9 | "time" 10 | "trojan/asset" 11 | "trojan/core" 12 | "trojan/util" 13 | ) 14 | 15 | var ( 16 | dockerInstallUrl = "https://docker-install.netlify.app/install.sh" 17 | dbDockerRun = "docker run --name trojan-mariadb --restart=always -p %d:3306 -v /home/mariadb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=%s -e MYSQL_ROOT_HOST=%% -e MYSQL_DATABASE=trojan -d mariadb:10.2" 18 | ) 19 | 20 | // InstallMenu 安装目录 21 | func InstallMenu() { 22 | fmt.Println() 23 | menu := []string{"更新trojan", "证书申请", "安装mysql"} 24 | switch util.LoopInput("请选择: ", menu, true) { 25 | case 1: 26 | InstallTrojan("") 27 | case 2: 28 | InstallTls() 29 | case 3: 30 | InstallMysql() 31 | default: 32 | return 33 | } 34 | } 35 | 36 | // InstallDocker 安装docker 37 | func InstallDocker() { 38 | if !util.CheckCommandExists("docker") { 39 | util.RunWebShell(dockerInstallUrl) 40 | fmt.Println() 41 | } 42 | } 43 | 44 | // InstallTrojan 安装trojan 45 | func InstallTrojan(version string) { 46 | fmt.Println() 47 | data := string(asset.GetAsset("trojan-install.sh")) 48 | checkTrojan := util.ExecCommandWithResult("systemctl list-unit-files|grep trojan.service") 49 | if (checkTrojan == "" && runtime.GOARCH != "amd64") || Type() == "trojan-go" { 50 | data = strings.ReplaceAll(data, "TYPE=0", "TYPE=1") 51 | } 52 | if version != "" { 53 | data = strings.ReplaceAll(data, "INSTALL_VERSION=\"\"", "INSTALL_VERSION=\""+version+"\"") 54 | } 55 | util.ExecCommand(data) 56 | util.OpenPort(443) 57 | util.SystemctlRestart("trojan") 58 | util.SystemctlEnable("trojan") 59 | } 60 | 61 | // InstallTls 安装证书 62 | func InstallTls() { 63 | domain := "" 64 | server := "letsencrypt" 65 | fmt.Println() 66 | choice := util.LoopInput("请选择使用证书方式: ", []string{"Let's Encrypt 证书", "ZeroSSL 证书", "BuyPass 证书", "自定义证书路径"}, true) 67 | if choice < 0 { 68 | return 69 | } else if choice == 4 { 70 | crtFile := util.Input("请输入证书的cert文件路径: ", "") 71 | keyFile := util.Input("请输入证书的key文件路径: ", "") 72 | if !util.IsExists(crtFile) || !util.IsExists(keyFile) { 73 | fmt.Println("输入的cert或者key文件不存在!") 74 | } else { 75 | domain = util.Input("请输入此证书对应的域名: ", "") 76 | if domain == "" { 77 | fmt.Println("输入域名为空!") 78 | return 79 | } 80 | core.WriteTls(crtFile, keyFile, domain) 81 | } 82 | } else { 83 | if choice == 2 { 84 | server = "zerossl" 85 | } else if choice == 3 { 86 | server = "buypass" 87 | } 88 | localIP := util.GetLocalIP() 89 | fmt.Printf("本机ip: %s\n", localIP) 90 | for { 91 | domain = util.Input("请输入申请证书的域名: ", "") 92 | ipList, err := net.LookupIP(domain) 93 | fmt.Printf("%s 解析到的ip: %v\n", domain, ipList) 94 | if err != nil { 95 | fmt.Println(err) 96 | fmt.Println("域名有误,请重新输入") 97 | continue 98 | } 99 | checkIp := false 100 | for _, ip := range ipList { 101 | if localIP == ip.String() { 102 | checkIp = true 103 | } 104 | } 105 | if checkIp { 106 | break 107 | } else { 108 | fmt.Println("输入的域名和本机ip不一致, 请重新输入!") 109 | } 110 | } 111 | util.InstallPack("socat") 112 | if !util.IsExists("/root/.acme.sh/acme.sh") { 113 | util.RunWebShell("https://get.acme.sh") 114 | } 115 | util.SystemctlStop("trojan-web") 116 | util.OpenPort(80) 117 | checkResult := util.ExecCommandWithResult("/root/.acme.sh/acme.sh -v|tr -cd '[0-9]'") 118 | acmeVersion, _ := strconv.Atoi(checkResult) 119 | if acmeVersion < 300 { 120 | util.ExecCommand("/root/.acme.sh/acme.sh --upgrade") 121 | } 122 | if server != "letsencrypt" { 123 | var email string 124 | for { 125 | email = util.Input(fmt.Sprintf("请输入申请%s域名所需的邮箱: ", server), "") 126 | if email == "" { 127 | fmt.Println("申请域名的邮箱地址为空!") 128 | return 129 | } else if util.VerifyEmailFormat(email) { 130 | break 131 | } else { 132 | fmt.Println("邮箱格式不正确, 请重新输入!") 133 | } 134 | } 135 | util.ExecCommand(fmt.Sprintf("bash /root/.acme.sh/acme.sh --server %s --register-account -m %s", server, email)) 136 | } 137 | issueCommand := fmt.Sprintf("bash /root/.acme.sh/acme.sh --issue -d %s --debug --standalone --keylength ec-256 --force --server %s", domain, server) 138 | if server == "buypass" { 139 | issueCommand = issueCommand + " --days 170" 140 | } 141 | util.ExecCommand(issueCommand) 142 | crtFile := "/root/.acme.sh/" + domain + "_ecc" + "/fullchain.cer" 143 | keyFile := "/root/.acme.sh/" + domain + "_ecc" + "/" + domain + ".key" 144 | core.WriteTls(crtFile, keyFile, domain) 145 | } 146 | Restart() 147 | util.SystemctlRestart("trojan-web") 148 | fmt.Println() 149 | } 150 | 151 | // InstallMysql 安装mysql 152 | func InstallMysql() { 153 | var ( 154 | mysql core.Mysql 155 | choice int 156 | ) 157 | fmt.Println() 158 | if util.IsExists("/.dockerenv") { 159 | choice = 2 160 | } else { 161 | choice = util.LoopInput("请选择: ", []string{"安装docker版mysql(mariadb)", "输入自定义mysql连接"}, true) 162 | } 163 | if choice < 0 { 164 | return 165 | } else if choice == 1 { 166 | mysql = core.Mysql{ServerAddr: "127.0.0.1", ServerPort: util.RandomPort(), Password: util.RandString(8, util.LETTER+util.DIGITS), Username: "root", Database: "trojan"} 167 | InstallDocker() 168 | fmt.Println(fmt.Sprintf(dbDockerRun, mysql.ServerPort, mysql.Password)) 169 | if util.CheckCommandExists("setenforce") { 170 | util.ExecCommand("setenforce 0") 171 | } 172 | util.OpenPort(mysql.ServerPort) 173 | util.ExecCommand(fmt.Sprintf(dbDockerRun, mysql.ServerPort, mysql.Password)) 174 | db := mysql.GetDB() 175 | for { 176 | fmt.Printf("%s mariadb启动中,请稍等...\n", time.Now().Format("2006-01-02 15:04:05")) 177 | err := db.Ping() 178 | if err == nil { 179 | db.Close() 180 | break 181 | } else { 182 | time.Sleep(2 * time.Second) 183 | } 184 | } 185 | fmt.Println("mariadb启动成功!") 186 | } else if choice == 2 { 187 | mysql = core.Mysql{} 188 | for { 189 | for { 190 | mysqlUrl := util.Input("请输入mysql连接地址(格式: host:port), 默认连接地址为127.0.0.1:3306, 使用直接回车, 否则输入自定义连接地址: ", 191 | "127.0.0.1:3306") 192 | urlInfo := strings.Split(mysqlUrl, ":") 193 | if len(urlInfo) != 2 { 194 | fmt.Printf("输入的%s不符合匹配格式(host:port)\n", mysqlUrl) 195 | continue 196 | } 197 | port, err := strconv.Atoi(urlInfo[1]) 198 | if err != nil { 199 | fmt.Printf("%s不是数字\n", urlInfo[1]) 200 | continue 201 | } 202 | mysql.ServerAddr, mysql.ServerPort = urlInfo[0], port 203 | break 204 | } 205 | mysql.Username = util.Input("请输入mysql的用户名(回车使用root): ", "root") 206 | mysql.Password = util.Input(fmt.Sprintf("请输入mysql %s用户的密码: ", mysql.Username), "") 207 | db := mysql.GetDB() 208 | if db != nil && db.Ping() == nil { 209 | mysql.Database = util.Input("请输入使用的数据库名(不存在可自动创建, 回车使用trojan): ", "trojan") 210 | db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s;", mysql.Database)) 211 | break 212 | } else { 213 | fmt.Println("连接mysql失败, 请重新输入") 214 | } 215 | } 216 | } 217 | mysql.CreateTable() 218 | core.WriteMysql(&mysql) 219 | if userList, _ := mysql.GetData(); len(userList) == 0 { 220 | AddUser() 221 | } 222 | Restart() 223 | fmt.Println() 224 | } 225 | -------------------------------------------------------------------------------- /trojan/trojan.go: -------------------------------------------------------------------------------- 1 | package trojan 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "os" 7 | "os/signal" 8 | "runtime" 9 | "strconv" 10 | "strings" 11 | "trojan/core" 12 | "trojan/util" 13 | ) 14 | 15 | // ControlMenu Trojan控制菜单 16 | func ControlMenu() { 17 | fmt.Println() 18 | tType := Type() 19 | if tType == "trojan" { 20 | tType = "trojan-go" 21 | } else { 22 | tType = "trojan" 23 | } 24 | menu := []string{"启动trojan", "停止trojan", "重启trojan", "查看trojan状态", "查看trojan日志", "修改trojan端口"} 25 | menu = append(menu, "切换为"+tType) 26 | switch util.LoopInput("请选择: ", menu, true) { 27 | case 1: 28 | Start() 29 | case 2: 30 | Stop() 31 | case 3: 32 | Restart() 33 | case 4: 34 | Status(true) 35 | case 5: 36 | go util.Log("trojan", 300) 37 | c := make(chan os.Signal, 1) 38 | signal.Notify(c, os.Interrupt, os.Kill) 39 | //阻塞 40 | <-c 41 | case 6: 42 | ChangePort() 43 | case 7: 44 | if err := SwitchType(tType); err != nil { 45 | fmt.Println(err) 46 | } 47 | } 48 | } 49 | 50 | // Restart 重启trojan 51 | func Restart() { 52 | util.OpenPort(core.GetConfig().LocalPort) 53 | util.SystemctlRestart("trojan") 54 | } 55 | 56 | // Start 启动trojan 57 | func Start() { 58 | util.OpenPort(core.GetConfig().LocalPort) 59 | util.SystemctlStart("trojan") 60 | } 61 | 62 | // Stop 停止trojan 63 | func Stop() { 64 | util.SystemctlStop("trojan") 65 | } 66 | 67 | // Status 获取trojan状态 68 | func Status(isPrint bool) string { 69 | result := util.SystemctlStatus("trojan") 70 | if isPrint { 71 | fmt.Println(result) 72 | } 73 | return result 74 | } 75 | 76 | // UpTime Trojan运行时间 77 | func UpTime() string { 78 | result := strings.TrimSpace(util.ExecCommandWithResult("ps -Ao etime,args|grep -v grep|grep /usr/local/etc/trojan/config.json")) 79 | resultSlice := strings.Split(result, " ") 80 | if len(resultSlice) > 0 { 81 | return resultSlice[0] 82 | } 83 | return "" 84 | } 85 | 86 | // ChangePort 修改trojan端口 87 | func ChangePort() { 88 | config := core.GetConfig() 89 | oldPort := config.LocalPort 90 | randomPort := util.RandomPort() 91 | fmt.Println("当前trojan端口: " + util.Green(strconv.Itoa(oldPort))) 92 | newPortStr := util.Input(fmt.Sprintf("请输入新的trojan端口(若要使用随机端口%s直接回车即可): ", util.Blue(strconv.Itoa(randomPort))), strconv.Itoa(randomPort)) 93 | newPort, err := strconv.Atoi(newPortStr) 94 | if err != nil { 95 | fmt.Println("修改端口失败: " + err.Error()) 96 | return 97 | } 98 | if core.WritePort(newPort) { 99 | util.OpenPort(newPort) 100 | fmt.Println(util.Green("端口修改成功!")) 101 | Restart() 102 | } else { 103 | fmt.Println(util.Red("端口修改成功!")) 104 | } 105 | } 106 | 107 | // Version Trojan版本 108 | func Version() string { 109 | flag := "-v" 110 | if Type() == "trojan-go" { 111 | flag = "-version" 112 | } 113 | result := strings.TrimSpace(util.ExecCommandWithResult("/usr/bin/trojan/trojan " + flag)) 114 | if len(result) == 0 { 115 | return "" 116 | } 117 | firstLine := strings.Split(result, "\n")[0] 118 | tempSlice := strings.Split(firstLine, " ") 119 | return tempSlice[len(tempSlice)-1] 120 | } 121 | 122 | // SwitchType 切换Trojan类型 123 | func SwitchType(tType string) error { 124 | ARCH := runtime.GOARCH 125 | if ARCH != "amd64" && ARCH != "arm64" { 126 | return errors.New("not support " + ARCH + " machine") 127 | } 128 | if tType == "trojan" && ARCH != "amd64" { 129 | return errors.New("trojan not support " + ARCH + " machine") 130 | } 131 | if err := core.SetValue("trojanType", tType); err != nil { 132 | return err 133 | } 134 | InstallTrojan("") 135 | return nil 136 | } 137 | 138 | // Type Trojan类型 139 | func Type() string { 140 | tType, _ := core.GetValue("trojanType") 141 | if tType == "" { 142 | if strings.Contains(Status(false), "trojan-go") { 143 | tType = "trojan-go" 144 | } else { 145 | tType = "trojan" 146 | } 147 | _ = core.SetValue("trojanType", tType) 148 | } 149 | return tType 150 | } 151 | -------------------------------------------------------------------------------- /trojan/user.go: -------------------------------------------------------------------------------- 1 | package trojan 2 | 3 | import ( 4 | "encoding/base64" 5 | "fmt" 6 | "net/url" 7 | "strconv" 8 | "strings" 9 | "trojan/core" 10 | "trojan/util" 11 | ) 12 | 13 | // UserMenu 用户管理菜单 14 | func UserMenu() { 15 | fmt.Println() 16 | menu := []string{"新增用户", "删除用户", "限制流量", "清空流量", "设置限期", "取消限期"} 17 | switch util.LoopInput("请选择: ", menu, false) { 18 | case 1: 19 | AddUser() 20 | case 2: 21 | DelUser() 22 | case 3: 23 | SetUserQuota() 24 | case 4: 25 | CleanData() 26 | case 5: 27 | SetupExpire() 28 | case 6: 29 | CancelExpire() 30 | } 31 | } 32 | 33 | // AddUser 添加用户 34 | func AddUser() { 35 | randomUser := util.RandString(4, util.LETTER) 36 | randomPass := util.RandString(8, util.LETTER+util.DIGITS) 37 | inputUser := util.Input(fmt.Sprintf("生成随机用户名: %s, 使用直接回车, 否则输入自定义用户名: ", randomUser), randomUser) 38 | if inputUser == "admin" { 39 | fmt.Println(util.Yellow("不能新建用户名为'admin'的用户!")) 40 | return 41 | } 42 | mysql := core.GetMysql() 43 | if user := mysql.GetUserByName(inputUser); user != nil { 44 | fmt.Println(util.Yellow("已存在用户名为: " + inputUser + " 的用户!")) 45 | return 46 | } 47 | inputPass := util.Input(fmt.Sprintf("生成随机密码: %s, 使用直接回车, 否则输入自定义密码: ", randomPass), randomPass) 48 | base64Pass := base64.StdEncoding.EncodeToString([]byte(inputPass)) 49 | if user := mysql.GetUserByPass(base64Pass); user != nil { 50 | fmt.Println(util.Yellow("已存在密码为: " + inputPass + " 的用户!")) 51 | return 52 | } 53 | if mysql.CreateUser(inputUser, base64Pass, inputPass) == nil { 54 | fmt.Println("新增用户成功!") 55 | } 56 | } 57 | 58 | // DelUser 删除用户 59 | func DelUser() { 60 | userList := UserList() 61 | mysql := core.GetMysql() 62 | choice := util.LoopInput("请选择要删除的用户序号: ", userList, true) 63 | if choice == -1 { 64 | return 65 | } 66 | if mysql.DeleteUser(userList[choice-1].ID) == nil { 67 | fmt.Println("删除用户成功!") 68 | Restart() 69 | } 70 | } 71 | 72 | // SetUserQuota 限制用户流量 73 | func SetUserQuota() { 74 | var ( 75 | limit int 76 | err error 77 | ) 78 | userList := UserList() 79 | mysql := core.GetMysql() 80 | choice := util.LoopInput("请选择要限制流量的用户序号: ", userList, true) 81 | if choice == -1 { 82 | return 83 | } 84 | for { 85 | quota := util.Input("请输入用户"+userList[choice-1].Username+"限制的流量大小(单位byte)", "") 86 | limit, err = strconv.Atoi(quota) 87 | if err != nil { 88 | fmt.Printf("%s 不是数字, 请重新输入!\n", quota) 89 | } else { 90 | break 91 | } 92 | } 93 | if mysql.SetQuota(userList[choice-1].ID, limit) == nil { 94 | fmt.Println("成功设置用户" + userList[choice-1].Username + "限制流量" + util.Bytefmt(uint64(limit))) 95 | } 96 | } 97 | 98 | // CleanData 清空用户流量 99 | func CleanData() { 100 | userList := UserList() 101 | mysql := core.GetMysql() 102 | choice := util.LoopInput("请选择要清空流量的用户序号: ", userList, true) 103 | if choice == -1 { 104 | return 105 | } 106 | if mysql.CleanData(userList[choice-1].ID) == nil { 107 | fmt.Println("清空流量成功!") 108 | } 109 | } 110 | 111 | // CancelExpire 取消限期 112 | func CancelExpire() { 113 | userList := UserList() 114 | mysql := core.GetMysql() 115 | choice := util.LoopInput("请选择要取消限期的用户序号: ", userList, true) 116 | if choice == -1 { 117 | return 118 | } 119 | if userList[choice-1].UseDays == 0 { 120 | fmt.Println(util.Yellow("选择的用户未设置限期!")) 121 | return 122 | } 123 | if mysql.CancelExpire(userList[choice-1].ID) == nil { 124 | fmt.Println("取消限期成功!") 125 | } 126 | } 127 | 128 | // SetupExpire 设置限期 129 | func SetupExpire() { 130 | userList := UserList() 131 | mysql := core.GetMysql() 132 | choice := util.LoopInput("请选择要设置限期的用户序号: ", userList, true) 133 | if choice == -1 { 134 | return 135 | } 136 | useDayStr := util.Input("请输入要限制使用的天数: ", "") 137 | if useDayStr == "" { 138 | return 139 | } else if strings.Contains(useDayStr, "-") { 140 | fmt.Println(util.Yellow("天数不能为负数")) 141 | return 142 | } else if !util.IsInteger(useDayStr) { 143 | fmt.Println(util.Yellow("输入为非整数!")) 144 | return 145 | } 146 | useDays, _ := strconv.Atoi(useDayStr) 147 | if mysql.SetExpire(userList[choice-1].ID, uint(useDays)) == nil { 148 | fmt.Println("设置限期成功!") 149 | } 150 | } 151 | 152 | // CleanDataByName 清空指定用户流量 153 | func CleanDataByName(usernames []string) { 154 | mysql := core.GetMysql() 155 | if err := mysql.CleanDataByName(usernames); err != nil { 156 | fmt.Println(err.Error()) 157 | } else { 158 | fmt.Println("清空流量成功!") 159 | } 160 | } 161 | 162 | // UserList 获取用户列表并打印显示 163 | func UserList(ids ...string) []*core.User { 164 | mysql := core.GetMysql() 165 | userList, err := mysql.GetData(ids...) 166 | if err != nil { 167 | fmt.Println(err.Error()) 168 | return nil 169 | } 170 | domain, port := GetDomainAndPort() 171 | for i, k := range userList { 172 | pass, err := base64.StdEncoding.DecodeString(k.Password) 173 | if err != nil { 174 | pass = []byte("") 175 | } 176 | fmt.Printf("%d.\n", i+1) 177 | fmt.Println("用户名: " + k.Username) 178 | fmt.Println("密码: " + string(pass)) 179 | fmt.Println("上传流量: " + util.Cyan(util.Bytefmt(k.Upload))) 180 | fmt.Println("下载流量: " + util.Cyan(util.Bytefmt(k.Download))) 181 | if k.Quota < 0 { 182 | fmt.Println("流量限额: " + util.Cyan("无限制")) 183 | } else { 184 | fmt.Println("流量限额: " + util.Cyan(util.Bytefmt(uint64(k.Quota)))) 185 | } 186 | if k.UseDays == 0 { 187 | fmt.Println("到期日期: " + util.Cyan("无限制")) 188 | } else { 189 | fmt.Println("到期日期: " + util.Cyan(k.ExpiryDate)) 190 | } 191 | remark := url.QueryEscape(fmt.Sprintf("%s:%d", domain, port)) 192 | fmt.Println("分享链接: " + util.Green(fmt.Sprintf("trojan://%s@%s:%d#%s", string(pass), domain, port, remark))) 193 | fmt.Println() 194 | } 195 | return userList 196 | } 197 | -------------------------------------------------------------------------------- /trojan/web.go: -------------------------------------------------------------------------------- 1 | package trojan 2 | 3 | import ( 4 | "crypto/sha256" 5 | "fmt" 6 | "trojan/core" 7 | "trojan/util" 8 | ) 9 | 10 | // WebMenu web管理菜单 11 | func WebMenu() { 12 | fmt.Println() 13 | menu := []string{"重置web管理员密码", "修改显示的域名(非申请证书)"} 14 | switch util.LoopInput("请选择: ", menu, true) { 15 | case 1: 16 | ResetAdminPass() 17 | case 2: 18 | SetDomain("") 19 | } 20 | } 21 | 22 | // ResetAdminPass 重置管理员密码 23 | func ResetAdminPass() { 24 | inputPass := util.Input("请输入admin用户密码: ", "") 25 | if inputPass == "" { 26 | fmt.Println("撤销更改!") 27 | } else { 28 | encryPass := sha256.Sum224([]byte(inputPass)) 29 | err := core.SetValue("admin_pass", fmt.Sprintf("%x", encryPass)) 30 | if err == nil { 31 | fmt.Println(util.Green("重置admin密码成功!")) 32 | } else { 33 | fmt.Println(err) 34 | } 35 | } 36 | } 37 | 38 | // SetDomain 设置显示的域名 39 | func SetDomain(domain string) { 40 | if domain == "" { 41 | domain = util.Input("请输入要显示的域名地址: ", "") 42 | } 43 | if domain == "" { 44 | fmt.Println("撤销更改!") 45 | } else { 46 | core.WriteDomain(domain) 47 | Restart() 48 | fmt.Println("修改domain成功!") 49 | } 50 | } 51 | 52 | // GetDomainAndPort 获取域名和端口 53 | func GetDomainAndPort() (string, int) { 54 | config := core.GetConfig() 55 | return config.SSl.Sni, config.LocalPort 56 | } 57 | -------------------------------------------------------------------------------- /util/bytefmt.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | const ( 9 | // BYTE 字节 10 | BYTE = 1 << (10 * iota) 11 | // KILOBYTE 千字节 12 | KILOBYTE 13 | // MEGABYTE 兆字节 14 | MEGABYTE 15 | // GIGABYTE 吉字节 16 | GIGABYTE 17 | // TERABYTE 太字节 18 | TERABYTE 19 | // PETABYTE 拍字节 20 | PETABYTE 21 | // EXABYTE 艾字节 22 | EXABYTE 23 | ) 24 | 25 | // Bytefmt returns a human-readable byte string of the form 10M, 12.5K, and so forth. The following units are available: 26 | // E: Exabyte 27 | // P: Petabyte 28 | // T: Terabyte 29 | // G: Gigabyte 30 | // M: Megabyte 31 | // K: Kilobyte 32 | // B: Byte 33 | // The unit that results in the smallest number greater than or equal to 1 is always chosen. 34 | func Bytefmt(bytes uint64) string { 35 | unit := "" 36 | value := float64(bytes) 37 | 38 | switch { 39 | case bytes >= EXABYTE: 40 | unit = "E" 41 | value = value / EXABYTE 42 | case bytes >= PETABYTE: 43 | unit = "P" 44 | value = value / PETABYTE 45 | case bytes >= TERABYTE: 46 | unit = "T" 47 | value = value / TERABYTE 48 | case bytes >= GIGABYTE: 49 | unit = "G" 50 | value = value / GIGABYTE 51 | case bytes >= MEGABYTE: 52 | unit = "M" 53 | value = value / MEGABYTE 54 | case bytes >= KILOBYTE: 55 | unit = "K" 56 | value = value / KILOBYTE 57 | case bytes >= BYTE: 58 | unit = "B" 59 | case bytes == 0: 60 | return "0B" 61 | } 62 | 63 | result := strconv.FormatFloat(value, 'f', 2, 64) 64 | result = strings.TrimSuffix(result, ".0") 65 | return result + unit 66 | } 67 | -------------------------------------------------------------------------------- /util/command.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "net/http" 8 | "os/exec" 9 | "strings" 10 | ) 11 | 12 | func systemctlReplace(out string) (bool, error) { 13 | var ( 14 | err error 15 | isReplace bool 16 | ) 17 | if IsExists("/.dockerenv") && strings.Contains(out, "Failed to get D-Bus") { 18 | isReplace = true 19 | fmt.Println(Yellow("正在下载并替换适配的systemctl。。")) 20 | if err = ExecCommand("curl -L https://raw.githubusercontent.com/gdraheim/docker-systemctl-replacement/master/files/docker/systemctl.py -o /usr/bin/systemctl && chmod +x /usr/bin/systemctl"); err != nil { 21 | return isReplace, err 22 | } 23 | fmt.Println() 24 | } 25 | return isReplace, err 26 | } 27 | 28 | func systemctlBase(name, operate string) (string, error) { 29 | out, err := exec.Command("bash", "-c", fmt.Sprintf("systemctl %s %s", operate, name)).CombinedOutput() 30 | if v, _ := systemctlReplace(string(out)); v { 31 | out, err = exec.Command("bash", "-c", fmt.Sprintf("systemctl %s %s", operate, name)).CombinedOutput() 32 | } 33 | return string(out), err 34 | } 35 | 36 | // SystemctlStart 服务启动 37 | func SystemctlStart(name string) { 38 | if _, err := systemctlBase(name, "start"); err != nil { 39 | fmt.Println(Red(fmt.Sprintf("启动%s失败!", name))) 40 | } else { 41 | fmt.Println(Green(fmt.Sprintf("启动%s成功!", name))) 42 | } 43 | } 44 | 45 | // SystemctlStop 服务停止 46 | func SystemctlStop(name string) { 47 | if _, err := systemctlBase(name, "stop"); err != nil { 48 | fmt.Println(Red(fmt.Sprintf("停止%s失败!", name))) 49 | } else { 50 | fmt.Println(Green(fmt.Sprintf("停止%s成功!", name))) 51 | } 52 | } 53 | 54 | // SystemctlRestart 服务重启 55 | func SystemctlRestart(name string) { 56 | if _, err := systemctlBase(name, "restart"); err != nil { 57 | fmt.Println(Red(fmt.Sprintf("重启%s失败!", name))) 58 | } else { 59 | fmt.Println(Green(fmt.Sprintf("重启%s成功!", name))) 60 | } 61 | } 62 | 63 | // SystemctlEnable 服务设置开机自启 64 | func SystemctlEnable(name string) { 65 | if _, err := systemctlBase(name, "enable"); err != nil { 66 | fmt.Println(Red(fmt.Sprintf("设置%s开机自启失败!", name))) 67 | } 68 | } 69 | 70 | // SystemctlStatus 服务状态查看 71 | func SystemctlStatus(name string) string { 72 | out, _ := systemctlBase(name, "status") 73 | return out 74 | } 75 | 76 | // CheckCommandExists 检查命令是否存在 77 | func CheckCommandExists(command string) bool { 78 | if _, err := exec.LookPath(command); err != nil { 79 | return false 80 | } 81 | return true 82 | } 83 | 84 | // RunWebShell 运行网上的脚本 85 | func RunWebShell(webShellPath string) { 86 | if !strings.HasPrefix(webShellPath, "http") && !strings.HasPrefix(webShellPath, "https") { 87 | fmt.Printf("shell path must start with http or https!") 88 | return 89 | } 90 | resp, err := http.Get(webShellPath) 91 | if err != nil { 92 | fmt.Println(err.Error()) 93 | } 94 | defer resp.Body.Close() 95 | installShell, err := io.ReadAll(resp.Body) 96 | if err != nil { 97 | fmt.Println(err.Error()) 98 | } 99 | ExecCommand(string(installShell)) 100 | } 101 | 102 | // ExecCommand 运行命令并实时查看运行结果 103 | func ExecCommand(command string) error { 104 | cmd := exec.Command("bash", "-c", command) 105 | 106 | stdout, _ := cmd.StdoutPipe() 107 | stderr, _ := cmd.StderrPipe() 108 | 109 | if err := cmd.Start(); err != nil { 110 | fmt.Println("Error:The command is err: ", err.Error()) 111 | return err 112 | } 113 | ch := make(chan string, 100) 114 | stdoutScan := bufio.NewScanner(stdout) 115 | stderrScan := bufio.NewScanner(stderr) 116 | go func() { 117 | for stdoutScan.Scan() { 118 | line := stdoutScan.Text() 119 | ch <- line 120 | } 121 | }() 122 | go func() { 123 | for stderrScan.Scan() { 124 | line := stderrScan.Text() 125 | ch <- line 126 | } 127 | }() 128 | var err error 129 | go func() { 130 | err = cmd.Wait() 131 | if err != nil && !strings.Contains(err.Error(), "exit status") { 132 | fmt.Println("wait:", err.Error()) 133 | } 134 | close(ch) 135 | }() 136 | for line := range ch { 137 | fmt.Println(line) 138 | } 139 | return err 140 | } 141 | 142 | // ExecCommandWithResult 运行命令并获取结果 143 | func ExecCommandWithResult(command string) string { 144 | out, err := exec.Command("bash", "-c", command).CombinedOutput() 145 | if strings.Contains(command, "systemctl") { 146 | if v, _ := systemctlReplace(string(out)); v { 147 | out, err = exec.Command("bash", "-c", command).CombinedOutput() 148 | } 149 | } 150 | if err != nil && !strings.Contains(err.Error(), "exit status") { 151 | fmt.Println("err: " + err.Error()) 152 | return "" 153 | } 154 | return string(out) 155 | } 156 | -------------------------------------------------------------------------------- /util/linux.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "math/rand" 8 | "net" 9 | "net/http" 10 | "os" 11 | "os/exec" 12 | "strconv" 13 | "time" 14 | ) 15 | 16 | // PortIsUse 判断端口是否占用 17 | func PortIsUse(port int) bool { 18 | _, tcpError := net.DialTimeout("tcp", fmt.Sprintf(":%d", port), time.Millisecond*50) 19 | udpAddr, _ := net.ResolveUDPAddr("udp4", fmt.Sprintf(":%d", port)) 20 | udpConn, udpError := net.ListenUDP("udp", udpAddr) 21 | if udpConn != nil { 22 | defer udpConn.Close() 23 | } 24 | return tcpError == nil || udpError != nil 25 | } 26 | 27 | // RandomPort 获取没占用的随机端口 28 | func RandomPort() int { 29 | for { 30 | rand.New(rand.NewSource(time.Now().UnixNano())) 31 | newPort := rand.Intn(65536) 32 | if !PortIsUse(newPort) { 33 | return newPort 34 | } 35 | } 36 | } 37 | 38 | // IsExists 检测指定路径文件或者文件夹是否存在 39 | func IsExists(path string) bool { 40 | _, err := os.Stat(path) //os.Stat获取文件信息 41 | if err != nil { 42 | if os.IsExist(err) { 43 | return true 44 | } 45 | return false 46 | } 47 | return true 48 | } 49 | 50 | // GetLocalIP 获取本机ipv4地址 51 | func GetLocalIP() string { 52 | resp, err := http.Get("http://api.ipify.org") 53 | if err != nil { 54 | resp, _ = http.Get("http://icanhazip.com") 55 | } 56 | defer resp.Body.Close() 57 | s, _ := io.ReadAll(resp.Body) 58 | return string(s) 59 | } 60 | 61 | // InstallPack 安装指定名字软件 62 | func InstallPack(name string) { 63 | if !CheckCommandExists(name) { 64 | if CheckCommandExists("yum") { 65 | ExecCommand("yum install -y " + name) 66 | } else if CheckCommandExists("apt-get") { 67 | ExecCommand("apt-get update") 68 | ExecCommand("apt-get install -y " + name) 69 | } 70 | } 71 | } 72 | 73 | // OpenPort 开通指定端口 74 | func OpenPort(port int) { 75 | if CheckCommandExists("firewall-cmd") { 76 | ExecCommand(fmt.Sprintf("firewall-cmd --zone=public --add-port=%d/tcp --add-port=%d/udp --permanent >/dev/null 2>&1", port, port)) 77 | ExecCommand("firewall-cmd --reload >/dev/null 2>&1") 78 | } else { 79 | if len(ExecCommandWithResult(fmt.Sprintf(`iptables -nvL --line-number|grep -w "%d"`, port))) > 0 { 80 | return 81 | } 82 | ExecCommand(fmt.Sprintf("iptables -I INPUT -p tcp --dport %d -j ACCEPT", port)) 83 | ExecCommand(fmt.Sprintf("iptables -I INPUT -p udp --dport %d -j ACCEPT", port)) 84 | ExecCommand(fmt.Sprintf("iptables -I OUTPUT -p udp --sport %d -j ACCEPT", port)) 85 | ExecCommand(fmt.Sprintf("iptables -I OUTPUT -p tcp --sport %d -j ACCEPT", port)) 86 | } 87 | } 88 | 89 | // Log 实时打印指定服务日志 90 | func Log(serviceName string, line int) { 91 | result, _ := LogChan(serviceName, "-n "+strconv.Itoa(line), make(chan byte)) 92 | for line := range result { 93 | fmt.Println(line) 94 | } 95 | } 96 | 97 | // LogChan 指定服务实时日志, 返回chan 98 | func LogChan(serviceName, param string, closeChan chan byte) (chan string, error) { 99 | cmd := exec.Command("bash", "-c", fmt.Sprintf("journalctl -f -u %s -o cat %s", serviceName, param)) 100 | 101 | stdout, _ := cmd.StdoutPipe() 102 | 103 | if err := cmd.Start(); err != nil { 104 | fmt.Println("Error:The command is err: ", err.Error()) 105 | return nil, err 106 | } 107 | ch := make(chan string, 100) 108 | stdoutScan := bufio.NewScanner(stdout) 109 | go func() { 110 | for stdoutScan.Scan() { 111 | select { 112 | case <-closeChan: 113 | stdout.Close() 114 | return 115 | default: 116 | ch <- stdoutScan.Text() 117 | } 118 | } 119 | }() 120 | return ch, nil 121 | } 122 | -------------------------------------------------------------------------------- /util/string.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | "github.com/eiannone/keyboard" 6 | "math/rand" 7 | "reflect" 8 | "regexp" 9 | "strconv" 10 | "time" 11 | ) 12 | 13 | const ( 14 | // RED 红色 15 | RED = "\033[31m" 16 | // GREEN 绿色 17 | GREEN = "\033[32m" 18 | // YELLOW 黄色 19 | YELLOW = "\033[33m" 20 | // BLUE 蓝色 21 | BLUE = "\033[34m" 22 | // FUCHSIA 紫红色 23 | FUCHSIA = "\033[35m" 24 | // CYAN 青色 25 | CYAN = "\033[36m" 26 | // WHITE 白色 27 | WHITE = "\033[37m" 28 | // RESET 重置颜色 29 | RESET = "\033[0m" 30 | // LETTER 大小写英文字母常量 31 | LETTER = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 32 | // DIGITS 数字常量 33 | DIGITS = "0123456789" 34 | // SPECIALS 特殊字符常量 35 | SPECIALS = "~=+%^*/()[]{}/!@#$?|" 36 | // ALL 全部字符常量 37 | ALL = LETTER + DIGITS + SPECIALS 38 | ) 39 | 40 | // IsInteger 判断字符串是否为整数 41 | func IsInteger(input string) bool { 42 | _, err := strconv.Atoi(input) 43 | return err == nil 44 | } 45 | 46 | // RandString 随机字符串 47 | func RandString(length int, source string) string { 48 | var runes = []rune(source) 49 | b := make([]rune, length) 50 | rand.New(rand.NewSource(time.Now().UnixNano())) 51 | for i := range b { 52 | b[i] = runes[rand.Intn(len(runes))] 53 | } 54 | return string(b) 55 | } 56 | 57 | // VerifyEmailFormat 邮箱验证 58 | func VerifyEmailFormat(email string) bool { 59 | pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$` 60 | reg := regexp.MustCompile(pattern) 61 | return reg.MatchString(email) 62 | } 63 | 64 | func getChar(str string) string { 65 | err := keyboard.Open() 66 | if err != nil { 67 | panic(err) 68 | } 69 | defer keyboard.Close() 70 | fmt.Print(str) 71 | char, _, _ := keyboard.GetKey() 72 | fmt.Printf("%c\n", char) 73 | if char == 0 { 74 | return "" 75 | } 76 | return string(char) 77 | } 78 | 79 | // LoopInput 循环输入选择, 或者直接回车退出 80 | func LoopInput(tip string, choices interface{}, singleRowPrint bool) int { 81 | reflectValue := reflect.ValueOf(choices) 82 | if reflectValue.Kind() != reflect.Slice && reflectValue.Kind() != reflect.Array { 83 | fmt.Println("only support slice or array type!") 84 | return -1 85 | } 86 | length := reflectValue.Len() 87 | if reflectValue.Type().String() == "[]string" { 88 | if singleRowPrint { 89 | for i := 0; i < length; i++ { 90 | fmt.Printf("%d.%s\n\n", i+1, reflectValue.Index(i).Interface()) 91 | } 92 | } else { 93 | for i := 0; i < length; i++ { 94 | if i%2 == 0 { 95 | fmt.Printf("%d.%-15s\t", i+1, reflectValue.Index(i).Interface()) 96 | } else { 97 | fmt.Printf("%d.%-15s\n\n", i+1, reflectValue.Index(i).Interface()) 98 | } 99 | } 100 | } 101 | } 102 | for { 103 | inputString := "" 104 | if length < 10 { 105 | inputString = getChar(tip) 106 | } else { 107 | fmt.Print(tip) 108 | _, _ = fmt.Scanln(&inputString) 109 | } 110 | if inputString == "" { 111 | return -1 112 | } else if !IsInteger(inputString) { 113 | fmt.Println("输入有误,请重新输入") 114 | continue 115 | } 116 | number, _ := strconv.Atoi(inputString) 117 | if number <= length && number > 0 { 118 | return number 119 | } 120 | fmt.Println("输入数字越界,请重新输入") 121 | } 122 | } 123 | 124 | // Input 读取终端用户输入 125 | func Input(tip string, defaultValue string) string { 126 | input := "" 127 | fmt.Print(tip) 128 | _, _ = fmt.Scanln(&input) 129 | if input == "" && defaultValue != "" { 130 | input = defaultValue 131 | } 132 | return input 133 | } 134 | 135 | // Red 红色 136 | func Red(str string) string { 137 | return RED + str + RESET 138 | } 139 | 140 | // Green 绿色 141 | func Green(str string) string { 142 | return GREEN + str + RESET 143 | } 144 | 145 | // Yellow 黄色 146 | func Yellow(str string) string { 147 | return YELLOW + str + RESET 148 | } 149 | 150 | // Blue 蓝色 151 | func Blue(str string) string { 152 | return BLUE + str + RESET 153 | } 154 | 155 | // Fuchsia 紫红色 156 | func Fuchsia(str string) string { 157 | return FUCHSIA + str + RESET 158 | } 159 | 160 | // Cyan 青色 161 | func Cyan(str string) string { 162 | return CYAN + str + RESET 163 | } 164 | 165 | // White 白色 166 | func White(str string) string { 167 | return WHITE + str + RESET 168 | } 169 | -------------------------------------------------------------------------------- /util/websocket.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "github.com/gorilla/websocket" 7 | "net/http" 8 | "sync" 9 | ) 10 | 11 | // http升级websocket协议的配置 12 | var wsUpgrader = websocket.Upgrader{ 13 | // 允许所有CORS跨域请求 14 | CheckOrigin: func(r *http.Request) bool { 15 | return true 16 | }, 17 | } 18 | 19 | // WsMessage websocket消息 20 | type WsMessage struct { 21 | MessageType int 22 | Data []byte 23 | } 24 | 25 | // WsConnection 封装websocket连接 26 | type WsConnection struct { 27 | wsSocket *websocket.Conn // 底层websocket 28 | inChan chan *WsMessage // 读取队列 29 | outChan chan *WsMessage // 发送队列 30 | 31 | mutex sync.Mutex // 避免重复关闭管道 32 | isClosed bool 33 | CloseChan chan byte // 关闭通知 34 | } 35 | 36 | // 读取协程 37 | func (wsConn *WsConnection) wsReadLoop() { 38 | var ( 39 | msgType int 40 | data []byte 41 | msg *WsMessage 42 | err error 43 | ) 44 | for { 45 | // 读一个message 46 | if msgType, data, err = wsConn.wsSocket.ReadMessage(); err != nil { 47 | fmt.Println("Read error: " + err.Error()) 48 | goto CLOSED 49 | } 50 | msg = &WsMessage{ 51 | msgType, 52 | data, 53 | } 54 | // 放入请求队列 55 | select { 56 | case wsConn.inChan <- msg: 57 | if string(data) == "exit" { 58 | goto CLOSED 59 | } 60 | case <-wsConn.CloseChan: 61 | goto CLOSED 62 | } 63 | } 64 | CLOSED: 65 | wsConn.WsClose() 66 | } 67 | 68 | // 发送协程 69 | func (wsConn *WsConnection) wsWriteLoop() { 70 | var ( 71 | msg *WsMessage 72 | err error 73 | ) 74 | for { 75 | select { 76 | // 取一个应答 77 | case msg = <-wsConn.outChan: 78 | // 写给websocket 79 | if err = wsConn.wsSocket.WriteMessage(msg.MessageType, msg.Data); err != nil { 80 | fmt.Println(err) 81 | goto CLOSED 82 | } 83 | case <-wsConn.CloseChan: 84 | goto CLOSED 85 | } 86 | } 87 | CLOSED: 88 | wsConn.WsClose() 89 | } 90 | 91 | // InitWebsocket 初始化ws 92 | func InitWebsocket(resp http.ResponseWriter, req *http.Request) (wsConn *WsConnection, err error) { 93 | var ( 94 | wsSocket *websocket.Conn 95 | ) 96 | // 应答客户端告知升级连接为websocket 97 | if wsSocket, err = wsUpgrader.Upgrade(resp, req, nil); err != nil { 98 | return 99 | } 100 | wsConn = &WsConnection{ 101 | wsSocket: wsSocket, 102 | inChan: make(chan *WsMessage, 1000), 103 | outChan: make(chan *WsMessage, 1000), 104 | CloseChan: make(chan byte), 105 | isClosed: false, 106 | } 107 | 108 | // 读协程 109 | go wsConn.wsReadLoop() 110 | // 写协程 111 | go wsConn.wsWriteLoop() 112 | 113 | return 114 | } 115 | 116 | // WsWrite 发送消息 117 | func (wsConn *WsConnection) WsWrite(messageType int, data []byte) (err error) { 118 | select { 119 | case wsConn.outChan <- &WsMessage{messageType, data}: 120 | case <-wsConn.CloseChan: 121 | err = errors.New("websocket closed") 122 | } 123 | return 124 | } 125 | 126 | // WsRead 读取消息 127 | func (wsConn *WsConnection) WsRead() (msg *WsMessage, err error) { 128 | select { 129 | case msg = <-wsConn.inChan: 130 | return 131 | case <-wsConn.CloseChan: 132 | err = errors.New("websocket closed") 133 | } 134 | return 135 | } 136 | 137 | // WsClose 关闭连接 138 | func (wsConn *WsConnection) WsClose() { 139 | wsConn.wsSocket.Close() 140 | wsConn.mutex.Lock() 141 | defer wsConn.mutex.Unlock() 142 | if !wsConn.isClosed { 143 | wsConn.isClosed = true 144 | close(wsConn.CloseChan) 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /web/auth.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "fmt" 5 | "github.com/appleboy/gin-jwt/v2" 6 | "github.com/gin-gonic/gin" 7 | "time" 8 | "trojan/core" 9 | "trojan/util" 10 | "trojan/web/controller" 11 | ) 12 | 13 | var ( 14 | identityKey = "id" 15 | authMiddleware *jwt.GinJWTMiddleware 16 | err error 17 | ) 18 | 19 | // Login auth用户验证结构体 20 | type Login struct { 21 | Username string `form:"username" json:"username" binding:"required"` 22 | Password string `form:"password" json:"password" binding:"required"` 23 | } 24 | 25 | func getSecretKey() string { 26 | sk, _ := core.GetValue("secretKey") 27 | if sk == "" { 28 | sk = util.RandString(15, util.ALL) 29 | core.SetValue("secretKey", sk) 30 | } 31 | return sk 32 | } 33 | 34 | func jwtInit(timeout int) { 35 | authMiddleware, err = jwt.New(&jwt.GinJWTMiddleware{ 36 | Realm: "trojan-manager", 37 | Key: []byte(getSecretKey()), 38 | Timeout: time.Minute * time.Duration(timeout), 39 | MaxRefresh: time.Minute * time.Duration(timeout), 40 | IdentityKey: identityKey, 41 | SendCookie: true, 42 | PayloadFunc: func(data interface{}) jwt.MapClaims { 43 | if v, ok := data.(*Login); ok { 44 | return jwt.MapClaims{ 45 | identityKey: v.Username, 46 | } 47 | } 48 | return jwt.MapClaims{} 49 | }, 50 | IdentityHandler: func(c *gin.Context) interface{} { 51 | claims := jwt.ExtractClaims(c) 52 | return &Login{ 53 | Username: claims[identityKey].(string), 54 | } 55 | }, 56 | Authenticator: func(c *gin.Context) (interface{}, error) { 57 | var ( 58 | password string 59 | loginVals Login 60 | ) 61 | if err := c.ShouldBind(&loginVals); err != nil { 62 | return "", jwt.ErrMissingLoginValues 63 | } 64 | userID := loginVals.Username 65 | pass := loginVals.Password 66 | if err != nil { 67 | return nil, err 68 | } 69 | if userID != "admin" { 70 | mysql := core.GetMysql() 71 | user := mysql.GetUserByName(userID) 72 | if user == nil { 73 | return nil, jwt.ErrFailedAuthentication 74 | } 75 | password = user.EncryptPass 76 | } else { 77 | if password, err = core.GetValue(userID + "_pass"); err != nil { 78 | return nil, err 79 | } 80 | } 81 | if password == pass { 82 | return &loginVals, nil 83 | } 84 | return nil, jwt.ErrFailedAuthentication 85 | }, 86 | Authorizator: func(data interface{}, c *gin.Context) bool { 87 | if _, ok := data.(*Login); ok { 88 | return true 89 | } 90 | return false 91 | }, 92 | Unauthorized: func(c *gin.Context, code int, message string) { 93 | c.JSON(code, gin.H{ 94 | "code": code, 95 | "message": message, 96 | }) 97 | }, 98 | TokenLookup: "header: Authorization, query: token, cookie: jwt", 99 | TokenHeadName: "Bearer", 100 | TimeFunc: time.Now, 101 | }) 102 | 103 | if err != nil { 104 | fmt.Println("JWT Error:" + err.Error()) 105 | } 106 | } 107 | 108 | func updateUser(c *gin.Context) { 109 | responseBody := controller.ResponseBody{Msg: "success"} 110 | defer controller.TimeCost(time.Now(), &responseBody) 111 | username := c.DefaultPostForm("username", "admin") 112 | pass := c.PostForm("password") 113 | err := core.SetValue(fmt.Sprintf("%s_pass", username), pass) 114 | if err != nil { 115 | responseBody.Msg = err.Error() 116 | } 117 | c.JSON(200, responseBody) 118 | } 119 | 120 | // RequestUsername 获取请求接口的用户名 121 | func RequestUsername(c *gin.Context) string { 122 | claims := jwt.ExtractClaims(c) 123 | return claims[identityKey].(string) 124 | } 125 | 126 | // Auth 权限router 127 | func Auth(r *gin.Engine, timeout int) *jwt.GinJWTMiddleware { 128 | jwtInit(timeout) 129 | 130 | newInstall := gin.H{"code": 201, "message": "No administrator account found inside the database", "data": nil} 131 | r.NoRoute(authMiddleware.MiddlewareFunc(), func(c *gin.Context) { 132 | claims := jwt.ExtractClaims(c) 133 | fmt.Printf("NoRoute claims: %#v\n", claims) 134 | c.JSON(404, gin.H{"code": 404, "message": "Page not found"}) 135 | }) 136 | r.GET("/auth/check", func(c *gin.Context) { 137 | result, _ := core.GetValue("admin_pass") 138 | if result == "" { 139 | c.JSON(201, newInstall) 140 | } else { 141 | title, err := core.GetValue("login_title") 142 | if err != nil { 143 | title = "trojan 管理平台" 144 | } 145 | c.JSON(200, gin.H{ 146 | "code": 200, 147 | "message": "success", 148 | "data": map[string]string{ 149 | "title": title, 150 | }, 151 | }) 152 | } 153 | }) 154 | r.POST("/auth/login", authMiddleware.LoginHandler) 155 | r.POST("/auth/register", updateUser) 156 | authO := r.Group("/auth") 157 | authO.Use(authMiddleware.MiddlewareFunc()) 158 | { 159 | authO.GET("/loginUser", func(c *gin.Context) { 160 | result, _ := core.GetValue("admin_pass") 161 | if result == "" { 162 | c.JSON(201, newInstall) 163 | } else { 164 | c.JSON(200, gin.H{ 165 | "code": 200, 166 | "message": "success", 167 | "data": map[string]string{ 168 | "username": RequestUsername(c), 169 | }, 170 | }) 171 | } 172 | }) 173 | authO.POST("/reset_pass", updateUser) 174 | authO.POST("/logout", authMiddleware.LogoutHandler) 175 | authO.POST("/refresh_token", authMiddleware.RefreshHandler) 176 | } 177 | return authMiddleware 178 | } 179 | -------------------------------------------------------------------------------- /web/controller/common.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "github.com/robfig/cron/v3" 5 | "github.com/shirou/gopsutil/cpu" 6 | "github.com/shirou/gopsutil/disk" 7 | "github.com/shirou/gopsutil/load" 8 | "github.com/shirou/gopsutil/mem" 9 | "github.com/shirou/gopsutil/net" 10 | "time" 11 | "trojan/asset" 12 | "trojan/core" 13 | "trojan/trojan" 14 | ) 15 | 16 | // ResponseBody 结构体 17 | type ResponseBody struct { 18 | Duration string 19 | Data interface{} 20 | Msg string 21 | } 22 | 23 | type speedInfo struct { 24 | Up uint64 25 | Down uint64 26 | } 27 | 28 | var si *speedInfo 29 | 30 | // TimeCost web函数执行用时统计方法 31 | func TimeCost(start time.Time, body *ResponseBody) { 32 | body.Duration = time.Since(start).String() 33 | } 34 | 35 | func clashRules() string { 36 | rules, _ := core.GetValue("clash-rules") 37 | if rules == "" { 38 | rules = string(asset.GetAsset("clash-rules.yaml")) 39 | } 40 | return rules 41 | } 42 | 43 | // Version 获取版本信息 44 | func Version() *ResponseBody { 45 | responseBody := ResponseBody{Msg: "success"} 46 | defer TimeCost(time.Now(), &responseBody) 47 | responseBody.Data = map[string]string{ 48 | "version": trojan.MVersion, 49 | "buildDate": trojan.BuildDate, 50 | "goVersion": trojan.GoVersion, 51 | "gitVersion": trojan.GitVersion, 52 | "trojanVersion": trojan.Version(), 53 | "trojanUptime": trojan.UpTime(), 54 | "trojanType": trojan.Type(), 55 | } 56 | return &responseBody 57 | } 58 | 59 | // SetLoginInfo 设置登录页信息 60 | func SetLoginInfo(title string) *ResponseBody { 61 | responseBody := ResponseBody{Msg: "success"} 62 | defer TimeCost(time.Now(), &responseBody) 63 | err := core.SetValue("login_title", title) 64 | if err != nil { 65 | responseBody.Msg = err.Error() 66 | } 67 | return &responseBody 68 | } 69 | 70 | // SetDomain 设置域名 71 | func SetDomain(domain string) *ResponseBody { 72 | responseBody := ResponseBody{Msg: "success"} 73 | defer TimeCost(time.Now(), &responseBody) 74 | trojan.SetDomain(domain) 75 | return &responseBody 76 | } 77 | 78 | // SetClashRules 设置clash规则 79 | func SetClashRules(rules string) *ResponseBody { 80 | responseBody := ResponseBody{Msg: "success"} 81 | defer TimeCost(time.Now(), &responseBody) 82 | core.SetValue("clash-rules", rules) 83 | return &responseBody 84 | } 85 | 86 | // ResetClashRules 重置clash规则 87 | func ResetClashRules() *ResponseBody { 88 | responseBody := ResponseBody{Msg: "success"} 89 | defer TimeCost(time.Now(), &responseBody) 90 | core.DelValue("clash-rules") 91 | responseBody.Data = clashRules() 92 | return &responseBody 93 | } 94 | 95 | // GetClashRules 获取clash规则 96 | func GetClashRules() *ResponseBody { 97 | responseBody := ResponseBody{Msg: "success"} 98 | defer TimeCost(time.Now(), &responseBody) 99 | responseBody.Data = clashRules() 100 | return &responseBody 101 | } 102 | 103 | // SetTrojanType 设置trojan类型 104 | func SetTrojanType(tType string) *ResponseBody { 105 | responseBody := ResponseBody{Msg: "success"} 106 | defer TimeCost(time.Now(), &responseBody) 107 | err := trojan.SwitchType(tType) 108 | if err != nil { 109 | responseBody.Msg = err.Error() 110 | } 111 | return &responseBody 112 | } 113 | 114 | // CollectTask 启动收集主机信息任务 115 | func CollectTask() { 116 | var recvCount, sentCount uint64 117 | c := cron.New() 118 | lastIO, _ := net.IOCounters(true) 119 | var lastRecvCount, lastSentCount uint64 120 | for _, k := range lastIO { 121 | lastRecvCount = lastRecvCount + k.BytesRecv 122 | lastSentCount = lastSentCount + k.BytesSent 123 | } 124 | si = &speedInfo{} 125 | c.AddFunc("@every 2s", func() { 126 | result, _ := net.IOCounters(true) 127 | recvCount, sentCount = 0, 0 128 | for _, k := range result { 129 | recvCount = recvCount + k.BytesRecv 130 | sentCount = sentCount + k.BytesSent 131 | } 132 | si.Up = (sentCount - lastSentCount) / 2 133 | si.Down = (recvCount - lastRecvCount) / 2 134 | lastSentCount = sentCount 135 | lastRecvCount = recvCount 136 | lastIO = result 137 | }) 138 | c.Start() 139 | } 140 | 141 | // ServerInfo 获取服务器信息 142 | func ServerInfo() *ResponseBody { 143 | responseBody := ResponseBody{Msg: "success"} 144 | defer TimeCost(time.Now(), &responseBody) 145 | cpuPercent, _ := cpu.Percent(0, false) 146 | vmInfo, _ := mem.VirtualMemory() 147 | smInfo, _ := mem.SwapMemory() 148 | diskInfo, _ := disk.Usage("/") 149 | loadInfo, _ := load.Avg() 150 | tcpCon, _ := net.Connections("tcp") 151 | udpCon, _ := net.Connections("udp") 152 | netCount := map[string]int{ 153 | "tcp": len(tcpCon), 154 | "udp": len(udpCon), 155 | } 156 | responseBody.Data = map[string]interface{}{ 157 | "cpu": cpuPercent, 158 | "memory": vmInfo, 159 | "swap": smInfo, 160 | "disk": diskInfo, 161 | "load": loadInfo, 162 | "speed": si, 163 | "netCount": netCount, 164 | } 165 | return &responseBody 166 | } 167 | -------------------------------------------------------------------------------- /web/controller/data.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "fmt" 5 | "github.com/robfig/cron/v3" 6 | "strconv" 7 | "time" 8 | "trojan/core" 9 | "trojan/trojan" 10 | ) 11 | 12 | var c *cron.Cron 13 | 14 | // SetData 设置流量限制 15 | func SetData(id uint, quota int) *ResponseBody { 16 | responseBody := ResponseBody{Msg: "success"} 17 | defer TimeCost(time.Now(), &responseBody) 18 | mysql := core.GetMysql() 19 | if err := mysql.SetQuota(id, quota); err != nil { 20 | responseBody.Msg = err.Error() 21 | } 22 | return &responseBody 23 | } 24 | 25 | // CleanData 清空流量 26 | func CleanData(id uint) *ResponseBody { 27 | responseBody := ResponseBody{Msg: "success"} 28 | defer TimeCost(time.Now(), &responseBody) 29 | mysql := core.GetMysql() 30 | if err := mysql.CleanData(id); err != nil { 31 | responseBody.Msg = err.Error() 32 | } 33 | return &responseBody 34 | } 35 | 36 | func monthlyResetJob() { 37 | mysql := core.GetMysql() 38 | if err := mysql.MonthlyResetData(); err != nil { 39 | fmt.Println("MonthlyResetError: " + err.Error()) 40 | } 41 | } 42 | 43 | // GetResetDay 获取重置日 44 | func GetResetDay() *ResponseBody { 45 | responseBody := ResponseBody{Msg: "success"} 46 | defer TimeCost(time.Now(), &responseBody) 47 | dayStr, _ := core.GetValue("reset_day") 48 | day, _ := strconv.Atoi(dayStr) 49 | responseBody.Data = map[string]interface{}{ 50 | "resetDay": day, 51 | } 52 | return &responseBody 53 | } 54 | 55 | // UpdateResetDay 更新重置流量日 56 | func UpdateResetDay(day uint) *ResponseBody { 57 | responseBody := ResponseBody{Msg: "success"} 58 | defer TimeCost(time.Now(), &responseBody) 59 | if day > 31 || day < 0 { 60 | responseBody.Msg = fmt.Sprintf("%d为非正常日期", day) 61 | return &responseBody 62 | } 63 | dayStr, _ := core.GetValue("reset_day") 64 | oldDay, _ := strconv.Atoi(dayStr) 65 | if day == uint(oldDay) { 66 | return &responseBody 67 | } 68 | if len(c.Entries()) > 1 { 69 | c.Remove(c.Entries()[len(c.Entries())-1].ID) 70 | } 71 | if day != 0 { 72 | c.AddFunc(fmt.Sprintf("0 0 %d * *", day), func() { 73 | monthlyResetJob() 74 | }) 75 | } 76 | core.SetValue("reset_day", strconv.Itoa(int(day))) 77 | return &responseBody 78 | } 79 | 80 | // ScheduleTask 定时任务 81 | func ScheduleTask() { 82 | loc, _ := time.LoadLocation("Asia/Shanghai") 83 | c = cron.New(cron.WithLocation(loc)) 84 | c.AddFunc("@daily", func() { 85 | mysql := core.GetMysql() 86 | if needRestart, err := mysql.DailyCheckExpire(); err != nil { 87 | fmt.Println("DailyCheckError: " + err.Error()) 88 | } else if needRestart { 89 | trojan.Restart() 90 | } 91 | }) 92 | 93 | dayStr, _ := core.GetValue("reset_day") 94 | if dayStr == "" { 95 | dayStr = "1" 96 | core.SetValue("reset_day", dayStr) 97 | } 98 | day, _ := strconv.Atoi(dayStr) 99 | if day != 0 { 100 | c.AddFunc(fmt.Sprintf("0 0 %d * *", day), func() { 101 | monthlyResetJob() 102 | }) 103 | } 104 | c.Start() 105 | } 106 | -------------------------------------------------------------------------------- /web/controller/trojan.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/csv" 7 | "fmt" 8 | "github.com/gin-gonic/gin" 9 | ws "github.com/gorilla/websocket" 10 | "io" 11 | "strconv" 12 | "strings" 13 | "time" 14 | "trojan/core" 15 | "trojan/trojan" 16 | "trojan/util" 17 | ) 18 | 19 | // Start 启动trojan 20 | func Start() *ResponseBody { 21 | responseBody := ResponseBody{Msg: "success"} 22 | defer TimeCost(time.Now(), &responseBody) 23 | trojan.Start() 24 | return &responseBody 25 | } 26 | 27 | // Stop 停止trojan 28 | func Stop() *ResponseBody { 29 | responseBody := ResponseBody{Msg: "success"} 30 | defer TimeCost(time.Now(), &responseBody) 31 | trojan.Stop() 32 | return &responseBody 33 | } 34 | 35 | // Restart 重启trojan 36 | func Restart() *ResponseBody { 37 | responseBody := ResponseBody{Msg: "success"} 38 | defer TimeCost(time.Now(), &responseBody) 39 | trojan.Restart() 40 | return &responseBody 41 | } 42 | 43 | // Update trojan更新 44 | func Update() *ResponseBody { 45 | responseBody := ResponseBody{Msg: "success"} 46 | defer TimeCost(time.Now(), &responseBody) 47 | trojan.InstallTrojan("") 48 | return &responseBody 49 | } 50 | 51 | // SetLogLevel 修改trojan日志等级 52 | func SetLogLevel(level int) *ResponseBody { 53 | responseBody := ResponseBody{Msg: "success"} 54 | defer TimeCost(time.Now(), &responseBody) 55 | core.WriteLogLevel(level) 56 | trojan.Restart() 57 | return &responseBody 58 | } 59 | 60 | // GetLogLevel 获取trojan日志等级 61 | func GetLogLevel() *ResponseBody { 62 | responseBody := ResponseBody{Msg: "success"} 63 | defer TimeCost(time.Now(), &responseBody) 64 | config := core.GetConfig() 65 | responseBody.Data = map[string]interface{}{ 66 | "loglevel": &config.LogLevel, 67 | } 68 | return &responseBody 69 | } 70 | 71 | // Log 通过ws查看trojan实时日志 72 | func Log(c *gin.Context) { 73 | var ( 74 | wsConn *util.WsConnection 75 | err error 76 | ) 77 | if wsConn, err = util.InitWebsocket(c.Writer, c.Request); err != nil { 78 | fmt.Println(err) 79 | return 80 | } 81 | defer wsConn.WsClose() 82 | param := c.DefaultQuery("line", "300") 83 | if !util.IsInteger(param) { 84 | fmt.Println("invalid param: " + param) 85 | return 86 | } 87 | if param == "-1" { 88 | param = "--no-tail" 89 | } else { 90 | param = "-n " + param 91 | } 92 | result, err := util.LogChan("trojan", param, wsConn.CloseChan) 93 | if err != nil { 94 | fmt.Println(err) 95 | return 96 | } 97 | for line := range result { 98 | if err := wsConn.WsWrite(ws.TextMessage, []byte(line+"\n")); err != nil { 99 | fmt.Println("can't send: ", line) 100 | break 101 | } 102 | } 103 | } 104 | 105 | // ImportCsv 导入csv文件到trojan数据库 106 | func ImportCsv(c *gin.Context) *ResponseBody { 107 | responseBody := ResponseBody{Msg: "success"} 108 | defer TimeCost(time.Now(), &responseBody) 109 | 110 | file, header, err := c.Request.FormFile("file") 111 | if err != nil { 112 | responseBody.Msg = err.Error() 113 | return &responseBody 114 | } 115 | defer file.Close() 116 | filename := header.Filename 117 | if !strings.Contains(filename, ".csv") { 118 | responseBody.Msg = "仅支持导入csv格式的文件" 119 | return &responseBody 120 | } 121 | reader := csv.NewReader(bufio.NewReader(file)) 122 | var userList []*core.User 123 | for { 124 | line, readErr := reader.Read() 125 | if readErr == io.EOF { 126 | break 127 | } else if readErr != nil { 128 | responseBody.Msg = readErr.Error() 129 | return &responseBody 130 | } 131 | quota, _ := strconv.Atoi(line[4]) 132 | download, _ := strconv.Atoi(line[5]) 133 | upload, _ := strconv.Atoi(line[6]) 134 | useDays, _ := strconv.Atoi(line[7]) 135 | userList = append(userList, &core.User{ 136 | Username: line[1], 137 | Password: line[2], 138 | EncryptPass: line[3], 139 | Quota: int64(quota), 140 | Download: uint64(download), 141 | Upload: uint64(upload), 142 | UseDays: uint(useDays), 143 | ExpiryDate: line[8], 144 | }) 145 | } 146 | mysql := core.GetMysql() 147 | db := mysql.GetDB() 148 | if _, err = db.Exec("DROP TABLE IF EXISTS users;"); err != nil { 149 | responseBody.Msg = err.Error() 150 | return &responseBody 151 | } 152 | if _, err = db.Exec(core.CreateTableSql); err != nil { 153 | responseBody.Msg = err.Error() 154 | return &responseBody 155 | } 156 | for _, user := range userList { 157 | if _, err = db.Exec(fmt.Sprintf(` 158 | INSERT INTO users(username, password, passwordShow, quota, download, upload, useDays, expiryDate) VALUES ('%s','%s','%s', %d, %d, %d, %d, '%s');`, 159 | user.Username, user.EncryptPass, user.Password, user.Quota, user.Download, user.Upload, user.UseDays, user.ExpiryDate)); err != nil { 160 | responseBody.Msg = err.Error() 161 | return &responseBody 162 | } 163 | } 164 | return &responseBody 165 | } 166 | 167 | // ExportCsv 导出trojan表数据到csv文件 168 | func ExportCsv(c *gin.Context) *ResponseBody { 169 | responseBody := ResponseBody{Msg: "success"} 170 | defer TimeCost(time.Now(), &responseBody) 171 | var dataBytes = new(bytes.Buffer) 172 | //设置UTF-8 BOM, 防止中文乱码 173 | dataBytes.WriteString("\xEF\xBB\xBF") 174 | mysql := core.GetMysql() 175 | userList, err := mysql.GetData() 176 | if err != nil { 177 | responseBody.Msg = err.Error() 178 | return &responseBody 179 | } 180 | wr := csv.NewWriter(dataBytes) 181 | for _, user := range userList { 182 | singleUser := []string{ 183 | strconv.Itoa(int(user.ID)), 184 | user.Username, 185 | user.Password, 186 | user.EncryptPass, 187 | strconv.Itoa(int(user.Quota)), 188 | strconv.Itoa(int(user.Download)), 189 | strconv.Itoa(int(user.Upload)), 190 | strconv.Itoa(int(user.UseDays)), 191 | user.ExpiryDate, 192 | } 193 | wr.Write(singleUser) 194 | } 195 | wr.Flush() 196 | c.Writer.Header().Set("Content-type", "application/octet-stream") 197 | c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", fmt.Sprintf("%s.csv", mysql.Database))) 198 | c.String(200, dataBytes.String()) 199 | return nil 200 | } 201 | -------------------------------------------------------------------------------- /web/controller/user.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "encoding/base64" 5 | "fmt" 6 | "github.com/gin-gonic/gin" 7 | "github.com/tidwall/gjson" 8 | "strconv" 9 | "time" 10 | "trojan/core" 11 | "trojan/trojan" 12 | ) 13 | 14 | // UserList 获取用户列表 15 | func UserList(requestUser string) *ResponseBody { 16 | responseBody := ResponseBody{Msg: "success"} 17 | defer TimeCost(time.Now(), &responseBody) 18 | mysql := core.GetMysql() 19 | userList, err := mysql.GetData() 20 | if err != nil { 21 | responseBody.Msg = err.Error() 22 | return &responseBody 23 | } 24 | if requestUser != "admin" { 25 | findUser := false 26 | for _, user := range userList { 27 | if user.Username == requestUser { 28 | userList = []*core.User{user} 29 | findUser = true 30 | break 31 | } 32 | } 33 | if !findUser { 34 | userList = []*core.User{} 35 | } 36 | } 37 | domain, port := trojan.GetDomainAndPort() 38 | responseBody.Data = map[string]interface{}{ 39 | "domain": domain, 40 | "port": port, 41 | "userList": userList, 42 | } 43 | return &responseBody 44 | } 45 | 46 | // PageUserList 分页查询获取用户列表 47 | func PageUserList(curPage int, pageSize int) *ResponseBody { 48 | responseBody := ResponseBody{Msg: "success"} 49 | defer TimeCost(time.Now(), &responseBody) 50 | mysql := core.GetMysql() 51 | pageData, err := mysql.PageList(curPage, pageSize) 52 | if err != nil { 53 | responseBody.Msg = err.Error() 54 | return &responseBody 55 | } 56 | domain, port := trojan.GetDomainAndPort() 57 | responseBody.Data = map[string]interface{}{ 58 | "domain": domain, 59 | "port": port, 60 | "pageData": pageData, 61 | } 62 | return &responseBody 63 | } 64 | 65 | // CreateUser 创建用户 66 | func CreateUser(username string, password string) *ResponseBody { 67 | responseBody := ResponseBody{Msg: "success"} 68 | defer TimeCost(time.Now(), &responseBody) 69 | if username == "admin" { 70 | responseBody.Msg = "不能创建用户名为admin的用户!" 71 | return &responseBody 72 | } 73 | mysql := core.GetMysql() 74 | if user := mysql.GetUserByName(username); user != nil { 75 | responseBody.Msg = "已存在用户名为: " + username + " 的用户!" 76 | return &responseBody 77 | } 78 | pass, err := base64.StdEncoding.DecodeString(password) 79 | if err != nil { 80 | responseBody.Msg = "Base64解码失败: " + err.Error() 81 | return &responseBody 82 | } 83 | if user := mysql.GetUserByPass(password); user != nil { 84 | responseBody.Msg = "已存在密码为: " + string(pass) + " 的用户!" 85 | return &responseBody 86 | } 87 | if err := mysql.CreateUser(username, password, string(pass)); err != nil { 88 | responseBody.Msg = err.Error() 89 | } 90 | return &responseBody 91 | } 92 | 93 | // UpdateUser 更新用户 94 | func UpdateUser(id uint, username string, password string) *ResponseBody { 95 | responseBody := ResponseBody{Msg: "success"} 96 | defer TimeCost(time.Now(), &responseBody) 97 | if username == "admin" { 98 | responseBody.Msg = "不能更改用户名为admin的用户!" 99 | return &responseBody 100 | } 101 | mysql := core.GetMysql() 102 | userList, err := mysql.GetData(strconv.Itoa(int(id))) 103 | if err != nil { 104 | responseBody.Msg = err.Error() 105 | return &responseBody 106 | } 107 | if userList[0].Username != username { 108 | if user := mysql.GetUserByName(username); user != nil { 109 | responseBody.Msg = "已存在用户名为: " + username + " 的用户!" 110 | return &responseBody 111 | } 112 | } 113 | pass, err := base64.StdEncoding.DecodeString(password) 114 | if err != nil { 115 | responseBody.Msg = "Base64解码失败: " + err.Error() 116 | return &responseBody 117 | } 118 | if userList[0].Password != password { 119 | if user := mysql.GetUserByPass(password); user != nil { 120 | responseBody.Msg = "已存在密码为: " + string(pass) + " 的用户!" 121 | return &responseBody 122 | } 123 | } 124 | if err := mysql.UpdateUser(id, username, password, string(pass)); err != nil { 125 | responseBody.Msg = err.Error() 126 | } 127 | return &responseBody 128 | } 129 | 130 | // DelUser 删除用户 131 | func DelUser(id uint) *ResponseBody { 132 | responseBody := ResponseBody{Msg: "success"} 133 | defer TimeCost(time.Now(), &responseBody) 134 | mysql := core.GetMysql() 135 | if err := mysql.DeleteUser(id); err != nil { 136 | responseBody.Msg = err.Error() 137 | } else { 138 | trojan.Restart() 139 | } 140 | return &responseBody 141 | } 142 | 143 | // SetExpire 设置用户过期 144 | func SetExpire(id uint, useDays uint) *ResponseBody { 145 | responseBody := ResponseBody{Msg: "success"} 146 | defer TimeCost(time.Now(), &responseBody) 147 | mysql := core.GetMysql() 148 | if err := mysql.SetExpire(id, useDays); err != nil { 149 | responseBody.Msg = err.Error() 150 | } 151 | return &responseBody 152 | } 153 | 154 | // CancelExpire 取消设置用户过期 155 | func CancelExpire(id uint) *ResponseBody { 156 | responseBody := ResponseBody{Msg: "success"} 157 | defer TimeCost(time.Now(), &responseBody) 158 | mysql := core.GetMysql() 159 | if err := mysql.CancelExpire(id); err != nil { 160 | responseBody.Msg = err.Error() 161 | } 162 | return &responseBody 163 | } 164 | 165 | // ClashSubInfo 获取clash订阅信息 166 | func ClashSubInfo(c *gin.Context) { 167 | token := c.Query("token") 168 | if token == "" { 169 | c.String(200, "token is null") 170 | return 171 | } 172 | decodeByte, err := base64.StdEncoding.DecodeString(token) 173 | if err != nil { 174 | c.String(200, "token is error") 175 | return 176 | } 177 | if !gjson.GetBytes(decodeByte, "user").Exists() || !gjson.GetBytes(decodeByte, "pass").Exists() { 178 | c.String(200, "token is error") 179 | return 180 | } 181 | username := gjson.GetBytes(decodeByte, "user").String() 182 | password := gjson.GetBytes(decodeByte, "pass").String() 183 | 184 | mysql := core.GetMysql() 185 | user := mysql.GetUserByName(username) 186 | if user != nil { 187 | pass, _ := base64.StdEncoding.DecodeString(user.Password) 188 | if password == string(pass) { 189 | var wsData, wsHost string 190 | userInfo := fmt.Sprintf("upload=%d, download=%d", user.Upload, user.Download) 191 | if user.Quota != -1 { 192 | userInfo = fmt.Sprintf("%s, total=%d", userInfo, user.Quota) 193 | } 194 | if user.ExpiryDate != "" { 195 | utc, _ := time.LoadLocation("Asia/Shanghai") 196 | t, _ := time.ParseInLocation("2006-01-02", user.ExpiryDate, utc) 197 | userInfo = fmt.Sprintf("%s, expire=%d", userInfo, t.Unix()) 198 | } 199 | c.Header("content-disposition", fmt.Sprintf("attachment; filename=%s", user.Username)) 200 | c.Header("subscription-userinfo", userInfo) 201 | 202 | domain, port := trojan.GetDomainAndPort() 203 | name := fmt.Sprintf("%s:%d", domain, port) 204 | configData := string(core.Load("")) 205 | if gjson.Get(configData, "websocket").Exists() && gjson.Get(configData, "websocket.enabled").Bool() { 206 | if gjson.Get(configData, "websocket.host").Exists() { 207 | hostTemp := gjson.Get(configData, "websocket.host").String() 208 | if hostTemp != "" { 209 | wsHost = fmt.Sprintf(", headers: {Host: %s}", hostTemp) 210 | } 211 | } 212 | wsOpt := fmt.Sprintf("{path: %s%s}", gjson.Get(configData, "websocket.path").String(), wsHost) 213 | wsData = fmt.Sprintf(", network: ws, udp: true, ws-opts: %s", wsOpt) 214 | } 215 | proxyData := fmt.Sprintf(" - {name: %s, server: %s, port: %d, type: trojan, password: %s, sni: %s%s}", 216 | name, domain, port, password, domain, wsData) 217 | result := fmt.Sprintf(`proxies: 218 | %s 219 | 220 | proxy-groups: 221 | - name: PROXY 222 | type: select 223 | proxies: 224 | - %s 225 | 226 | %s 227 | `, proxyData, name, clashRules()) 228 | c.String(200, result) 229 | return 230 | } 231 | } 232 | c.String(200, "token is error") 233 | } 234 | -------------------------------------------------------------------------------- /web/web.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "embed" 5 | "fmt" 6 | "github.com/gin-contrib/gzip" 7 | "github.com/gin-gonic/gin" 8 | "io/fs" 9 | "net/http" 10 | "strconv" 11 | "trojan/core" 12 | "trojan/util" 13 | "trojan/web/controller" 14 | ) 15 | 16 | //go:embed templates/* 17 | var f embed.FS 18 | 19 | func userRouter(router *gin.Engine) { 20 | user := router.Group("/trojan/user") 21 | { 22 | user.GET("", func(c *gin.Context) { 23 | requestUser := RequestUsername(c) 24 | c.JSON(200, controller.UserList(requestUser)) 25 | }) 26 | user.GET("/page", func(c *gin.Context) { 27 | curPageStr := c.DefaultQuery("curPage", "1") 28 | pageSizeStr := c.DefaultQuery("pageSize", "10") 29 | curPage, _ := strconv.Atoi(curPageStr) 30 | pageSize, _ := strconv.Atoi(pageSizeStr) 31 | c.JSON(200, controller.PageUserList(curPage, pageSize)) 32 | }) 33 | user.POST("", func(c *gin.Context) { 34 | username := c.PostForm("username") 35 | password := c.PostForm("password") 36 | c.JSON(200, controller.CreateUser(username, password)) 37 | }) 38 | user.POST("/update", func(c *gin.Context) { 39 | sid := c.PostForm("id") 40 | username := c.PostForm("username") 41 | password := c.PostForm("password") 42 | id, _ := strconv.Atoi(sid) 43 | c.JSON(200, controller.UpdateUser(uint(id), username, password)) 44 | }) 45 | user.POST("/expire", func(c *gin.Context) { 46 | sid := c.PostForm("id") 47 | sDays := c.PostForm("useDays") 48 | id, _ := strconv.Atoi(sid) 49 | useDays, _ := strconv.Atoi(sDays) 50 | c.JSON(200, controller.SetExpire(uint(id), uint(useDays))) 51 | }) 52 | user.DELETE("/expire", func(c *gin.Context) { 53 | sid := c.Query("id") 54 | id, _ := strconv.Atoi(sid) 55 | c.JSON(200, controller.CancelExpire(uint(id))) 56 | }) 57 | user.DELETE("", func(c *gin.Context) { 58 | stringId := c.Query("id") 59 | id, _ := strconv.Atoi(stringId) 60 | c.JSON(200, controller.DelUser(uint(id))) 61 | }) 62 | } 63 | } 64 | 65 | func trojanRouter(router *gin.Engine) { 66 | router.POST("/trojan/start", func(c *gin.Context) { 67 | c.JSON(200, controller.Start()) 68 | }) 69 | router.POST("/trojan/stop", func(c *gin.Context) { 70 | c.JSON(200, controller.Stop()) 71 | }) 72 | router.POST("/trojan/restart", func(c *gin.Context) { 73 | c.JSON(200, controller.Restart()) 74 | }) 75 | router.GET("/trojan/loglevel", func(c *gin.Context) { 76 | c.JSON(200, controller.GetLogLevel()) 77 | }) 78 | router.GET("/trojan/export", func(c *gin.Context) { 79 | result := controller.ExportCsv(c) 80 | if result != nil { 81 | c.JSON(200, result) 82 | } 83 | }) 84 | router.POST("/trojan/import", func(c *gin.Context) { 85 | c.JSON(200, controller.ImportCsv(c)) 86 | }) 87 | router.POST("/trojan/update", func(c *gin.Context) { 88 | c.JSON(200, controller.Update()) 89 | }) 90 | router.POST("/trojan/switch", func(c *gin.Context) { 91 | tType := c.DefaultPostForm("type", "trojan") 92 | c.JSON(200, controller.SetTrojanType(tType)) 93 | }) 94 | router.POST("/trojan/loglevel", func(c *gin.Context) { 95 | slevel := c.DefaultPostForm("level", "1") 96 | level, _ := strconv.Atoi(slevel) 97 | c.JSON(200, controller.SetLogLevel(level)) 98 | }) 99 | router.POST("/trojan/domain", func(c *gin.Context) { 100 | c.JSON(200, controller.SetDomain(c.PostForm("domain"))) 101 | }) 102 | router.GET("/trojan/log", func(c *gin.Context) { 103 | controller.Log(c) 104 | }) 105 | } 106 | 107 | func dataRouter(router *gin.Engine) { 108 | data := router.Group("/trojan/data") 109 | { 110 | data.POST("", func(c *gin.Context) { 111 | sID := c.PostForm("id") 112 | sQuota := c.PostForm("quota") 113 | id, _ := strconv.Atoi(sID) 114 | quota, _ := strconv.Atoi(sQuota) 115 | c.JSON(200, controller.SetData(uint(id), quota)) 116 | }) 117 | data.DELETE("", func(c *gin.Context) { 118 | sID := c.Query("id") 119 | id, _ := strconv.Atoi(sID) 120 | c.JSON(200, controller.CleanData(uint(id))) 121 | }) 122 | data.POST("/resetDay", func(c *gin.Context) { 123 | dayStr := c.DefaultPostForm("day", "1") 124 | day, _ := strconv.Atoi(dayStr) 125 | c.JSON(200, controller.UpdateResetDay(uint(day))) 126 | }) 127 | data.GET("/resetDay", func(c *gin.Context) { 128 | c.JSON(200, controller.GetResetDay()) 129 | }) 130 | } 131 | } 132 | 133 | func commonRouter(router *gin.Engine) { 134 | common := router.Group("/common") 135 | { 136 | common.GET("/version", func(c *gin.Context) { 137 | c.JSON(200, controller.Version()) 138 | }) 139 | common.GET("/serverInfo", func(c *gin.Context) { 140 | c.JSON(200, controller.ServerInfo()) 141 | }) 142 | common.GET("/clashRules", func(c *gin.Context) { 143 | c.JSON(200, controller.GetClashRules()) 144 | }) 145 | common.POST("/clashRules", func(c *gin.Context) { 146 | rules := c.PostForm("rules") 147 | c.JSON(200, controller.SetClashRules(rules)) 148 | }) 149 | common.DELETE("/clashRules", func(c *gin.Context) { 150 | c.JSON(200, controller.ResetClashRules()) 151 | }) 152 | common.POST("/loginInfo", func(c *gin.Context) { 153 | c.JSON(200, controller.SetLoginInfo(c.PostForm("title"))) 154 | }) 155 | } 156 | } 157 | 158 | func staticRouter(router *gin.Engine) { 159 | staticFs, _ := fs.Sub(f, "templates/static") 160 | router.StaticFS("/static", http.FS(staticFs)) 161 | 162 | router.GET("/", func(c *gin.Context) { 163 | indexHTML, _ := f.ReadFile("templates/" + "index.html") 164 | c.Writer.Write(indexHTML) 165 | }) 166 | } 167 | 168 | func noTokenRouter(router *gin.Engine) { 169 | router.GET("/trojan/user/subscribe", func(c *gin.Context) { 170 | controller.ClashSubInfo(c) 171 | }) 172 | } 173 | 174 | // Start web启动入口 175 | func Start(host string, port, timeout int, isSSL bool) { 176 | router := gin.Default() 177 | router.SetTrustedProxies(nil) 178 | router.Use(gzip.Gzip(gzip.DefaultCompression)) 179 | staticRouter(router) 180 | noTokenRouter(router) 181 | router.Use(Auth(router, timeout).MiddlewareFunc()) 182 | trojanRouter(router) 183 | userRouter(router) 184 | dataRouter(router) 185 | commonRouter(router) 186 | controller.ScheduleTask() 187 | controller.CollectTask() 188 | util.OpenPort(port) 189 | if isSSL { 190 | config := core.GetConfig() 191 | ssl := &config.SSl 192 | router.RunTLS(fmt.Sprintf("%s:%d", host, port), ssl.Cert, ssl.Key) 193 | } else { 194 | router.Run(fmt.Sprintf("%s:%d", host, port)) 195 | } 196 | } 197 | --------------------------------------------------------------------------------