Compare commits

...

8 Commits

Author SHA1 Message Date
102c975388 Merge branch 'staging' of https://git.fossy.my.id/bagas/tunnel-please into staging
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 4m17s
2025-12-09 23:40:06 +07:00
ad034ef681 fix: resolve random SSH disconnections caused by 'unexpected bytes remain' errors 2025-12-09 23:39:22 +07:00
a2a688fc4e Update LICENSE.md
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 3m51s
2025-12-08 16:02:51 +00:00
c951c41a9b fix: prevent race condition when channel is used before being set
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m24s
2025-12-08 22:46:10 +07:00
cb08bb7673 update: readme
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m24s
2025-12-08 21:13:16 +07:00
5d9f7aee92 Update .gitea/workflows/build.yml
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 5m26s
2025-12-08 13:35:46 +00:00
dd96c8fe75 refactor: remove magic numbers and replace with named constants
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 6m20s
2025-12-08 19:46:04 +07:00
ba5f702e36 feat: add droping conn command
All checks were successful
Docker Build and Push / build-and-push (push) Successful in 4m38s
2025-12-07 15:26:37 +07:00
10 changed files with 637 additions and 614 deletions

View File

@ -30,7 +30,7 @@ jobs:
context: .
push: true
tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnl_please:latest
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:latest
platforms: linux/amd64,linux/arm64
if: github.ref == 'refs/heads/main'
@ -40,6 +40,6 @@ jobs:
context: .
push: true
tags: |
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnl_please:staging
git.fossy.my.id/${{ secrets.DOCKER_USERNAME }}/tunnel-please:staging
platforms: linux/amd64,linux/arm64
if: github.ref == 'refs/heads/staging'

View File

@ -1,157 +1,157 @@
# Attribution-NonCommercial-NoDerivatives 4.0 International
> *Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.*
>
> ### Using Creative Commons Public Licenses
>
> Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
>
> * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
>
> * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. __Downstream recipients.__
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material, You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
# Attribution-NonCommercial-NoDerivatives 4.0 International
> *Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.*
>
> ### Using Creative Commons Public Licenses
>
> Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
>
> * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
>
> * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. __Downstream recipients.__
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material, You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only and provided You do not Share Adapted Material;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org).

106
README.md
View File

@ -1,93 +1,35 @@
# tunnel_pls
# Tunnel Please
A lightweight SSH-based tunnel server written in Go that enables secure TCP and HTTP forwarding with an interactive terminal interface for managing connections and custom subdomains.
## Features
## Getting started
- SSH interactive session with real-time command handling
- Custom subdomain management for HTTP tunnels
- Active connection control with drop functionality
- Dual protocol support: HTTP and TCP tunnels
- Real-time connection monitoring
## Requirements
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://git.fossy.my.id/bagas/tunnel_pls.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://git.fossy.my.id/bagas/tunnel_pls/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
- Go 1.18 or higher
- Valid domain name for subdomain routing
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
Contributions are welcome!
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
If you'd like to contribute to this project, please follow the workflow below:
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
1. **Fork** the repository
2. Create a new branch for your changes
3. Commit and push your updates
4. Open a **Pull Request** targeting the **`staging`** branch
5. Clearly describe your changes and the reasoning behind them
## License
For open source projects, say how it is licensed.
This project is licensed under the [Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)](https://creativecommons.org/licenses/by-nc-nd/4.0/) license.
## Author
**Bagas (fossyy)**
- Website: [fossy.my.id](https://fossy.my.id)
- GitHub: [@fossyy](https://github.com/fossyy)
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

View File

@ -11,7 +11,6 @@ import (
"regexp"
"strings"
"tunnel_pls/session"
"tunnel_pls/types"
"tunnel_pls/utils"
)
@ -30,7 +29,6 @@ type CustomWriter struct {
respMW []ResponseMiddleware
reqStartMW []RequestMiddleware
reqEndMW []RequestMiddleware
overflow []byte
}
func (cw *CustomWriter) SetInteraction(interaction Interaction) {
@ -38,14 +36,6 @@ func (cw *CustomWriter) SetInteraction(interaction Interaction) {
}
func (cw *CustomWriter) Read(p []byte) (int, error) {
if len(cw.overflow) > 0 {
n := copy(p, cw.overflow)
cw.overflow = cw.overflow[n:]
if len(cw.overflow) == 0 {
cw.overflow = nil
}
return n, nil
}
tmp := make([]byte, len(p))
read, err := cw.reader.Read(tmp)
if read == 0 && err != nil {
@ -99,12 +89,6 @@ func (cw *CustomWriter) Read(p []byte) (int, error) {
n := copy(p, combined)
if n > len(p) {
cw.overflow = make([]byte, len(combined)-n)
copy(cw.overflow, combined[n:])
log.Printf("output buffer too small (%d vs %d)", len(p), n)
}
return n, nil
}
@ -118,7 +102,7 @@ func NewCustomWriter(writer io.Writer, reader io.Reader, remoteAddr net.Addr) *C
}
}
var DELIMITER = []byte{0x0D, 0x0A, 0x0D, 0x0A} // HTTP HEADER DELIMITER `\r\n\r\n`
var DELIMITER = []byte{0x0D, 0x0A, 0x0D, 0x0A}
var requestLine = regexp.MustCompile(`^(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|TRACE|CONNECT) \S+ HTTP/\d\.\d$`)
var responseLine = regexp.MustCompile(`^HTTP/\d\.\d \d{3} .+`)
@ -143,8 +127,8 @@ func isHTTPHeader(buf []byte) bool {
}
func (cw *CustomWriter) Write(p []byte) (int, error) {
if len(p) == len(types.BadGatewayResponse) && bytes.Equal(p, types.BadGatewayResponse) {
return cw.writer.Write(p)
if cw.respHeader != nil && len(cw.buf) == 0 && len(p) >= 5 && string(p[0:5]) == "HTTP/" {
cw.respHeader = nil
}
if cw.respHeader != nil {
@ -166,9 +150,12 @@ func (cw *CustomWriter) Write(p []byte) (int, error) {
body := cw.buf[idx+len(DELIMITER):]
if !isHTTPHeader(header) {
n, err := cw.writer.Write(cw.buf)
_, err := cw.writer.Write(cw.buf)
cw.buf = nil
return n, err
if err != nil {
return 0, err
}
return len(p), nil
}
resphf := NewResponseHeaderFactory(header)
@ -323,20 +310,12 @@ func forwardRequest(cw *CustomWriter, initialRequest *RequestHeaderFactory, sshS
}
}
}()
_, err = channel.Write(initialRequest.Finalize())
if err != nil {
log.Printf("Failed to forward request: %v", err)
return
}
//TODO: Implement wrapper func buat add/remove middleware
fingerprintMiddleware := NewTunnelFingerprint()
loggerMiddleware := NewRequestLogger(cw.interaction, cw.RemoteAddr)
forwardedForMiddleware := NewForwardedFor(cw.RemoteAddr)
cw.respMW = append(cw.respMW, fingerprintMiddleware)
cw.reqStartMW = append(cw.reqStartMW, loggerMiddleware)
cw.reqStartMW = append(cw.reqStartMW, forwardedForMiddleware)
//TODO: Tambah req Middleware
cw.reqEndMW = nil
cw.reqHeader = initialRequest
@ -348,6 +327,12 @@ func forwardRequest(cw *CustomWriter, initialRequest *RequestHeaderFactory, sshS
}
}
_, err = channel.Write(initialRequest.Finalize())
if err != nil {
log.Printf("Failed to forward request: %v", err)
return
}
sshSession.Forwarder.HandleConnection(cw, channel, cw.RemoteAddr)
return
}

View File

@ -1,9 +1,7 @@
package server
import (
"fmt"
"net"
"time"
)
type RequestMiddleware interface {
@ -30,18 +28,6 @@ type RequestLogger struct {
remoteAddr net.Addr
}
func NewRequestLogger(interaction Interaction, remoteAddr net.Addr) *RequestLogger {
return &RequestLogger{
interaction: interaction,
remoteAddr: remoteAddr,
}
}
func (rl *RequestLogger) HandleRequest(header *RequestHeaderFactory) error {
rl.interaction.SendMessage(fmt.Sprintf("\033[32m%s %s -> %s %s \033[0m\r\n", time.Now().UTC().Format(time.RFC3339), rl.remoteAddr.String(), header.Method, header.Path))
return nil
}
type ForwardedFor struct {
addr net.Addr
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
@ -15,11 +16,12 @@ import (
)
type Forwarder struct {
Listener net.Listener
TunnelType types.TunnelType
ForwardedPort uint16
SlugManager slug.Manager
Lifecycle Lifecycle
Listener net.Listener
TunnelType types.TunnelType
ForwardedPort uint16
SlugManager slug.Manager
Lifecycle Lifecycle
ActiveForwarder []chan struct{}
}
type Lifecycle interface {
@ -39,6 +41,27 @@ type ForwardingController interface {
SetLifecycle(lifecycle Lifecycle)
CreateForwardedTCPIPPayload(origin net.Addr) []byte
WriteBadGatewayResponse(dst io.Writer)
AddActiveForwarder(drop chan struct{})
DropAllForwarder() int
GetForwarderCount() int
}
func (f *Forwarder) AddActiveForwarder(drop chan struct{}) {
f.ActiveForwarder = append(f.ActiveForwarder, drop)
}
func (f *Forwarder) DropAllForwarder() int {
total := 0
for _, d := range f.ActiveForwarder {
close(d)
total += 1
}
f.ActiveForwarder = nil
return total
}
func (f *Forwarder) GetForwarderCount() int {
return len(f.ActiveForwarder)
}
func (f *Forwarder) SetLifecycle(lifecycle Lifecycle) {
@ -76,6 +99,7 @@ func (f *Forwarder) AcceptTCPConnections() {
}
func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteAddr net.Addr) {
drop := make(chan struct{})
defer func(src ssh.Channel) {
_, err := io.Copy(io.Discard, src)
if err != nil {
@ -96,6 +120,16 @@ func (f *Forwarder) HandleConnection(dst io.ReadWriter, src ssh.Channel, remoteA
}
}()
go func() {
select {
case <-drop:
fmt.Println("Closinggggg")
return
}
}()
f.AddActiveForwarder(drop)
_, err := io.Copy(dst, src)
if err != nil && !errors.Is(err, io.EOF) {

View File

@ -0,0 +1,27 @@
package interaction
const (
backspaceChar = 8
deleteChar = 127
enterChar = 13
escapeChar = 27
ctrlC = 3
forwardSlash = '/'
minPrintableChar = 32
maxPrintableChar = 126
minSlugLength = 3
maxSlugLength = 20
clearScreen = "\033[H\033[2J"
clearLine = "\033[K"
clearToLineEnd = "\r\033[K"
backspaceSeq = "\b \b"
minBoxWidth = 50
paddingRight = 4
)
var forbiddenSlugs = []string{
"ping",
}

View File

@ -14,10 +14,6 @@ import (
"golang.org/x/crypto/ssh"
)
var forbiddenSlug = []string{
"ping",
}
type Lifecycle interface {
Close() error
}
@ -26,27 +22,32 @@ type Controller interface {
SendMessage(message string)
HandleUserInput()
HandleCommand(command string)
HandleSlugEditMode(connection ssh.Channel, char byte)
HandleSlugSave(conn ssh.Channel)
HandleSlugCancel(connection ssh.Channel)
HandleSlugEditMode(char byte)
HandleSlugSave()
HandleSlugCancel()
HandleSlugUpdateError()
ShowWelcomeMessage()
DisplaySlugEditor()
SetChannel(channel ssh.Channel)
SetLifecycle(lifecycle Lifecycle)
SetSlugModificator(func(oldSlug, newSlug string) bool)
WaitForKeyPress()
ShowForwardingMessage()
}
type Forwarder interface {
Close() error
GetTunnelType() types.TunnelType
GetForwardedPort() uint16
DropAllForwarder() int
GetForwarderCount() int
}
type Interaction struct {
InputLength int
CommandBuffer *bytes.Buffer
EditMode bool
InteractiveMode bool
InteractionType types.InteractionType
EditSlug string
channel ssh.Channel
SlugManager slug.Manager
@ -65,317 +66,359 @@ func (i *Interaction) SetChannel(channel ssh.Channel) {
}
func (i *Interaction) SendMessage(message string) {
if i.channel != nil {
_, err := i.channel.Write([]byte(message))
if err != nil && err != io.EOF {
log.Printf("Error writing to channel: %v", err)
return
}
if i.channel == nil {
log.Printf("channel is nil")
}
_, err := i.channel.Write([]byte(message))
if err != nil && err != io.EOF {
log.Printf("error writing to channel: %s", err)
}
return
}
func (i *Interaction) HandleUserInput() {
buf := make([]byte, 1)
i.EditMode = false
i.InteractiveMode = false
for {
n, err := i.channel.Read(buf)
if err != nil {
if err != io.EOF {
log.Printf("Error reading from client: %s", err)
}
i.handleReadError(err)
break
}
if n > 0 {
char := buf[0]
if i.EditMode {
i.HandleSlugEditMode(i.channel, char)
continue
}
if i.pendingExit {
if char != 3 {
i.pendingExit = false
i.SendMessage("Operation canceled.\r\n")
}
}
if char == 3 {
if i.pendingExit {
i.SendMessage("Closing connection...\r\n")
err = i.Lifecycle.Close()
if err != nil {
log.Printf("failed to close session: %v", err)
return
}
return
}
i.SendMessage("Please press Ctrl+C again to disconnect.\r\n")
i.pendingExit = true
}
i.SendMessage(string(buf[:n]))
if char == 8 || char == 127 {
if i.InputLength > 0 {
i.SendMessage("\b \b")
}
if i.CommandBuffer.Len() > 0 {
i.CommandBuffer.Truncate(i.CommandBuffer.Len() - 1)
}
continue
}
i.InputLength += n
if char == '/' {
i.CommandBuffer.Reset()
i.CommandBuffer.WriteByte(char)
continue
}
if i.CommandBuffer.Len() > 0 {
if char == 13 {
i.SendMessage("\033[K")
i.HandleCommand(i.CommandBuffer.String())
continue
}
i.CommandBuffer.WriteByte(char)
}
if char == 13 {
i.SendMessage("\033[K")
}
i.processCharacter(buf[0])
}
}
}
func (i *Interaction) HandleSlugEditMode(connection ssh.Channel, char byte) {
if char == 13 {
i.HandleSlugSave(connection)
} else if char == 27 || char == 3 {
i.HandleSlugCancel(connection)
} else if char == 8 || char == 127 {
if len(i.EditSlug) > 0 {
i.EditSlug = (i.EditSlug)[:len(i.EditSlug)-1]
_, err := connection.Write([]byte("\r\033[K"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("➤ " + i.EditSlug + "." + utils.Getenv("domain")))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
}
} else if char >= 32 && char <= 126 {
if (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') || char == '-' {
i.EditSlug += string(char)
_, err := connection.Write([]byte("\r\033[K"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("➤ " + i.EditSlug + "." + utils.Getenv("domain")))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
}
func (i *Interaction) handleReadError(err error) {
if err != io.EOF {
log.Printf("Error reading from client: %s", err)
}
}
func (i *Interaction) HandleSlugSave(connection ssh.Channel) {
isValid := isValidSlug(i.EditSlug)
_, err := connection.Write([]byte("\033[H\033[2J"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
func (i *Interaction) processCharacter(char byte) {
if i.InteractiveMode {
i.handleInteractiveMode(char)
return
}
if isValid {
oldSlug := i.SlugManager.Get()
newSlug := i.EditSlug
if !i.updateClientSlug(oldSlug, newSlug) {
i.HandleSlugUpdateError()
return
}
_, err := connection.Write([]byte("\r\n\r\n✅ SUBDOMAIN UPDATED ✅\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Your new address is: " + newSlug + "." + utils.Getenv("domain") + "\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
} else if isForbiddenSlug(i.EditSlug) {
_, err := connection.Write([]byte("\r\n\r\n❌ FORBIDDEN SUBDOMAIN ❌\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("This subdomain is not allowed.\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Please try a different subdomain.\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
} else {
_, err := connection.Write([]byte("\r\n\r\n❌ INVALID SUBDOMAIN ❌\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Use only lowercase letters, numbers, and hyphens.\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Length must be 3-20 characters and cannot start or end with a hyphen.\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
}
waitForKeyPress(connection)
_, err = connection.Write([]byte("\033[H\033[2J"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
if i.handleExitSequence(char) {
return
}
i.SendMessage(string(char))
i.handleNonInteractiveInput(char)
}
func (i *Interaction) handleInteractiveMode(char byte) {
switch i.InteractionType {
case types.Slug:
i.HandleSlugEditMode(char)
case types.Drop:
i.HandleDropMode(char)
}
}
func (i *Interaction) handleExitSequence(char byte) bool {
if char == ctrlC {
if i.pendingExit {
i.SendMessage("Closing connection...\r\n")
if err := i.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err)
}
return true
}
i.SendMessage("Please press Ctrl+C again to disconnect.\r\n")
i.pendingExit = true
return true
}
if i.pendingExit && char != ctrlC {
i.pendingExit = false
i.SendMessage("Operation canceled.\r\n")
}
return false
}
func (i *Interaction) handleNonInteractiveInput(char byte) {
switch {
case char == backspaceChar || char == deleteChar:
i.handleBackspace()
case char == forwardSlash:
i.handleCommandStart()
case i.CommandBuffer.Len() > 0:
i.handleCommandInput(char)
case char == enterChar:
i.SendMessage(clearLine)
default:
i.InputLength++
}
}
func (i *Interaction) handleBackspace() {
if i.InputLength > 0 {
i.SendMessage(backspaceSeq)
}
if i.CommandBuffer.Len() > 0 {
i.CommandBuffer.Truncate(i.CommandBuffer.Len() - 1)
}
}
func (i *Interaction) handleCommandStart() {
i.CommandBuffer.Reset()
i.CommandBuffer.WriteByte(forwardSlash)
}
func (i *Interaction) handleCommandInput(char byte) {
if char == enterChar {
i.SendMessage(clearLine)
i.HandleCommand(i.CommandBuffer.String())
return
}
i.CommandBuffer.WriteByte(char)
i.InputLength++
}
func (i *Interaction) HandleSlugEditMode(char byte) {
switch {
case char == enterChar:
i.HandleSlugSave()
case char == escapeChar || char == ctrlC:
i.HandleSlugCancel()
case char == backspaceChar || char == deleteChar:
i.handleSlugBackspace()
case char >= minPrintableChar && char <= maxPrintableChar:
i.appendToSlug(char)
}
}
func (i *Interaction) handleSlugBackspace() {
if len(i.EditSlug) > 0 {
i.EditSlug = i.EditSlug[:len(i.EditSlug)-1]
i.refreshSlugDisplay()
}
}
func (i *Interaction) appendToSlug(char byte) {
if isValidSlugChar(char) {
i.EditSlug += string(char)
i.refreshSlugDisplay()
}
}
func (i *Interaction) refreshSlugDisplay() {
domain := utils.Getenv("domain")
i.SendMessage(clearToLineEnd)
i.SendMessage("➤ " + i.EditSlug + "." + domain)
}
func (i *Interaction) HandleSlugSave() {
i.SendMessage(clearScreen)
switch {
case isForbiddenSlug(i.EditSlug):
i.showForbiddenSlugMessage()
case !isValidSlug(i.EditSlug):
i.showInvalidSlugMessage()
default:
i.updateSlug()
}
i.WaitForKeyPress()
i.returnToMainScreen()
}
func (i *Interaction) updateSlug() {
oldSlug := i.SlugManager.Get()
newSlug := i.EditSlug
if !i.updateClientSlug(oldSlug, newSlug) {
i.HandleSlugUpdateError()
return
}
i.ShowWelcomeMessage()
domain := utils.Getenv("domain")
protocol := "http"
if utils.Getenv("tls_enabled") == "true" {
protocol = "https"
}
_, err = connection.Write([]byte(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain)))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
i.SendMessage("\r\n\r\n✅ SUBDOMAIN UPDATED ✅\r\n\r\n")
i.SendMessage("Your new address is: " + newSlug + "." + domain + "\r\n\r\n")
i.SendMessage("Press any key to continue...\r\n")
}
i.EditMode = false
func (i *Interaction) showForbiddenSlugMessage() {
i.SendMessage("\r\n\r\n❌ FORBIDDEN SUBDOMAIN ❌\r\n\r\n")
i.SendMessage("This subdomain is not allowed.\r\n")
i.SendMessage("Please try a different subdomain.\r\n\r\n")
i.SendMessage("Press any key to continue...\r\n")
}
func (i *Interaction) showInvalidSlugMessage() {
i.SendMessage("\r\n\r\n❌ INVALID SUBDOMAIN ❌\r\n\r\n")
i.SendMessage("Use only lowercase letters, numbers, and hyphens.\r\n")
i.SendMessage(fmt.Sprintf("Length must be %d-%d characters and cannot start or end with a hyphen.\r\n\r\n", minSlugLength, maxSlugLength))
i.SendMessage("Press any key to continue...\r\n")
}
func (i *Interaction) returnToMainScreen() {
i.SendMessage(clearScreen)
i.ShowWelcomeMessage()
i.ShowForwardingMessage()
i.InteractiveMode = false
i.CommandBuffer.Reset()
}
func (i *Interaction) HandleSlugCancel(connection ssh.Channel) {
i.EditMode = false
_, err := connection.Write([]byte("\033[H\033[2J"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("\r\n\r\n⚠ SUBDOMAIN EDIT CANCELLED ⚠️\r\n\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
_, err = connection.Write([]byte("Press any key to continue...\r\n"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
waitForKeyPress(connection)
_, err = connection.Write([]byte("\033[H\033[2J"))
if err != nil {
log.Printf("failed to write to channel: %v", err)
return
}
i.ShowWelcomeMessage()
i.CommandBuffer.Reset()
func (i *Interaction) HandleSlugCancel() {
i.InteractiveMode = false
i.showMessageAndWait("\r\n\r\n⚠ SUBDOMAIN EDIT CANCELLED ⚠️\r\n\r\n")
}
func (i *Interaction) HandleSlugUpdateError() {
i.SendMessage("\r\n\r\n❌ SERVER ERROR ❌\r\n\r\n")
i.SendMessage("Failed to update subdomain. You will be disconnected in 5 seconds.\r\n\r\n")
for iter := 5; iter > 0; iter-- {
i.SendMessage(fmt.Sprintf("Disconnecting in %d...\r\n", iter))
for countdown := 5; countdown > 0; countdown-- {
i.SendMessage(fmt.Sprintf("Disconnecting in %d...\r\n", countdown))
time.Sleep(1 * time.Second)
}
err := i.Lifecycle.Close()
if err != nil {
if err := i.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err)
return
}
}
func (i *Interaction) HandleCommand(command string) {
switch command {
case "/bye":
i.SendMessage("Closing connection...\r\n")
err := i.Lifecycle.Close()
if err != nil {
log.Printf("failed to close session: %v", err)
return
}
return
case "/help":
i.SendMessage("\r\nAvailable commands: /bye, /help, /clear, /slug\r\n")
case "/clear":
i.SendMessage("\033[H\033[2J")
i.ShowWelcomeMessage()
domain := utils.Getenv("domain")
if i.Forwarder.GetTunnelType() == types.HTTP {
protocol := "http"
if utils.Getenv("tls_enabled") == "true" {
protocol = "https"
}
i.SendMessage(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain))
} else {
i.SendMessage(fmt.Sprintf("Forwarding your traffic to tcp://%s:%d \r\n", domain, i.Forwarder.GetForwardedPort()))
}
case "/slug":
if i.Forwarder.GetTunnelType() != types.HTTP {
i.SendMessage(fmt.Sprintf("\r\n%s tunnels cannot have custom subdomains", i.Forwarder.GetTunnelType()))
} else {
i.EditMode = true
i.EditSlug = i.SlugManager.Get()
i.SendMessage("\033[H\033[2J")
i.DisplaySlugEditor()
i.SendMessage("➤ " + i.EditSlug + "." + utils.Getenv("domain"))
}
default:
handlers := map[string]func(){
"/bye": i.handleByeCommand,
"/help": i.handleHelpCommand,
"/clear": i.handleClearCommand,
"/slug": i.handleSlugCommand,
"/drop": i.handleDropCommand,
}
if handler, exists := handlers[command]; exists {
handler()
} else {
i.SendMessage("Unknown command\r\n")
}
i.CommandBuffer.Reset()
}
func (i *Interaction) handleByeCommand() {
i.SendMessage("Closing connection...\r\n")
if err := i.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err)
}
}
func (i *Interaction) handleHelpCommand() {
i.SendMessage("\r\nAvailable commands: /bye, /help, /clear, /slug, /drop\r\n")
}
func (i *Interaction) handleClearCommand() {
i.SendMessage(clearScreen)
i.ShowWelcomeMessage()
i.ShowForwardingMessage()
}
func (i *Interaction) handleSlugCommand() {
if i.Forwarder.GetTunnelType() != types.HTTP {
i.SendMessage(fmt.Sprintf("\r\n%s tunnels cannot have custom subdomains\r\n", i.Forwarder.GetTunnelType()))
return
}
i.InteractiveMode = true
i.InteractionType = types.Slug
i.EditSlug = i.SlugManager.Get()
i.SendMessage(clearScreen)
i.DisplaySlugEditor()
domain := utils.Getenv("domain")
i.SendMessage("➤ " + i.EditSlug + "." + domain)
}
func (i *Interaction) handleDropCommand() {
i.InteractiveMode = true
i.InteractionType = types.Drop
i.SendMessage(clearScreen)
i.ShowDropMessage()
}
func (i *Interaction) ShowForwardingMessage() {
domain := utils.Getenv("domain")
if i.Forwarder.GetTunnelType() == types.HTTP {
protocol := "http"
if utils.Getenv("tls_enabled") == "true" {
protocol = "https"
}
i.SendMessage(fmt.Sprintf("Forwarding your traffic to %s://%s.%s \r\n", protocol, i.SlugManager.Get(), domain))
} else {
i.SendMessage(fmt.Sprintf("Forwarding your traffic to tcp://%s:%d \r\n", domain, i.Forwarder.GetForwardedPort()))
}
}
func (i *Interaction) HandleDropMode(char byte) {
switch {
case char == enterChar || char == 'y' || char == 'Y':
i.executeDropAll()
case char == escapeChar || char == 'n' || char == 'N' || char == ctrlC:
i.cancelDrop()
}
}
func (i *Interaction) executeDropAll() {
count := i.Forwarder.DropAllForwarder()
message := fmt.Sprintf("Dropped %d forwarders\r\n", count)
i.showMessageAndWait(message)
}
func (i *Interaction) cancelDrop() {
i.showMessageAndWait("Dropping canceled.\r\n")
}
func (i *Interaction) showMessageAndWait(message string) {
i.SendMessage(clearScreen)
i.SendMessage(message)
i.SendMessage("Press any key to continue...\r\n")
i.InteractiveMode = false
i.InteractionType = ""
i.WaitForKeyPress()
i.SendMessage(clearScreen)
i.ShowWelcomeMessage()
i.ShowForwardingMessage()
}
func (i *Interaction) ShowDropMessage() {
confirmText := fmt.Sprintf(" ║ Drop ALL %d active connections?", i.Forwarder.GetForwarderCount())
boxWidth := calculateBoxWidth(confirmText)
box := buildDropConfirmationBox(boxWidth, confirmText)
i.SendMessage("\r\n" + box + "\r\n\r\n")
}
func buildDropConfirmationBox(boxWidth int, confirmText string) string {
topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n"
title := centerText("DROP CONFIRMATION", boxWidth-4)
header := " ║" + title + "║\r\n"
midBorder := " ╠" + strings.Repeat("═", boxWidth-4) + "╣\r\n"
emptyLine := " ║" + strings.Repeat(" ", boxWidth-4) + "║\r\n"
confirmLine := confirmText + strings.Repeat(" ", boxWidth-len(confirmText)+1) + "║\r\n"
controlText := " ║ [Enter/Y] Confirm [N/Esc] Cancel"
controlLine := controlText + strings.Repeat(" ", boxWidth-len(controlText)+1) + "║\r\n"
bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n"
return topBorder + header + midBorder + emptyLine + confirmLine + emptyLine + controlLine + emptyLine + bottomBorder
}
func (i *Interaction) ShowWelcomeMessage() {
asciiArt := []string{
` _______ _ _____ _ `,
@ -393,6 +436,7 @@ func (i *Interaction) ShowWelcomeMessage() {
` - '/help' : Show this help message`,
` - '/clear' : Clear the current line`,
` - '/slug' : Set custom subdomain`,
` - '/drop' : Drop all active forwarders`,
}
for _, line := range asciiArt {
@ -405,14 +449,14 @@ func (i *Interaction) DisplaySlugEditor() {
domain := utils.Getenv("domain")
fullDomain := i.SlugManager.Get() + "." + domain
const paddingRight = 4
contentLine := " ║ Current: " + fullDomain
boxWidth := len(contentLine) + paddingRight + 1
if boxWidth < 50 {
boxWidth = 50
}
boxWidth := calculateBoxWidth(contentLine)
box := buildSlugEditorBox(boxWidth, fullDomain)
i.SendMessage("\r\n\r\n" + box + "\r\n\r\n")
}
func buildSlugEditorBox(boxWidth int, fullDomain string) string {
topBorder := " ╔" + strings.Repeat("═", boxWidth-4) + "╗\r\n"
title := centerText("SUBDOMAIN EDITOR", boxWidth-4)
header := " ║" + title + "║\r\n"
@ -425,24 +469,31 @@ func (i *Interaction) DisplaySlugEditor() {
saveCancel := " ║ [Enter] Save | [Esc] Cancel" + strings.Repeat(" ", boxWidth-35) + "║\r\n"
bottomBorder := " ╚" + strings.Repeat("═", boxWidth-4) + "╝\r\n"
i.SendMessage("\r\n\r\n")
i.SendMessage(topBorder)
i.SendMessage(header)
i.SendMessage(midBorder)
i.SendMessage(emptyLine)
i.SendMessage(currentLine)
i.SendMessage(emptyLine)
i.SendMessage(emptyLine)
i.SendMessage(midBorder)
i.SendMessage(saveCancel)
i.SendMessage(bottomBorder)
i.SendMessage("\r\n\r\n")
return topBorder + header + midBorder + emptyLine + currentLine + emptyLine + emptyLine + midBorder + saveCancel + bottomBorder
}
func (i *Interaction) SetSlugModificator(modificator func(oldSlug, newSlug string) bool) {
i.updateClientSlug = modificator
}
func (i *Interaction) WaitForKeyPress() {
keyBuf := make([]byte, 1)
for {
_, err := i.channel.Read(keyBuf)
if err == nil {
break
}
}
}
func calculateBoxWidth(contentLine string) int {
boxWidth := len(contentLine) + paddingRight + 1
if boxWidth < minBoxWidth {
boxWidth = minBoxWidth
}
return boxWidth
}
func centerText(text string, width int) string {
padding := (width - len(text)) / 2
if padding < 0 {
@ -452,7 +503,7 @@ func centerText(text string, width int) string {
}
func isValidSlug(slug string) bool {
if len(slug) < 3 || len(slug) > 20 {
if len(slug) < minSlugLength || len(slug) > maxSlugLength {
return false
}
@ -461,7 +512,7 @@ func isValidSlug(slug string) bool {
}
for _, c := range slug {
if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') {
if !isValidSlugChar(byte(c)) {
return false
}
}
@ -469,18 +520,12 @@ func isValidSlug(slug string) bool {
return true
}
func waitForKeyPress(connection ssh.Channel) {
keyBuf := make([]byte, 1)
for {
_, err := connection.Read(keyBuf)
if err == nil {
break
}
}
func isValidSlugChar(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'
}
func isForbiddenSlug(slug string) bool {
for _, s := range forbiddenSlug {
for _, s := range forbiddenSlugs {
if slug == s {
return true
}

View File

@ -43,12 +43,12 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
SlugManager: slugManager,
}
interactionManager := &interaction.Interaction{
CommandBuffer: bytes.NewBuffer(make([]byte, 0, 20)),
EditMode: false,
EditSlug: "",
SlugManager: slugManager,
Forwarder: forwarderManager,
Lifecycle: nil,
CommandBuffer: bytes.NewBuffer(make([]byte, 0, 20)),
InteractiveMode: false,
EditSlug: "",
SlugManager: slugManager,
Forwarder: forwarderManager,
Lifecycle: nil,
}
lifecycleManager := &lifecycle.Lifecycle{
Status: "",
@ -71,28 +71,25 @@ func New(conn *ssh.ServerConn, forwardingReq <-chan *ssh.Request, sshChan <-chan
SlugManager: slugManager,
}
go func() {
go session.Lifecycle.WaitForRunningStatus()
for channel := range sshChan {
ch, reqs, err := channel.Accept()
if err != nil {
log.Printf("failed to accept channel: %v", err)
continue
}
session.channelOnce.Do(func() {
session.Lifecycle.SetChannel(ch)
session.Interaction.SetChannel(ch)
session.Lifecycle.SetStatus(types.SETUP)
go session.HandleGlobalRequest(forwardingReq)
})
go session.HandleGlobalRequest(reqs)
for channel := range sshChan {
ch, reqs, err := channel.Accept()
if err != nil {
log.Printf("failed to accept channel: %v", err)
continue
}
if err := session.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err)
}
}()
session.channelOnce.Do(func() {
session.Lifecycle.SetChannel(ch)
session.Interaction.SetChannel(ch)
session.Lifecycle.SetStatus(types.SETUP)
go session.HandleGlobalRequest(forwardingReq)
session.Lifecycle.WaitForRunningStatus()
})
go session.HandleGlobalRequest(reqs)
}
if err := session.Lifecycle.Close(); err != nil {
log.Printf("failed to close session: %v", err)
}
}
func updateClientSlug(oldSlug, newSlug string) bool {

View File

@ -15,6 +15,13 @@ const (
TCP TunnelType = "TCP"
)
type InteractionType string
const (
Slug InteractionType = "SLUG"
Drop InteractionType = "DROP"
)
var BadGatewayResponse = []byte("HTTP/1.1 502 Bad Gateway\r\n" +
"Content-Length: 11\r\n" +
"Content-Type: text/plain\r\n\r\n" +