├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ └── release.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── api └── api.go ├── cmd └── infrared │ ├── .goreleaser.yml │ └── main.go ├── config.go ├── conn.go ├── docker-compose.yml ├── gateway.go ├── gateway_test.go ├── go.mod ├── go.sum ├── grafana ├── README.md ├── dashboard.json └── dashboard.png ├── process ├── docker.go ├── portainer.go └── process.go ├── protocol ├── cfb8 │ └── cfb8.go ├── errors.go ├── handshaking │ ├── serverbound_handshake.go │ └── serverbound_handshake_test.go ├── login │ ├── clientbound_disconnect.go │ ├── clientbound_disconnect_test.go │ ├── clientbound_encryptionrequest.go │ ├── clientbound_loginsuccess.go │ ├── serverbound_encryptionresponse.go │ ├── serverbound_loginstart.go │ └── serverbound_loginstart_test.go ├── packet.go ├── packet_test.go ├── peeker.go ├── peeker_test.go ├── play │ └── clientbound_disconnect.go ├── status │ ├── clientbound_pong.go │ ├── clientbound_response.go │ ├── clientbound_response_test.go │ ├── serverbound_ping.go │ ├── serverbound_request.go │ └── serverbound_request_test.go ├── types.go └── types_test.go ├── proxy.go └── sha1.go /.gitattributes: -------------------------------------------------------------------------------- 1 | * -text -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | What OS are you using? 15 | What version of Infrared are you using? 16 | What do your Infrared proxy config(s) look like? 17 | How do you trigger the bug/issue? 18 | 19 | **Expected behavior** 20 | A clear and concise description of what you expected to happen. 21 | 22 | **Screenshots** (Optional) 23 | If applicable, add screenshots to help explain your problem. 24 | A copy of your logs would be nice, but please be sure to censor any information that you don't want to be public. 25 | 26 | **Additional context** (Optional) 27 | Add any other context of the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. E.g.: "I'm always frustrated when [...]" 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots regarding the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: goreleaser 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | goreleaser: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | with: 15 | fetch-depth: 0 16 | - name: Set up Go 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: 1.17 20 | - name: Run GoReleaser 21 | uses: goreleaser/goreleaser-action@v2 22 | with: 23 | version: latest 24 | args: release --rm-dist 25 | workdir: ./cmd/infrared/. 26 | env: 27 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Config files 15 | *.yaml 16 | 17 | .idea 18 | ./configs/ -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.16.0-buster AS builder 2 | LABEL stage=intermediate 3 | COPY . /infrared 4 | WORKDIR /infrared/cmd/infrared 5 | ENV GO111MODULE=on 6 | RUN CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -a --installsuffix cgo -v -tags netgo -ldflags '-extldflags "-static"' -o /main . 7 | 8 | FROM scratch 9 | LABEL maintainer="Hendrik Jonas Schlehlein " 10 | WORKDIR / 11 | COPY --from=builder /main ./ 12 | ENTRYPOINT [ "./main" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | # Infrared - a Minecraft Proxy 6 | 7 | fork of [haveachin/infrared](https://github.com/haveachin/infrared) 8 | 9 | ## TODO 10 | - Make encryption check use 1.19 signatures 11 | 12 | ## Added/changed Features 13 | 14 | - Default configurable placeholder for invalid domain and kick message 15 | - Antibot based on ip lookups, encryption checks, authentication checks, protocol checks and username lookups 16 | - Caching in redis server (can be used for multiple instances) 17 | - Added handshakes and blocked connections(multiple types) to prometheus exporter 18 | - Allow multiple domains in 1 configfile 19 | - Global .yml config 20 | - Removed docker and callback features 21 | - Status packet caching (per protocol version) 22 | - Bandwith usage tracking for proxy configs through prometheus 23 | - Use redis to get proxy configs ([lhridder/infrapi](https://github.com/lhridder/infrapi)) 24 | - Live upgrades using [tableflip](https://github.com/cloudflare/tableflip) 25 | - Dual stack (both IPv4 and IPv6 are supported) 26 | 27 | ## Command-Line Flags 28 | 29 | `-config-path` specifies the path to all your server configs [default: `"./configs/"`] 30 | 31 | ### Example Usage 32 | 33 | `./infrared -config-path="."` 34 | 35 | ## Global config.yml 36 | ### Example/Default 37 | ```yaml 38 | debug: false 39 | receiveProxyProtocol: false 40 | useRedisConfigs: false 41 | underAttack: false 42 | connectionThreshold: 50 43 | trackBandwidth: false 44 | prometheus: 45 | enabled: false 46 | bind: :9070 47 | api: 48 | enabled: false 49 | bind: :5000 50 | mojangAPIenabled: false 51 | geoip: 52 | enabled: false 53 | databaseFile: 54 | enableIprisk: false 55 | redis: 56 | host: localhost 57 | pass: 58 | db: 0 59 | configredis: 60 | host: localhost 61 | pass: 62 | db: 0 63 | rejoinMessage: Please rejoin to verify your connection. 64 | blockedMessage: Your ip is blocked for suspicious activity. 65 | genericJoinResponse: There is no proxy associated with this domain. Please check your configuration. 66 | genericping: 67 | version: infrared 68 | description: There is no proxy associated with this domain. Please check your configuration. 69 | iconPath: 70 | tableflip: 71 | enabled: false 72 | pidfile: infrared.pid 73 | ``` 74 | Values can be left out if they don't deviate from the default, an empty config.yml is still required for startup. 75 | ### Fields 76 | - `receiveProxyProtocol` whether to allow for inbound proxyProtocol connections. 77 | - prometheus: 78 | - `enabled` whether to enable to builtin prometheus exporter or not. 79 | - `bind` on what port/address to have the prometheus exporter listen on. 80 | - `bind2` what secondary port should be used when using tableflip. 81 | - api: 82 | - `nabled` if the json http api should be enabled. 83 | - `bind` on what port/address to have the api listen on. 84 | - genericping: 85 | - `version` what version should be sent with for an unknown domain status request. 86 | - `description` what description should be sent with for an unknown domain status request. 87 | - `iconPath` what icon should be sent with for an unknown domain status request. 88 | - `genericJoinResponse` what text response should be sent for an unknown domain join request. 89 | - geoip: 90 | - `enabled` if geoip lookups should be enabled. 91 | - `databaseFile` where the .mmdb file is located for geoip lookups. 92 | - `enableIprisk` whether or not ip lookups should be done through iprisk.info. 93 | - `mojangAPIenabled` whether to enable mojang API username checks (only works if geoip is enabled). 94 | - redis: 95 | - `host` what redis server to connect to when caching geoip and username lookups. 96 | - `DB` what redis db should be used on the redis server. 97 | - `pass` what password should be used when logging into the redis server. 98 | - configredis: 99 | - `host` what redis server to connect to when fetching and watching configs. 100 | - `DB` what redis db should be used on the redis server. 101 | - `pass` what password should be used when logging into the redis server. 102 | - tableflip: 103 | - `enabled` whether or not tableflip should be used. 104 | - `pidfile` where the PID file used for tableflip is located. 105 | - `rejoinMessage` what text response should be sent when a player needs to rejoin to verify they're not a bot. 106 | - `blockedMessage` what text response should be sent when an ip address gets blocked. 107 | - `underAttack` if the instance should permanently be in attack mode. 108 | - `debug` if debug logs should be enabled. 109 | - `connectionTreshold` at what amount of packets per second the underAttack mode should trigger. 110 | - `trackBandwith` whether or not bandwith usage should be tracked in prometheus (requires prometheusEnabled). 111 | - `useRedisConfigs` whether or not to get the proxy configs from redis (this will disable the builtin api). 112 | 113 | ## Proxy Config 114 | 115 | | Field Name | Type | Required | Default | Description | 116 | |-------------------|-----------|----------|------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 117 | | domainNames | String[] | true | localhost | Should be [fully qualified domain name](https://en.wikipedia.org/wiki/Domain_name).
Note: Every string is accepted. So `localhost` is also valid. | 118 | | listenTo | String | true | :25565 | The address (usually just the port; so short term `:port`) that the proxy should listen to for incoming connections.
Accepts basically every address format you throw at it. Valid examples: `:25565`, `localhost:25565`, `0.0.0.0:25565`, `127.0.0.1:25565`, `example.de:25565` | 119 | | proxyTo | String | true | | The address that the proxy should send incoming connections to. Accepts Same formats as the `listenTo` field. | 120 | | proxyBind | String | false | | The local IP that is being used to dail to the server on `proxyTo`. (Same as Nginx `proxy-bind`) | 121 | | disconnectMessage | String | false | Sorry {{username}}, but the server is offline. | The message a client sees when he gets disconnected from Infrared due to the server on `proxyTo` won't respond. Currently available placeholders:
- `username` the username of player that tries to connect
- `now` the current server time
- `remoteAddress` the address of the client that tries to connect
- `localAddress` the local address of the server
- `domain` the domain of the proxy (same as `domainName`)
- `proxyTo` the address that the proxy proxies to (same as `proxyTo`)
- `listenTo` the address that Infrared listens on (same as `listenTo`) | 122 | | timeout | Integer | true | 1000 | The time in milliseconds for the proxy to wait for a ping response before the host (the address you proxyTo) will be declared as offline. This "online check" will be resend for every new connection. | 123 | | proxyProtocol | Boolean | false | false | If Infrared should use HAProxy's Proxy Protocol for IP **forwarding**.
Warning: You should only ever set this to true if you now that the server you `proxyTo` is compatible. | 124 | | realIp | Boolean | false | false | If Infrared should use TCPShield/RealIP Protocol for IP **forwarding**.
Warning: You should only ever set this to true if you now that the server you `proxyTo` is compatible. | | 125 | | onlineStatus | Object | false | | This is the response that Infrared will give when a client asks for the server status and the server is online. | 126 | | offlineStatus | Object | false | See [Response Status](#response-status) | This is the response that Infrared will give when a client asks for the server status and the server is offline. | 127 | 128 | ### Response Status 129 | 130 | | Field Name | Type | Required | Default | Description | 131 | |----------------|---------|----------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------| 132 | | versionName | String | false | Infrared 1.18 | The version name of the Minecraft Server. | 133 | | protocolNumber | Integer | true | 757 | The protocol version number. | 134 | | maxPlayers | Integer | false | 20 | The maximum number of players that can join the server.
Note: Infrared will not limit more players from joining. This number is just for display. | 135 | | playersOnline | Integer | false | 0 | The number of online players.
Note: Infrared will not that this number is also just for display. | 136 | | playerSamples | Array | false | | An array of player samples. See [Player Sample](#Player Sample). | 137 | | iconPath | String | false | | The path to the server icon. | 138 | | motd | String | false | | The motto of the day, short MOTD. | 139 | 140 | ### Examples 141 | 142 | #### Minimal Config 143 | 144 |
145 | min.example.com 146 | 147 | ```json 148 | { 149 | "domainNames": ["mc.example.com", "example.com"], 150 | "proxyTo": ":8080" 151 | } 152 | ``` 153 | 154 |
155 | 156 | #### Full Config 157 | 158 |
159 | full.example.com 160 | 161 | ```json 162 | { 163 | "domainNames": ["mc.example.com", "example.com"], 164 | "listenTo": ":25565", 165 | "proxyTo": ":8080", 166 | "proxyBind": "0.0.0.0", 167 | "proxyProtocol": false, 168 | "realIp": false, 169 | "timeout": 1000, 170 | "disconnectMessage": "Username: {{username}}\nNow: {{now}}\nRemoteAddress: {{remoteAddress}}\nLocalAddress: {{localAddress}}\nDomain: {{domain}}\nProxyTo: {{proxyTo}}\nListenTo: {{listenTo}}", 171 | "onlineStatus": { 172 | "versionName": "1.18", 173 | "protocolNumber": 757, 174 | "maxPlayers": 20, 175 | "playersOnline": 2, 176 | "playerSamples": [ 177 | { 178 | "name": "Steve", 179 | "uuid": "8667ba71-b85a-4004-af54-457a9734eed7" 180 | }, 181 | { 182 | "name": "Alex", 183 | "uuid": "ec561538-f3fd-461d-aff5-086b22154bce" 184 | } 185 | ], 186 | "motd": "Join us!" 187 | }, 188 | "offlineStatus": { 189 | "versionName": "1.18", 190 | "protocolNumber": 757, 191 | "maxPlayers": 20, 192 | "playersOnline": 0, 193 | "motd": "Server is currently offline" 194 | } 195 | } 196 | ``` 197 | 198 |
199 | 200 | ## Prometheus exporter 201 | The built-in prometheus exporter can be used to view metrics about infrareds operation. 202 | This can be used through `"prometheusEnabled": true` and `"prometheusBind": ":9070"` in `config.yml` 203 | It is recommended to firewall the prometheus exporter with an application like *ufw* or *iptables* to make it only accessible by your own Prometheus instance. 204 | ### Prometheus configuration: 205 | Example prometheus.yml configuration: 206 | ```yaml 207 | scrape_configs: 208 | - job_name: infrared 209 | static_configs: 210 | - targets: ['infrared-exporter-hostname:port'] 211 | ``` 212 | 213 | ### Metrics: 214 | * infrared_connected: show the amount of connected players per instance and proxy: 215 | * **Example response:** `infrared_connected{host="proxy.example.com",instance="vps1.example.com:9070",job="infrared"} 10` 216 | * **host:** listenTo domain as specified in the infrared configuration. 217 | * **instance:** what infrared instance the amount of players are connected to. 218 | * **job:** what job was specified in the prometheus configuration. 219 | * infrared_handshakes: counter of the number of handshake packets received per instance, type and target: 220 | * **Example response:** `infrared_handshakes{instance="vps1.example.com:9070",type="status",host="proxy.example.com",country="DE"} 5` 221 | * **instance:** what infrared instance handshakes were received on. 222 | * **type:** the type of handshake received; "status", "login", "cancelled_host", "cancelled_encryption", "cancelled_name", "cancelled", "cancelled_authentication" and "cancelled_invalid". 223 | * **country:** country where the player ip is from. 224 | * **host:** the target host specified by the "Server Address" field in the handshake packet. [[1]](https://wiki.vg/Protocol#Handshaking) 225 | 226 | ## Mitigation 227 | ### GeoIP 228 | Infrared uses maxminds mmdb format for looking up the countries ips originate from.\ 229 | The required GeoLite2-Country.mmdb/GeoLite2-City.mmdb can be downloaded from [maxmind](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) for free by making an account. 230 | 231 | ### Configuration 232 | The following configuration settings are recommended for optimal mitigation, keep in mind this requieres a local/online redis server for caching. 233 | ```yaml 234 | debug: false 235 | mojangAPIenabled: true 236 | geoip: 237 | enabled: true 238 | databaseFile: GeoLite2-Country.mmdb 239 | redis: 240 | host: localhost 241 | pass: 242 | db: 0 243 | ``` 244 | 245 | ### System 246 | * Linux kernel >=5.8 (Debian >=11 or Ubuntu >=22.04) 247 | * Increasing `net.core.somaxconn` in sysctl to for example 50000 (default is 4096). Can be done with `sysctl net.core.somaxconn=50000`. 248 | * Increasing the `ulimit` to for example 500000 (default is 1024). Can be done with `ulimit -n 500000` when running in a terminal or `LimitNOFILE=500000` in a systemd service file. 249 | 250 | ## Tableflip 251 | [Tableflip](https://github.com/cloudflare/tableflip) allows for the golang application to be upgraded live by swapping the binary and creating a new process without killing off existing connections.\ 252 | #### Systemd 253 | To use this feature running infrared under systemd is required, here an example of how the .service file should look: 254 | Upgrades can then be triggered with `systemctl reload infrared`. 255 | ```text 256 | [Unit] 257 | Description=Infrared 258 | After=network-online.target 259 | 260 | [Service] 261 | User=root 262 | Group=root 263 | WorkingDirectory=/srv/infrared 264 | ExecStart=/srv/infrared/infrared 265 | ExecReload=/bin/kill -HUP $MAINPID 266 | PIDFile=/srv/infrared/infrared.pid 267 | LimitNOFILE=500000 268 | LimitNPROC=500000 269 | 270 | [Install] 271 | WantedBy=multi-user.target 272 | ``` 273 | #### Configuration 274 | ```yaml 275 | tableflip: 276 | enabled: true 277 | pidfile: infrared.pid 278 | ``` 279 | 280 | ## API 281 | ### Route examples 282 | GET `/proxies` will return 283 | ```json 284 | [ 285 | "config", 286 | "config2" 287 | ] 288 | ``` 289 | 290 | GET `/proxies/{name}` will return 291 | ```json 292 | { 293 | "domainNames": ["play.example.org"], 294 | "proxyTo": "backend.example.org:25566" 295 | } 296 | ``` 297 | 298 | POST `/proxies/{name}` with body 299 | ```json 300 | { 301 | "domainNames": ["play.example.org"], 302 | "proxyTo": "backend.example.org:25566" 303 | } 304 | ``` 305 | will return 306 | ```json 307 | {"success": true, "message": "the proxy has been succesfully added"} 308 | ``` 309 | 310 | DELETE `/proxies/{name}` will return 200(OK) 311 | 312 | GET `/` will return 200(OK) 313 | 314 | ## Used sources 315 | - [Minecraft protocol documentation](https://wiki.vg/Protocol) 316 | - [Minecraft protocol implementation in golang 1](https://github.com/specspace/plasma) 317 | - [Minecraft protocol implementation in golang 2](https://github.com/Tnze/go-mc) 318 | - [Mojang api implementation in golang](https://github.com/Lukaesebrot/mojango) 319 | - [Redis library for golang](https://github.com/go-redis/redis/v8) 320 | - [MMDB geoip library for golang](https://github.com/oschwald/geoip2-golang) 321 | - [Govalidator](https://github.com/asaskevich/govalidator) 322 | - [Mux router](https://github.com/gorilla/mux) 323 | - [Tableflip](https://github.com/cloudflare/tableflip) 324 | -------------------------------------------------------------------------------- /api/api.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/gorilla/mux" 6 | "github.com/haveachin/infrared" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | "os" 11 | "strings" 12 | ) 13 | 14 | // ListenAndServe Start Webserver 15 | func ListenAndServe(configPath string, apiBind string) { 16 | log.Println("Starting WebAPI on " + apiBind) 17 | router := mux.NewRouter() 18 | 19 | router.HandleFunc("/", getHome()).Methods("GET") 20 | router.HandleFunc("/proxies", getProxies(configPath)).Methods("GET") 21 | router.HandleFunc("/proxies/{name}", getProxy(configPath)).Methods("GET") 22 | router.HandleFunc("/proxies/{name}", addProxyWithName(configPath)).Methods("POST") 23 | router.HandleFunc("/proxies/{name}", removeProxy(configPath)).Methods("DELETE") 24 | 25 | if infrared.Config.Tableflip.Enabled { 26 | listen, err := infrared.Upg.Listen("tcp", apiBind) 27 | if err != nil { 28 | log.Printf("Failed to start API listener: %s", err) 29 | return 30 | } 31 | err = http.Serve(listen, router) 32 | if err != nil { 33 | log.Printf("Failed to start serving API: %s", err) 34 | return 35 | } 36 | } else { 37 | err := http.ListenAndServe(apiBind, router) 38 | if err != nil { 39 | log.Printf("Failed to start serving API: %s", err) 40 | return 41 | } 42 | } 43 | } 44 | 45 | // getHome 46 | func getHome() http.HandlerFunc { 47 | return func(w http.ResponseWriter, r *http.Request) {} 48 | } 49 | 50 | // getProxies 51 | func getProxies(configPath string) http.HandlerFunc { 52 | return func(w http.ResponseWriter, r *http.Request) { 53 | var configs []string 54 | 55 | files, err := ioutil.ReadDir(configPath) 56 | if err != nil { 57 | log.Println(err) 58 | w.WriteHeader(http.StatusInternalServerError) 59 | return 60 | } 61 | 62 | for _, file := range files { 63 | configs = append(configs, strings.Split(file.Name(), ".json")[0]) 64 | } 65 | 66 | err = json.NewEncoder(w).Encode(&configs) 67 | if err != nil { 68 | w.WriteHeader(http.StatusInternalServerError) 69 | return 70 | } 71 | } 72 | } 73 | 74 | // getProxy 75 | func getProxy(configPath string) http.HandlerFunc { 76 | return func(w http.ResponseWriter, r *http.Request) { 77 | fileName := mux.Vars(r)["name"] + ".json" 78 | 79 | jsonFile, err := os.Open(configPath + "/" + fileName) 80 | defer jsonFile.Close() 81 | if err != nil { 82 | w.WriteHeader(http.StatusNotFound) 83 | return 84 | } 85 | 86 | config, err := ioutil.ReadAll(jsonFile) 87 | if err != nil { 88 | log.Println(err) 89 | w.WriteHeader(http.StatusInternalServerError) 90 | return 91 | } 92 | 93 | _, err = w.Write(config) 94 | if err != nil { 95 | log.Println(err) 96 | w.WriteHeader(http.StatusInternalServerError) 97 | return 98 | } 99 | } 100 | } 101 | 102 | // addProxyWithName respond to post proxy request 103 | func addProxyWithName(configPath string) http.HandlerFunc { 104 | return func(w http.ResponseWriter, r *http.Request) { 105 | fileName := mux.Vars(r)["name"] + ".json" 106 | 107 | rawData, err := ioutil.ReadAll(r.Body) 108 | if err != nil || string(rawData) == "" { 109 | w.WriteHeader(http.StatusBadRequest) 110 | return 111 | } 112 | 113 | jsonIsValid := checkJSONAndRegister(rawData, fileName, configPath) 114 | if jsonIsValid { 115 | w.WriteHeader(http.StatusOK) 116 | w.Write([]byte("{'success': true, 'message': 'the proxy has been added succesfully'}")) 117 | return 118 | } else { 119 | w.WriteHeader(http.StatusBadRequest) 120 | w.Write([]byte("{'success': false, 'message': 'domainNames and proxyTo could not be found'}")) 121 | return 122 | } 123 | } 124 | } 125 | 126 | // removeProxy respond to delete proxy request 127 | func removeProxy(configPath string) http.HandlerFunc { 128 | return func(w http.ResponseWriter, r *http.Request) { 129 | file := mux.Vars(r)["name"] + ".json" 130 | 131 | err := os.Remove(configPath + "/" + file) 132 | if err != nil { 133 | w.WriteHeader(http.StatusNoContent) 134 | w.Write([]byte(err.Error())) 135 | return 136 | } 137 | } 138 | } 139 | 140 | // checkJSONAndRegister validate proxy configuration 141 | func checkJSONAndRegister(rawData []byte, filename string, configPath string) (successful bool) { 142 | var cfg infrared.ProxyConfig 143 | err := json.Unmarshal(rawData, &cfg) 144 | if err != nil { 145 | log.Println(err) 146 | return false 147 | } 148 | 149 | if len(cfg.DomainNames) < 1 || cfg.ProxyTo == "" { 150 | return false 151 | } 152 | 153 | path := configPath + "/" + filename 154 | temppath := path + ".temp" 155 | 156 | err = os.WriteFile(temppath, rawData, 0644) 157 | if err != nil { 158 | log.Println(err) 159 | return false 160 | } 161 | 162 | err = os.Rename(temppath, path) 163 | if err != nil { 164 | return false 165 | } 166 | 167 | return true 168 | } 169 | -------------------------------------------------------------------------------- /cmd/infrared/.goreleaser.yml: -------------------------------------------------------------------------------- 1 | env: 2 | - GO111MODULE=on 3 | - GOPROXY=https://proxy.golang.org 4 | before: 5 | hooks: 6 | - go mod download 7 | builds: 8 | - env: 9 | - CGO_ENABLED=0 10 | goos: 11 | - linux 12 | - darwin 13 | - windows 14 | goarch: 15 | - 386 16 | - amd64 17 | - arm 18 | - arm64 19 | ignore: 20 | - goos: darwin 21 | goarch: 386 22 | mod_timestamp: '{{ .CommitTimestamp }}' 23 | flags: 24 | - -trimpath 25 | ldflags: 26 | - -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{ .CommitDate }} -X main.builtBy=goreleaser 27 | checksum: 28 | name_template: '{{ .ProjectName }}_checksums.txt' 29 | changelog: 30 | sort: asc 31 | filters: 32 | exclude: 33 | - '^docs:' 34 | - '^test:' 35 | - Merge pull request 36 | - Merge branch 37 | - go mod tidy 38 | archives: 39 | - name_template: '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' 40 | replacements: 41 | darwin: Darwin 42 | linux: Linux 43 | windows: Windows 44 | 386: i386 45 | amd64: x86_64 46 | format_overrides: 47 | - goos: windows 48 | format: zip -------------------------------------------------------------------------------- /cmd/infrared/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "flag" 6 | "fmt" 7 | "github.com/cloudflare/tableflip" 8 | "github.com/haveachin/infrared" 9 | "github.com/haveachin/infrared/api" 10 | "log" 11 | "os" 12 | "os/signal" 13 | "strconv" 14 | "syscall" 15 | ) 16 | 17 | const ( 18 | envPrefix = "INFRARED_" 19 | envConfigPath = envPrefix + "CONFIG_PATH" 20 | ) 21 | 22 | const ( 23 | clfConfigPath = "config-path" 24 | ) 25 | 26 | var ( 27 | configPath = "./configs" 28 | ) 29 | 30 | func envString(name string, value string) string { 31 | envString := os.Getenv(name) 32 | if envString == "" { 33 | return value 34 | } 35 | 36 | return envString 37 | } 38 | 39 | func initEnv() { 40 | configPath = envString(envConfigPath, configPath) 41 | } 42 | 43 | func initFlags() { 44 | flag.StringVar(&configPath, clfConfigPath, configPath, "path of all proxy configs") 45 | flag.Parse() 46 | } 47 | 48 | func init() { 49 | initEnv() 50 | initFlags() 51 | } 52 | 53 | func main() { 54 | log.SetPrefix(strconv.Itoa(os.Getpid()) + " ") 55 | log.Println("Loading global config") 56 | err := infrared.LoadGlobalConfig() 57 | if err != nil { 58 | log.Println(err) 59 | return 60 | } 61 | 62 | var cfgs []*infrared.ProxyConfig 63 | outCfgs := make(chan *infrared.ProxyConfig) 64 | 65 | if infrared.Config.UseRedisConfig { 66 | log.Println("Start watching redis for configs") 67 | go func() { 68 | if err := infrared.WatchRedisConfigs(outCfgs); err != nil { 69 | log.Println("Failed watching redis configs; error:", err) 70 | } 71 | }() 72 | 73 | log.Println("Loading proxy configs from redis") 74 | cfgs, err = infrared.LoadProxyConfigsFromRedis() 75 | if err != nil { 76 | log.Printf("Failed loading proxy configs from redis; error: %s", err) 77 | return 78 | } 79 | } else { 80 | log.Printf("Loading proxy configs from %s", configPath) 81 | cfgs, err = infrared.LoadProxyConfigsFromPath(configPath, false) 82 | if err != nil { 83 | log.Printf("Failed loading proxy configs from %s; error: %s", configPath, err) 84 | return 85 | } 86 | 87 | go func() { 88 | if err := infrared.WatchProxyConfigFolder(configPath, outCfgs); err != nil { 89 | log.Println("Failed watching config folder; error:", err) 90 | log.Println("SYSTEM FAILURE: CONFIG WATCHER FAILED") 91 | } 92 | }() 93 | } 94 | 95 | var proxies []*infrared.Proxy 96 | for _, cfg := range cfgs { 97 | proxies = append(proxies, &infrared.Proxy{ 98 | Config: cfg, 99 | }) 100 | } 101 | 102 | gateway := infrared.Gateway{ReceiveProxyProtocol: infrared.Config.ReceiveProxyProtocol} 103 | go func() { 104 | for { 105 | cfg, ok := <-outCfgs 106 | if !ok { 107 | return 108 | } 109 | 110 | proxy := &infrared.Proxy{Config: cfg} 111 | if err := gateway.RegisterProxy(proxy); err != nil { 112 | log.Println("Failed registering proxy; error:", err) 113 | } 114 | } 115 | }() 116 | 117 | if infrared.Config.Tableflip.Enabled { 118 | log.Println("Starting tableflip upgrade listener") 119 | 120 | if _, err := os.Stat(infrared.Config.Tableflip.PIDfile); errors.Is(err, os.ErrNotExist) { 121 | pid := fmt.Sprint(os.Getpid()) 122 | bb := []byte(pid) 123 | err := os.WriteFile(infrared.Config.Tableflip.PIDfile, bb, os.ModePerm) 124 | if err != nil { 125 | log.Printf("Failed to set up PIDfile: %s", err) 126 | return 127 | } 128 | } 129 | 130 | var err error 131 | infrared.Upg, err = tableflip.New(tableflip.Options{ 132 | PIDFile: infrared.Config.Tableflip.PIDfile, 133 | }) 134 | if err != nil { 135 | log.Printf("Failed to set up Tableflip Upgrader: %s", err) 136 | return 137 | } 138 | 139 | go func() { 140 | sig := make(chan os.Signal, 1) 141 | signal.Notify(sig, syscall.SIGHUP) 142 | for range sig { 143 | err := infrared.Upg.Upgrade() 144 | if err != nil { 145 | log.Println("upgrade failed:", err) 146 | } 147 | } 148 | }() 149 | } 150 | 151 | if infrared.Config.Api.Enabled && !infrared.Config.UseRedisConfig { 152 | go api.ListenAndServe(configPath, infrared.Config.Api.Bind) 153 | } 154 | 155 | if infrared.Config.GeoIP.Enabled { 156 | log.Println("Loading GeoIPDB") 157 | err := gateway.LoadDB() 158 | if err != nil { 159 | log.Println(err) 160 | return 161 | } 162 | log.Println("Loading Redis") 163 | err = gateway.ConnectRedis() 164 | if err != nil { 165 | log.Println(err) 166 | return 167 | } 168 | if infrared.Config.MojangAPIenabled { 169 | log.Println("Loading Mojang API instance") 170 | gateway.LoadMojangAPI() 171 | err := gateway.GenerateKeys() 172 | if err != nil { 173 | return 174 | } 175 | } 176 | } 177 | 178 | if infrared.Config.Prometheus.Enabled { 179 | err := gateway.EnablePrometheus(infrared.Config.Prometheus.Bind) 180 | if err != nil { 181 | log.Println(err) 182 | return 183 | } 184 | 185 | if infrared.Config.TrackBandwidth { 186 | go func() { 187 | for { 188 | gateway.TrackBandwith() 189 | } 190 | }() 191 | } 192 | } 193 | 194 | if !infrared.Config.UnderAttack { 195 | go func() { 196 | for { 197 | gateway.ClearCps() 198 | } 199 | }() 200 | } 201 | 202 | log.Println("Starting gateway listeners") 203 | if err := gateway.ListenAndServe(proxies); err != nil { 204 | log.Fatal("Gateway exited; error: ", err) 205 | } 206 | 207 | if infrared.Config.Tableflip.Enabled { 208 | if err := infrared.Upg.Ready(); err != nil { 209 | panic(err) 210 | } 211 | <-infrared.Upg.Exit() 212 | log.Println("Starting tableflip shutdown for old instance") 213 | gateway.Close() 214 | 215 | gateway.WaitConnGroup() 216 | log.Println("Shutting down infrared") 217 | } else { 218 | gateway.KeepProcessActive() 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package infrared 2 | 3 | import ( 4 | "bufio" 5 | "encoding/base64" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "github.com/go-redis/redis/v8" 10 | "golang.org/x/net/context" 11 | "gopkg.in/yaml.v2" 12 | "io/ioutil" 13 | "log" 14 | "net" 15 | "os" 16 | "path/filepath" 17 | "strings" 18 | "sync" 19 | "time" 20 | 21 | "github.com/fsnotify/fsnotify" 22 | "github.com/haveachin/infrared/protocol" 23 | "github.com/haveachin/infrared/protocol/status" 24 | ) 25 | 26 | // ProxyConfig is a data representation of a Proxy configuration 27 | type ProxyConfig struct { 28 | sync.RWMutex 29 | watcher *fsnotify.Watcher 30 | 31 | removeCallback func() 32 | changeCallback func() 33 | dialer *Dialer 34 | 35 | Name string 36 | 37 | DomainNames []string `json:"domainNames"` 38 | ListenTo string `json:"listenTo"` 39 | ProxyTo string `json:"proxyTo"` 40 | ProxyBind string `json:"proxyBind"` 41 | ProxyProtocol bool `json:"proxyProtocol"` 42 | RealIP bool `json:"realIp"` 43 | Timeout int `json:"timeout"` 44 | DisconnectMessage string `json:"disconnectMessage"` 45 | AllowCracked bool `json:"allowCracked"` 46 | OnlineStatus StatusConfig `json:"onlineStatus"` 47 | OfflineStatus StatusConfig `json:"offlineStatus"` 48 | } 49 | 50 | type Redis struct { 51 | Host string `yaml:"host"` 52 | Pass string `yaml:"pass"` 53 | DB int `yaml:"db"` 54 | } 55 | 56 | type Service struct { 57 | Enabled bool `yaml:"enabled"` 58 | Bind string `yaml:"bind"` 59 | Bind2 string `yaml:"bind2"` 60 | } 61 | 62 | type GenericPing struct { 63 | Version string `yaml:"version"` 64 | Description string `yaml:"description"` 65 | IconPath string `yaml:"iconPath"` 66 | } 67 | 68 | type GeoIP struct { 69 | Enabled bool `yaml:"enabled"` 70 | DatabaseFile string `yaml:"databaseFile"` 71 | EnableIprisk bool `yaml:"enableIprisk"` 72 | } 73 | 74 | type Tableflip struct { 75 | Enabled bool `yaml:"enabled"` 76 | PIDfile string `yaml:"pidfile"` 77 | } 78 | 79 | type GlobalConfig struct { 80 | Debug bool `yaml:"debug"` 81 | ReceiveProxyProtocol bool `yaml:"receiveProxyProtocol"` 82 | GenericJoinResponse string `yaml:"genericJoinResponse"` 83 | MojangAPIenabled bool `yaml:"mojangAPIenabled"` 84 | RejoinMessage string `yaml:"rejoinMessage"` 85 | BlockedMessage string `yaml:"blockedMessage"` 86 | UnderAttack bool `yaml:"underAttack"` 87 | ConnectionThreshold uint64 `yaml:"connectionThreshold"` 88 | TrackBandwidth bool `yaml:"trackBandwidth"` 89 | UseRedisConfig bool `yaml:"useRedisConfigs"` 90 | Redis Redis 91 | ConfigRedis Redis 92 | Api Service 93 | Prometheus Service 94 | GeoIP GeoIP 95 | GenericPing GenericPing 96 | Tableflip Tableflip 97 | } 98 | 99 | type redisEvent struct { 100 | Name string `json:"name"` 101 | Config json.RawMessage `json:"config"` 102 | } 103 | 104 | var ( 105 | Config GlobalConfig 106 | rdb *redis.Client 107 | ) 108 | 109 | var DefaultConfig = GlobalConfig{ 110 | Debug: false, 111 | ReceiveProxyProtocol: false, 112 | UseRedisConfig: false, 113 | UnderAttack: false, 114 | ConnectionThreshold: 50, 115 | TrackBandwidth: false, 116 | Prometheus: Service{ 117 | Enabled: false, 118 | Bind: ":9070", 119 | }, 120 | Api: Service{ 121 | Enabled: false, 122 | Bind: ":5000", 123 | }, 124 | MojangAPIenabled: false, 125 | GeoIP: GeoIP{ 126 | Enabled: false, 127 | DatabaseFile: "", 128 | EnableIprisk: false, 129 | }, 130 | Redis: Redis{ 131 | Host: "localhost", 132 | Pass: "", 133 | DB: 0, 134 | }, 135 | ConfigRedis: Redis{ 136 | Host: "localhost", 137 | Pass: "", 138 | DB: 0, 139 | }, 140 | RejoinMessage: "Please rejoin to verify your connection.", 141 | BlockedMessage: "Your ip is blocked for suspicious activity.", 142 | GenericJoinResponse: "There is no proxy associated with this domain. Please check your configuration.", 143 | GenericPing: GenericPing{ 144 | Version: "Infrared", 145 | Description: "There is no proxy associated with this domain. Please check your configuration.", 146 | IconPath: "", 147 | }, 148 | Tableflip: Tableflip{ 149 | Enabled: false, 150 | PIDfile: "", 151 | }, 152 | } 153 | 154 | func (cfg *ProxyConfig) Dialer() (*Dialer, error) { 155 | if cfg.dialer != nil { 156 | return cfg.dialer, nil 157 | } 158 | 159 | cfg.dialer = &Dialer{ 160 | Dialer: net.Dialer{ 161 | Timeout: time.Millisecond * time.Duration(cfg.Timeout), 162 | LocalAddr: &net.TCPAddr{ 163 | IP: net.ParseIP(cfg.ProxyBind), 164 | }, 165 | }, 166 | } 167 | return cfg.dialer, nil 168 | } 169 | 170 | type PlayerSample struct { 171 | Name string `json:"name"` 172 | UUID string `json:"uuid"` 173 | } 174 | 175 | type StatusConfig struct { 176 | cachedPacket *protocol.Packet 177 | 178 | VersionName string `json:"versionName"` 179 | ProtocolNumber int `json:"protocolNumber"` 180 | MaxPlayers int `json:"maxPlayers"` 181 | PlayersOnline int `json:"playersOnline"` 182 | PlayerSamples []PlayerSample `json:"playerSamples"` 183 | IconPath string `json:"iconPath"` 184 | MOTD string `json:"motd"` 185 | } 186 | 187 | func (cfg StatusConfig) StatusResponsePacket() (protocol.Packet, error) { 188 | if cfg.cachedPacket != nil { 189 | return *cfg.cachedPacket, nil 190 | } 191 | 192 | var samples []status.PlayerSampleJSON 193 | for _, sample := range cfg.PlayerSamples { 194 | samples = append(samples, status.PlayerSampleJSON{ 195 | Name: sample.Name, 196 | ID: sample.UUID, 197 | }) 198 | } 199 | 200 | responseJSON := status.ResponseJSON{ 201 | Version: status.VersionJSON{ 202 | Name: cfg.VersionName, 203 | Protocol: cfg.ProtocolNumber, 204 | }, 205 | Players: status.PlayersJSON{ 206 | Max: cfg.MaxPlayers, 207 | Online: cfg.PlayersOnline, 208 | Sample: samples, 209 | }, 210 | Description: json.RawMessage(fmt.Sprintf("{\"text\":\"%s\"}", cfg.MOTD)), 211 | } 212 | 213 | if cfg.IconPath != "" { 214 | img64, err := loadImageAndEncodeToBase64String(cfg.IconPath) 215 | if err != nil { 216 | return protocol.Packet{}, err 217 | } 218 | responseJSON.Favicon = fmt.Sprintf("data:image/png;base64,%s", img64) 219 | } 220 | 221 | bb, err := json.Marshal(responseJSON) 222 | if err != nil { 223 | return protocol.Packet{}, err 224 | } 225 | 226 | packet := status.ClientBoundResponse{ 227 | JSONResponse: protocol.String(bb), 228 | }.Marshal() 229 | 230 | cfg.cachedPacket = &packet 231 | return packet, nil 232 | } 233 | 234 | func loadImageAndEncodeToBase64String(path string) (string, error) { 235 | if path == "" { 236 | return "", nil 237 | } 238 | 239 | imgFile, err := os.Open(path) 240 | if err != nil { 241 | return "", err 242 | } 243 | defer imgFile.Close() 244 | 245 | fileInfo, err := imgFile.Stat() 246 | if err != nil { 247 | return "", err 248 | } 249 | 250 | buffer := make([]byte, fileInfo.Size()) 251 | fileReader := bufio.NewReader(imgFile) 252 | _, err = fileReader.Read(buffer) 253 | if err != nil { 254 | return "", nil 255 | } 256 | 257 | return base64.StdEncoding.EncodeToString(buffer), nil 258 | } 259 | 260 | func DefaultProxyConfig() ProxyConfig { 261 | return ProxyConfig{ 262 | DomainNames: []string{"localhost"}, 263 | ListenTo: ":25565", 264 | Timeout: 1000, 265 | DisconnectMessage: "Sorry {{username}}, but the server is offline.", 266 | OfflineStatus: StatusConfig{ 267 | VersionName: Config.GenericPing.Version, 268 | ProtocolNumber: 757, 269 | MaxPlayers: 20, 270 | MOTD: "Server is currently offline.", 271 | }, 272 | AllowCracked: false, 273 | } 274 | } 275 | 276 | func ReadFilePaths(path string, recursive bool) ([]string, error) { 277 | if recursive { 278 | return readFilePathsRecursively(path) 279 | } 280 | 281 | return readFilePaths(path) 282 | } 283 | 284 | func readFilePathsRecursively(path string) ([]string, error) { 285 | var filePaths []string 286 | 287 | err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { 288 | if err != nil { 289 | return err 290 | } 291 | 292 | if info.IsDir() { 293 | return nil 294 | } 295 | 296 | filePaths = append(filePaths, path) 297 | return nil 298 | }) 299 | 300 | return filePaths, err 301 | } 302 | 303 | func readFilePaths(path string) ([]string, error) { 304 | var filePaths []string 305 | files, err := ioutil.ReadDir(path) 306 | if err != nil { 307 | return nil, err 308 | } 309 | 310 | for _, file := range files { 311 | if file.IsDir() { 312 | continue 313 | } 314 | 315 | filePaths = append(filePaths, filepath.Join(path, file.Name())) 316 | } 317 | 318 | return filePaths, err 319 | } 320 | 321 | func LoadProxyConfigsFromPath(path string, recursive bool) ([]*ProxyConfig, error) { 322 | filePaths, err := ReadFilePaths(path, recursive) 323 | if err != nil { 324 | return nil, err 325 | } 326 | 327 | var cfgs []*ProxyConfig 328 | 329 | for _, filePath := range filePaths { 330 | cfg, err := NewProxyConfigFromPath(filePath) 331 | if err != nil { 332 | return nil, err 333 | } 334 | cfgs = append(cfgs, cfg) 335 | } 336 | 337 | return cfgs, nil 338 | } 339 | 340 | // NewProxyConfigFromPath loads a ProxyConfig from a file path and then starts watching 341 | // it for changes. On change the ProxyConfig will automatically LoadFromPath itself 342 | func NewProxyConfigFromPath(path string) (*ProxyConfig, error) { 343 | log.Println("Loading", path) 344 | 345 | var cfg ProxyConfig 346 | if err := cfg.LoadFromPath(path); err != nil { 347 | return nil, err 348 | } 349 | 350 | watcher, err := fsnotify.NewWatcher() 351 | if err != nil { 352 | return nil, err 353 | } 354 | cfg.watcher = watcher 355 | 356 | go func() { 357 | defer watcher.Close() 358 | log.Printf("Starting to watch %s", path) 359 | cfg.watch(path, time.Millisecond*50) 360 | log.Printf("Stopping to watch %s", path) 361 | }() 362 | 363 | if err := watcher.Add(path); err != nil { 364 | return nil, err 365 | } 366 | 367 | return &cfg, err 368 | } 369 | 370 | func (cfg *ProxyConfig) watch(path string, interval time.Duration) { 371 | // The interval protects the watcher from write event spams 372 | // This is necessary due to how some text editors handle file safes 373 | tick := time.Tick(interval) 374 | var lastEvent *fsnotify.Event 375 | 376 | for { 377 | select { 378 | case <-tick: 379 | if lastEvent == nil { 380 | continue 381 | } 382 | cfg.onConfigWrite(*lastEvent) 383 | lastEvent = nil 384 | case event, ok := <-cfg.watcher.Events: 385 | if !ok { 386 | return 387 | } 388 | if event.Op&fsnotify.Remove == fsnotify.Remove { 389 | cfg.removeCallback() 390 | return 391 | } 392 | if event.Op&fsnotify.Write == fsnotify.Write { 393 | lastEvent = &event 394 | } 395 | case err, ok := <-cfg.watcher.Errors: 396 | if !ok { 397 | return 398 | } 399 | log.Printf("Failed watching %s; error %s", path, err) 400 | } 401 | } 402 | } 403 | 404 | func (cfg *ProxyConfig) onConfigWrite(event fsnotify.Event) { 405 | log.Println("Updating", event.Name) 406 | if err := cfg.LoadFromPath(event.Name); err != nil { 407 | log.Printf("Failed update on %s; error %s", event.Name, err) 408 | return 409 | } 410 | cfg.OnlineStatus.cachedPacket = nil 411 | cfg.OfflineStatus.cachedPacket = nil 412 | cfg.dialer = nil 413 | cfg.changeCallback() 414 | } 415 | 416 | // LoadFromPath loads the ProxyConfig from a file 417 | func (cfg *ProxyConfig) LoadFromPath(path string) error { 418 | cfg.Lock() 419 | defer cfg.Unlock() 420 | 421 | var defaultCfg map[string]interface{} 422 | bb, err := json.Marshal(DefaultProxyConfig()) 423 | if err != nil { 424 | return err 425 | } 426 | 427 | if err := json.Unmarshal(bb, &defaultCfg); err != nil { 428 | return err 429 | } 430 | 431 | bb, err = ioutil.ReadFile(path) 432 | if err != nil { 433 | return err 434 | } 435 | 436 | var loadedCfg map[string]interface{} 437 | if err := json.Unmarshal(bb, &loadedCfg); err != nil { 438 | log.Println(string(bb)) 439 | return err 440 | } 441 | 442 | for k, v := range loadedCfg { 443 | defaultCfg[k] = v 444 | } 445 | 446 | bb, err = json.Marshal(defaultCfg) 447 | if err != nil { 448 | return err 449 | } 450 | 451 | return json.Unmarshal(bb, cfg) 452 | } 453 | 454 | func WatchProxyConfigFolder(path string, out chan *ProxyConfig) error { 455 | watcher, err := fsnotify.NewWatcher() 456 | if err != nil { 457 | return err 458 | } 459 | defer watcher.Close() 460 | 461 | if err := watcher.Add(path); err != nil { 462 | return err 463 | } 464 | 465 | defer close(out) 466 | for { 467 | select { 468 | case event, ok := <-watcher.Events: 469 | if !ok { 470 | return nil 471 | } 472 | if event.Op&fsnotify.Create == fsnotify.Create && filepath.Ext(event.Name) == ".json" { 473 | proxyCfg, err := NewProxyConfigFromPath(event.Name) 474 | if err != nil { 475 | log.Printf("Failed loading %s; error %s", event.Name, err) 476 | continue 477 | } 478 | out <- proxyCfg 479 | } 480 | case err, ok := <-watcher.Errors: 481 | if !ok { 482 | return nil 483 | } 484 | log.Printf("Failed watching %s; error %s", path, err) 485 | } 486 | } 487 | } 488 | 489 | func LoadGlobalConfig() error { 490 | log.Println("Loading config.yml") 491 | ymlFile, err := ioutil.ReadFile("config.yml") 492 | if err != nil { 493 | return err 494 | } 495 | var config = DefaultConfig 496 | err = yaml.Unmarshal(ymlFile, &config) 497 | if err != nil { 498 | return err 499 | } 500 | Config = config 501 | return nil 502 | } 503 | 504 | func DefaultStatusResponse() protocol.Packet { 505 | responseJSON := status.ResponseJSON{ 506 | Version: status.VersionJSON{ 507 | Name: Config.GenericPing.Version, 508 | Protocol: 0, 509 | }, 510 | Players: status.PlayersJSON{ 511 | Max: 0, 512 | Online: 0, 513 | }, 514 | Description: json.RawMessage(fmt.Sprintf("{\"text\":\"%s\"}", Config.GenericPing.Description)), 515 | } 516 | 517 | if Config.GenericPing.IconPath != "" { 518 | img64, err := loadImageAndEncodeToBase64String(Config.GenericPing.IconPath) 519 | if err == nil { 520 | responseJSON.Favicon = fmt.Sprintf("data:image/png;base64,%s", img64) 521 | } 522 | } 523 | 524 | bb, _ := json.Marshal(responseJSON) 525 | 526 | return status.ClientBoundResponse{ 527 | JSONResponse: protocol.String(bb), 528 | }.Marshal() 529 | } 530 | 531 | func LoadProxyConfigsFromRedis() ([]*ProxyConfig, error) { 532 | var cfgs []*ProxyConfig 533 | rcfg := Config.ConfigRedis 534 | 535 | ctx := context.Background() 536 | rdb := redis.NewClient(&redis.Options{ 537 | Addr: rcfg.Host + ":6379", 538 | Password: rcfg.Pass, 539 | DB: rcfg.DB, 540 | }) 541 | _, err := rdb.Ping(ctx).Result() 542 | if err != nil { 543 | return nil, err 544 | } 545 | 546 | defer rdb.Close() 547 | 548 | configList, err := rdb.Keys(ctx, "config:*").Result() 549 | if err != nil { 550 | return nil, err 551 | } 552 | 553 | if len(configList) == 0 { 554 | return nil, errors.New("no configs were found") 555 | } 556 | 557 | for _, element := range configList { 558 | config, err := rdb.Get(ctx, element).Result() 559 | if err != nil { 560 | return nil, err 561 | } 562 | 563 | cfg := DefaultProxyConfig() 564 | 565 | err = json.Unmarshal([]byte(config), &cfg) 566 | if err != nil { 567 | return nil, err 568 | } 569 | 570 | cfg.Name = strings.Split(element, "config:")[1] 571 | go cfg.watchRedis() 572 | 573 | cfgs = append(cfgs, &cfg) 574 | } 575 | 576 | return cfgs, nil 577 | } 578 | 579 | func WatchRedisConfigs(out chan *ProxyConfig) error { 580 | ctx := context.Background() 581 | rcfg := Config.ConfigRedis 582 | rdb = redis.NewClient(&redis.Options{ 583 | Addr: rcfg.Host + ":6379", 584 | Password: rcfg.Pass, 585 | DB: rcfg.DB, 586 | }) 587 | _, err := rdb.Ping(ctx).Result() 588 | if err != nil { 589 | return err 590 | } 591 | 592 | defer rdb.Close() 593 | 594 | subscriber := rdb.Subscribe(ctx, "infrared-add-config") 595 | for { 596 | msg, err := subscriber.ReceiveMessage(ctx) 597 | if err != nil { 598 | return err 599 | } 600 | 601 | var event redisEvent 602 | if err := json.Unmarshal([]byte(msg.Payload), &event); err != nil { 603 | return err 604 | } 605 | 606 | cfg := DefaultProxyConfig() 607 | if err := json.Unmarshal(event.Config, &cfg); err != nil { 608 | return err 609 | } 610 | 611 | cfg.Name = event.Name 612 | 613 | go cfg.watchRedis() 614 | out <- &cfg 615 | } 616 | } 617 | 618 | func (cfg *ProxyConfig) watchRedis() { 619 | ctx := context.Background() 620 | 621 | subscriber := rdb.Subscribe(ctx, "infrared-delete-config") 622 | for { 623 | msg, err := subscriber.ReceiveMessage(ctx) 624 | if err != nil { 625 | log.Println(err) 626 | return 627 | } 628 | 629 | if msg.Payload == cfg.Name { 630 | cfg.removeCallback() 631 | } 632 | } 633 | } 634 | -------------------------------------------------------------------------------- /conn.go: -------------------------------------------------------------------------------- 1 | package infrared 2 | 3 | import ( 4 | "bufio" 5 | "crypto/cipher" 6 | "github.com/haveachin/infrared/protocol" 7 | "io" 8 | "net" 9 | ) 10 | 11 | type PacketWriter interface { 12 | WritePacket(p protocol.Packet) error 13 | } 14 | 15 | type PacketReader interface { 16 | ReadPacket(limit bool) (protocol.Packet, error) 17 | } 18 | 19 | type PacketPeeker interface { 20 | PeekPacket() (protocol.Packet, error) 21 | } 22 | 23 | type PacketCipherer interface { 24 | SetCipher(ecoStream, decoStream cipher.Stream) 25 | } 26 | 27 | type conn struct { 28 | net.Conn 29 | 30 | r *bufio.Reader 31 | w io.Writer 32 | } 33 | 34 | type Listener struct { 35 | net.Listener 36 | } 37 | 38 | func Listen(addr string) (Listener, error) { 39 | if Config.Tableflip.Enabled { 40 | l, err := Upg.Listen("tcp", addr) 41 | return Listener{Listener: l}, err 42 | } 43 | 44 | l, err := net.Listen("tcp", addr) 45 | return Listener{Listener: l}, err 46 | } 47 | 48 | func (l Listener) Accept() (Conn, error) { 49 | conn, err := l.Listener.Accept() 50 | if err != nil { 51 | return nil, err 52 | } 53 | return wrapConn(conn), nil 54 | } 55 | 56 | // Conn is a minecraft Connection 57 | type Conn interface { 58 | net.Conn 59 | PacketWriter 60 | PacketReader 61 | PacketPeeker 62 | PacketCipherer 63 | 64 | CloseForce() error 65 | Reader() *bufio.Reader 66 | } 67 | 68 | // wrapConn warp an net.Conn to infared.conn 69 | func wrapConn(c net.Conn) *conn { 70 | return &conn{ 71 | Conn: c, 72 | r: bufio.NewReader(c), 73 | w: c, 74 | } 75 | } 76 | 77 | type Dialer struct { 78 | net.Dialer 79 | } 80 | 81 | // Dial create a Minecraft connection 82 | func (d Dialer) Dial(addr string) (Conn, error) { 83 | conn, err := d.Dialer.Dial("tcp", addr) 84 | if err != nil { 85 | return nil, err 86 | } 87 | 88 | return wrapConn(conn), nil 89 | } 90 | 91 | func (c *conn) Read(b []byte) (int, error) { 92 | return c.r.Read(b) 93 | } 94 | 95 | func (c *conn) Write(b []byte) (int, error) { 96 | return c.w.Write(b) 97 | } 98 | 99 | // ReadPacket read a Packet from Conn. 100 | func (c *conn) ReadPacket(limit bool) (protocol.Packet, error) { 101 | return protocol.ReadPacket(c.r, limit) 102 | } 103 | 104 | // PeekPacket peeks a Packet from Conn. 105 | func (c *conn) PeekPacket() (protocol.Packet, error) { 106 | return protocol.PeekPacket(c.r) 107 | } 108 | 109 | //WritePacket write a Packet to Conn. 110 | func (c *conn) WritePacket(p protocol.Packet) error { 111 | pk, err := p.Marshal() 112 | if err != nil { 113 | return err 114 | } 115 | _, err = c.w.Write(pk) 116 | return err 117 | } 118 | 119 | // SetCipher sets the decode/encode stream for this Conn 120 | func (c *conn) SetCipher(ecoStream, decoStream cipher.Stream) { 121 | c.r = bufio.NewReader(cipher.StreamReader{ 122 | S: decoStream, 123 | R: c.Conn, 124 | }) 125 | c.w = cipher.StreamWriter{ 126 | S: ecoStream, 127 | W: c.Conn, 128 | } 129 | } 130 | 131 | func (c *conn) CloseForce() error { 132 | err := c.Conn.(*net.TCPConn).SetLinger(0) 133 | if err != nil { 134 | return err 135 | } 136 | err = c.Close() 137 | if err != nil { 138 | return err 139 | } 140 | return nil 141 | } 142 | 143 | func (c *conn) Reader() *bufio.Reader { 144 | return c.r 145 | } 146 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | infrared: 5 | build: "." 6 | container_name: "infrared" 7 | restart: "unless-stopped" 8 | stdin_open: true 9 | tty: true 10 | ports: 11 | - "25565:25565/tcp" 12 | volumes: 13 | - "/usr/local/infrared/configs:/configs" 14 | expose: 15 | - "25565" 16 | environment: 17 | INFRARED_CONFIG_PATH: "/configs" 18 | -------------------------------------------------------------------------------- /gateway.go: -------------------------------------------------------------------------------- 1 | package infrared 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "crypto/aes" 7 | "crypto/rand" 8 | "crypto/rsa" 9 | "crypto/x509" 10 | "encoding/json" 11 | "errors" 12 | "fmt" 13 | "github.com/Lukaesebrot/mojango" 14 | "github.com/asaskevich/govalidator" 15 | "github.com/cloudflare/tableflip" 16 | "github.com/go-redis/redis/v8" 17 | "github.com/gofrs/uuid" 18 | "github.com/haveachin/infrared/protocol" 19 | "github.com/haveachin/infrared/protocol/cfb8" 20 | "github.com/haveachin/infrared/protocol/handshaking" 21 | "github.com/haveachin/infrared/protocol/login" 22 | "github.com/haveachin/infrared/protocol/status" 23 | "github.com/oschwald/geoip2-golang" 24 | "github.com/pires/go-proxyproto" 25 | "github.com/prometheus/client_golang/prometheus" 26 | "github.com/prometheus/client_golang/prometheus/promauto" 27 | "github.com/prometheus/client_golang/prometheus/promhttp" 28 | "io/ioutil" 29 | "log" 30 | "net" 31 | "net/http" 32 | "reflect" 33 | "strconv" 34 | "strings" 35 | "sync" 36 | "sync/atomic" 37 | "time" 38 | ) 39 | 40 | var ( 41 | handshakeCount = promauto.NewCounterVec(prometheus.CounterOpts{ 42 | Name: "infrared_handshakes", 43 | Help: "The total number of handshakes made to each proxy by type", 44 | }, []string{"type", "host", "country"}) 45 | underAttackStatus = promauto.NewGauge(prometheus.GaugeOpts{ 46 | Name: "infrared_underAttack", 47 | Help: "Is the proxy under attack", 48 | }) 49 | usedBandwith = promauto.NewCounterVec(prometheus.CounterOpts{ 50 | Name: "infrared_used_bandwith", 51 | Help: "The total number of used bytes of bandwith per proxy", 52 | }, []string{"host"}) 53 | ctx = context.Background() 54 | Upg *tableflip.Upgrader 55 | ) 56 | 57 | type Gateway struct { 58 | listeners sync.Map 59 | Proxies sync.Map 60 | closed chan bool 61 | wg sync.WaitGroup 62 | conngroup sync.WaitGroup 63 | ReceiveProxyProtocol bool 64 | underAttack bool 65 | connections uint64 66 | db *geoip2.Reader 67 | api *mojango.Client 68 | rdb *redis.Client 69 | publicKey []byte 70 | privateKey *rsa.PrivateKey 71 | } 72 | 73 | type Session struct { 74 | username string 75 | loginPacket protocol.Packet 76 | handshakePacket protocol.Packet 77 | country string 78 | ip string 79 | serverAddress string 80 | connRemoteAddr net.Addr 81 | ProtocolVersion protocol.VarInt 82 | config *ProxyConfig 83 | } 84 | 85 | type iprisk struct { 86 | Datacenter bool `json:"data_center"` 87 | PublicProxy bool `json:"public_proxy"` 88 | TorExitRelay bool `json:"tor_exit_relay"` 89 | } 90 | 91 | func (gateway *Gateway) LoadDB() error { 92 | err := error(nil) 93 | gateway.db, err = geoip2.Open(Config.GeoIP.DatabaseFile) 94 | return err 95 | } 96 | 97 | func (gateway *Gateway) LoadMojangAPI() { 98 | gateway.api = mojango.New() 99 | } 100 | 101 | func (gateway *Gateway) ConnectRedis() error { 102 | gateway.rdb = redis.NewClient(&redis.Options{ 103 | Addr: Config.Redis.Host + ":6379", 104 | Password: Config.Redis.Pass, 105 | DB: Config.Redis.DB, 106 | }) 107 | _, err := gateway.rdb.Ping(ctx).Result() 108 | if err != nil { 109 | return err 110 | } 111 | return nil 112 | } 113 | 114 | func (gateway *Gateway) ListenAndServe(proxies []*Proxy) error { 115 | if len(proxies) <= 0 { 116 | return errors.New("no proxies in gateway") 117 | } 118 | 119 | if Config.UnderAttack { 120 | log.Println("Enabled permanent underAttack mode") 121 | gateway.underAttack = true 122 | underAttackStatus.Set(1) 123 | } 124 | 125 | gateway.closed = make(chan bool, len(proxies)) 126 | 127 | for _, proxy := range proxies { 128 | if err := gateway.RegisterProxy(proxy); err != nil { 129 | gateway.Close() 130 | return err 131 | } 132 | } 133 | 134 | log.Println("All proxies are online") 135 | return nil 136 | } 137 | 138 | func (gateway *Gateway) EnablePrometheus(bind string) error { 139 | gateway.wg.Add(1) 140 | 141 | go func() { 142 | defer gateway.wg.Done() 143 | 144 | http.Handle("/metrics", promhttp.Handler()) 145 | 146 | if Config.Tableflip.Enabled { 147 | var listen net.Listener 148 | var err error 149 | listen, err = net.Listen("tcp", bind) 150 | if err != nil { 151 | if strings.Contains(err.Error(), "bind: address already in use") { 152 | log.Printf("Starting secondary prometheus listener on %s", Config.Prometheus.Bind2) 153 | listen, err = net.Listen("tcp", Config.Prometheus.Bind2) 154 | if err != nil { 155 | log.Printf("Failed to open secondary prometheus listener: %s", err) 156 | return 157 | } 158 | } else { 159 | log.Printf("Failed to open new prometheus listener: %s", err) 160 | return 161 | } 162 | } 163 | http.Serve(listen, nil) 164 | } else { 165 | http.ListenAndServe(bind, nil) 166 | } 167 | }() 168 | 169 | log.Println("Enabling Prometheus metrics endpoint on", bind) 170 | return nil 171 | } 172 | 173 | func (gateway *Gateway) GenerateKeys() error { 174 | privateKey, err := rsa.GenerateKey(rand.Reader, 1024) 175 | if err != nil { 176 | return err 177 | } 178 | gateway.privateKey = privateKey 179 | 180 | gateway.publicKey, err = x509.MarshalPKIXPublicKey(&gateway.privateKey.PublicKey) 181 | if err != nil { 182 | return err 183 | } 184 | return nil 185 | } 186 | 187 | func (gateway *Gateway) KeepProcessActive() { 188 | gateway.wg.Wait() 189 | } 190 | 191 | func (gateway *Gateway) WaitConnGroup() { 192 | gateway.conngroup.Wait() 193 | } 194 | 195 | // Close closes all listeners 196 | func (gateway *Gateway) Close() { 197 | gateway.listeners.Range(func(k, v interface{}) bool { 198 | gateway.closed <- true 199 | _ = v.(Listener).Close() 200 | return false 201 | }) 202 | } 203 | 204 | func (gateway *Gateway) CloseProxy(proxyUID string) { 205 | log.Println("Closing config with UID", proxyUID) 206 | v, ok := gateway.Proxies.Load(proxyUID) 207 | if !ok { 208 | return 209 | } 210 | proxy := v.(*Proxy) 211 | 212 | uids := proxy.UIDs() 213 | for _, uid := range uids { 214 | log.Println("Closing proxy with UID", uid) 215 | gateway.Proxies.Delete(uid) 216 | } 217 | 218 | playersConnected.DeleteLabelValues(proxy.DomainName()) 219 | 220 | closeListener := true 221 | gateway.Proxies.Range(func(k, v interface{}) bool { 222 | otherProxy := v.(*Proxy) 223 | if proxy.ListenTo() == otherProxy.ListenTo() { 224 | closeListener = false 225 | return false 226 | } 227 | return true 228 | }) 229 | 230 | if !closeListener { 231 | return 232 | } 233 | 234 | v, ok = gateway.listeners.Load(proxy.ListenTo()) 235 | if !ok { 236 | return 237 | } 238 | v.(Listener).Close() 239 | } 240 | 241 | func (gateway *Gateway) RegisterProxy(proxy *Proxy) error { 242 | // Register new Proxy 243 | uids := proxy.UIDs() 244 | for _, uid := range uids { 245 | log.Println("Registering proxy with UID", uid) 246 | gateway.Proxies.Store(uid, proxy) 247 | } 248 | proxyUID := proxy.UID() 249 | 250 | proxy.Config.removeCallback = func() { 251 | gateway.CloseProxy(proxyUID) 252 | } 253 | 254 | proxy.Config.changeCallback = func() { 255 | gateway.CloseProxy(proxyUID) 256 | if err := gateway.RegisterProxy(proxy); err != nil { 257 | log.Println(err) 258 | } 259 | } 260 | 261 | playersConnected.WithLabelValues(proxy.DomainName()) 262 | 263 | if Config.TrackBandwidth { 264 | usedBandwith.WithLabelValues(proxy.DomainName()) 265 | } 266 | 267 | // Check if a gate is already listening to the Proxy address 268 | addr := proxy.ListenTo() 269 | if _, ok := gateway.listeners.Load(addr); ok { 270 | return nil 271 | } 272 | 273 | log.Println("Creating listener on", addr) 274 | listener, err := Listen(addr) 275 | if err != nil { 276 | return err 277 | } 278 | gateway.listeners.Store(addr, listener) 279 | 280 | gateway.wg.Add(1) 281 | go func() { 282 | if err := gateway.listenAndServe(listener, addr); err != nil { 283 | log.Printf("Failed to listen on %s; error: %s", proxy.ListenTo(), err) 284 | } 285 | }() 286 | return nil 287 | } 288 | 289 | func (gateway *Gateway) listenAndServe(listener Listener, addr string) error { 290 | defer gateway.wg.Done() 291 | 292 | for { 293 | conn, err := listener.Accept() 294 | if err != nil { 295 | if errors.Is(err, net.ErrClosed) { 296 | log.Println("Closing listener on", addr) 297 | gateway.listeners.Delete(addr) 298 | return nil 299 | } 300 | 301 | continue 302 | } 303 | 304 | go func() { 305 | gateway.conngroup.Add(1) 306 | if Config.Debug { 307 | log.Printf("[>] Incoming %s on listener %s", conn.RemoteAddr(), addr) 308 | } 309 | if gateway.underAttack { 310 | defer conn.CloseForce() 311 | } else { 312 | defer conn.Close() 313 | } 314 | 315 | realip := conn.RemoteAddr() 316 | if gateway.ReceiveProxyProtocol { 317 | header, err := proxyproto.Read(conn.Reader()) 318 | if err != nil { 319 | if Config.Debug { 320 | log.Printf("[e] failed to parse proxyproto for %s: %s", conn.RemoteAddr(), err) 321 | } 322 | return 323 | } 324 | realip = header.SourceAddr 325 | } 326 | 327 | _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) 328 | if err := gateway.serve(conn, addr, realip); err != nil { 329 | if errors.Is(err, protocol.ErrInvalidPacketID) || errors.Is(err, protocol.ErrInvalidPacketLength) { 330 | if Config.GeoIP.Enabled { 331 | ip, _, err := net.SplitHostPort(realip.String()) 332 | if err != nil { 333 | log.Printf("[i] failed to split ip and port for %s: %s", realip, err) 334 | } 335 | 336 | record, err := gateway.db.Country(net.ParseIP(ip)) 337 | if err != nil { 338 | log.Printf("[i] failed to lookup country for %s", realip) 339 | } 340 | handshakeCount.With(prometheus.Labels{"type": "cancelled_invalid", "host": "", "country": record.Country.IsoCode}).Inc() 341 | 342 | err = gateway.rdb.Set(ctx, "ip:"+ip, "false,"+record.Country.IsoCode, time.Hour*12).Err() 343 | } else { 344 | handshakeCount.With(prometheus.Labels{"type": "cancelled_invalid", "host": "", "country": ""}).Inc() 345 | } 346 | } 347 | 348 | if Config.Debug { 349 | log.Printf("[x] %s closed connection with %s; error: %s", realip, addr, err) 350 | } 351 | gateway.conngroup.Done() 352 | return 353 | } 354 | _ = conn.SetDeadline(time.Time{}) 355 | if Config.Debug { 356 | log.Printf("[x] %s closed connection with %s", realip, addr) 357 | } 358 | gateway.conngroup.Done() 359 | }() 360 | } 361 | } 362 | 363 | func (gateway *Gateway) serve(conn Conn, addr string, realip net.Addr) (rerr error) { 364 | defer func() { 365 | if r := recover(); r != nil { 366 | switch x := r.(type) { 367 | case string: 368 | rerr = errors.New(x) 369 | case error: 370 | rerr = x 371 | default: 372 | rerr = errors.New("unknown panic in client handler") 373 | } 374 | } 375 | }() 376 | 377 | atomic.AddUint64(&gateway.connections, 1) 378 | 379 | session := Session{} 380 | 381 | session.connRemoteAddr = realip 382 | 383 | err := error(nil) 384 | session.handshakePacket, err = conn.ReadPacket(true) 385 | if err != nil { 386 | return err 387 | } 388 | 389 | hs, err := handshaking.UnmarshalServerBoundHandshake(session.handshakePacket) 390 | if err != nil { 391 | return err 392 | } 393 | session.ProtocolVersion = hs.ProtocolVersion 394 | 395 | session.serverAddress = strings.ToLower(hs.ParseServerAddress()) 396 | if !govalidator.IsDNSName(session.serverAddress) && !govalidator.IsIP(session.serverAddress) { 397 | return errors.New(session.serverAddress + " is not a valid domain") 398 | } 399 | 400 | proxyUID := proxyUID(session.serverAddress, addr) 401 | if Config.Debug { 402 | log.Printf("[i] %s requests proxy with UID %s", session.connRemoteAddr, proxyUID) 403 | } 404 | 405 | session.ip, _, _ = net.SplitHostPort(session.connRemoteAddr.String()) 406 | 407 | v, ok := gateway.Proxies.Load(proxyUID) 408 | if !ok { 409 | if hs.IsLoginRequest() { 410 | err := gateway.handleUnknown(conn, session, true) 411 | if err != nil { 412 | return err 413 | } 414 | } 415 | err := gateway.handleUnknown(conn, session, false) 416 | if err != nil { 417 | return err 418 | } 419 | } 420 | proxy := v.(*Proxy) 421 | session.config = proxy.Config 422 | 423 | if hs.IsLoginRequest() { 424 | session.loginPacket, err = conn.ReadPacket(true) 425 | if err != nil { 426 | return err 427 | } 428 | 429 | loginStart, err := login.UnmarshalServerBoundLoginStart(session.loginPacket) 430 | if err != nil { 431 | return err 432 | } 433 | 434 | session.username = string(loginStart.Name) 435 | 436 | if Config.GeoIP.Enabled { 437 | err := gateway.geoCheck(conn, &session) 438 | if err != nil { 439 | return err 440 | } 441 | 442 | if Config.MojangAPIenabled && !gateway.underAttack && !session.config.AllowCracked { 443 | err := gateway.usernameCheck(&session) 444 | if err != nil { 445 | return err 446 | } 447 | } 448 | } 449 | handshakeCount.With(prometheus.Labels{"type": "login", "host": session.serverAddress, "country": session.country}).Inc() 450 | _ = conn.SetDeadline(time.Time{}) 451 | if err := proxy.handleLoginConnection(conn, session); err != nil { 452 | return err 453 | } 454 | } 455 | 456 | if hs.IsStatusRequest() { 457 | if Config.GeoIP.Enabled { 458 | record, err := gateway.db.Country(net.ParseIP(session.ip)) 459 | session.country = record.Country.IsoCode 460 | if err != nil { 461 | log.Printf("[i] failed to lookup country for %s", session.connRemoteAddr) 462 | } 463 | } 464 | handshakeCount.With(prometheus.Labels{"type": "status", "host": session.serverAddress, "country": session.country}).Inc() 465 | if err := proxy.handleStatusConnection(conn, session); err != nil { 466 | return err 467 | } 468 | } 469 | return nil 470 | } 471 | 472 | func (gateway *Gateway) handleUnknown(conn Conn, session Session, isLogin bool) error { 473 | if gateway.underAttack { 474 | return errors.New("blocked connection because underAttack") 475 | } 476 | 477 | if Config.GeoIP.Enabled { 478 | record, err := gateway.db.Country(net.ParseIP(session.ip)) 479 | session.country = record.Country.IsoCode 480 | if err != nil { 481 | log.Printf("[i] failed to lookup country for %s", session.connRemoteAddr) 482 | } 483 | } 484 | 485 | if !isLogin { 486 | _, err := conn.ReadPacket(true) 487 | if err != nil { 488 | return err 489 | } 490 | 491 | err = conn.WritePacket(DefaultStatusResponse()) 492 | if err != nil { 493 | return err 494 | } 495 | 496 | pingPacket, err := conn.ReadPacket(true) 497 | if err != nil { 498 | return err 499 | } 500 | 501 | ping, err := status.UnmarshalServerBoundPing(pingPacket) 502 | if err != nil { 503 | return err 504 | } 505 | 506 | err = conn.WritePacket(status.ClientBoundPong{ 507 | Payload: ping.Payload, 508 | }.Marshal()) 509 | if err != nil { 510 | return err 511 | } 512 | 513 | handshakeCount.With(prometheus.Labels{"type": "status", "host": session.serverAddress, "country": session.country}).Inc() 514 | return errors.New("no proxy with domain " + session.serverAddress) 515 | } 516 | 517 | // Client send an invalid address/port; we don't have a v for that address 518 | err := conn.WritePacket(login.ClientBoundDisconnect{ 519 | Reason: protocol.Chat(fmt.Sprintf("{\"text\":\"%s\"}", Config.GenericJoinResponse)), 520 | }.Marshal()) 521 | if err != nil { 522 | log.Println(err) 523 | } 524 | handshakeCount.With(prometheus.Labels{"type": "login", "host": session.serverAddress, "country": session.country}).Inc() 525 | 526 | return errors.New("no proxy with domain " + session.serverAddress) 527 | } 528 | 529 | func (gateway *Gateway) geoCheck(conn Conn, session *Session) error { 530 | result, err := gateway.rdb.Get(ctx, "ip:"+session.ip).Result() 531 | if err == redis.Nil { 532 | record, err := gateway.db.Country(net.ParseIP(session.ip)) 533 | if err != nil { 534 | log.Printf("[i] failed to lookup country for %s", session.connRemoteAddr) 535 | } 536 | session.country = record.Country.IsoCode 537 | 538 | if Config.GeoIP.EnableIprisk { 539 | var client http.Client 540 | 541 | req, err := http.NewRequest(http.MethodGet, "https://beta.iprisk.info/v1/"+session.ip, nil) 542 | if err != nil { 543 | return errors.New("cannot format request to iprisk because of " + err.Error()) 544 | } 545 | req.Header.Set("User-Agent", "github.com/lhridder/infrared") 546 | 547 | res, err := client.Do(req) 548 | if err != nil { 549 | log.Printf("Cannot query iprisk for %s because of %s", session.ip, err.Error()) 550 | return errors.New("cannot query iprisk because of " + err.Error()) 551 | } 552 | 553 | if res.StatusCode != 200 { 554 | log.Printf("Failed to query iprisk for %s, status code %s", session.ip, strconv.Itoa(res.StatusCode)) 555 | return errors.New("failed to query iprisk, error code: " + strconv.Itoa(res.StatusCode)) 556 | } 557 | 558 | body, err := ioutil.ReadAll(res.Body) 559 | if err != nil { 560 | return errors.New("failed to read iprisk response: " + err.Error()) 561 | } 562 | 563 | var iprisk iprisk 564 | err = json.Unmarshal(body, &iprisk) 565 | if err != nil { 566 | return errors.New("failed to unmarshal iprisk response: " + err.Error()) 567 | } 568 | 569 | if iprisk.TorExitRelay || iprisk.PublicProxy { 570 | err := kickBlocked(conn) 571 | if err != nil { 572 | return err 573 | } 574 | handshakeCount.With(prometheus.Labels{"type": "cancelled_ip", "host": session.serverAddress, "country": session.country}).Inc() 575 | 576 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 577 | if err != nil { 578 | log.Println(err) 579 | } 580 | return errors.New("blocked because iprisk tor/proxy") 581 | } 582 | 583 | if iprisk.Datacenter { 584 | if gateway.underAttack { 585 | err := kickBlocked(conn) 586 | if err != nil { 587 | return err 588 | } 589 | handshakeCount.With(prometheus.Labels{"type": "cancelled_ip", "host": session.serverAddress, "country": session.country}).Inc() 590 | 591 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 592 | if err != nil { 593 | log.Println(err) 594 | } 595 | return errors.New("blocked because iprisk datacenter during attack") 596 | } 597 | 598 | if Config.MojangAPIenabled && !session.config.AllowCracked { 599 | err := gateway.loginCheck(conn, session) 600 | if err != nil { 601 | return err 602 | } 603 | } else { 604 | handshakeCount.With(prometheus.Labels{"type": "cancelled", "host": session.serverAddress, "country": session.country}).Inc() 605 | 606 | err := kickRejoin(conn) 607 | if err != nil { 608 | return err 609 | } 610 | 611 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "half,"+session.country, time.Hour*24).Err() 612 | if err != nil { 613 | log.Println(err) 614 | } 615 | 616 | return errors.New("blocked for rejoin (geoip)") 617 | } 618 | } else { 619 | if gateway.underAttack { 620 | if Config.MojangAPIenabled && !session.config.AllowCracked { 621 | err := gateway.loginCheck(conn, session) 622 | if err != nil { 623 | return err 624 | } 625 | } else { 626 | handshakeCount.With(prometheus.Labels{"type": "cancelled", "host": session.serverAddress, "country": session.country}).Inc() 627 | 628 | err := kickRejoin(conn) 629 | if err != nil { 630 | return err 631 | } 632 | 633 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "half,"+session.country, time.Hour*24).Err() 634 | if err != nil { 635 | log.Println(err) 636 | } 637 | 638 | return errors.New("blocked for rejoin (geoip)") 639 | } 640 | } else { 641 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "half,"+session.country, time.Hour*24).Err() 642 | if err != nil { 643 | log.Println(err) 644 | } 645 | } 646 | } 647 | } else { 648 | if gateway.underAttack { 649 | if Config.MojangAPIenabled && !session.config.AllowCracked { 650 | err := gateway.loginCheck(conn, session) 651 | if err != nil { 652 | return err 653 | } 654 | } else { 655 | handshakeCount.With(prometheus.Labels{"type": "cancelled", "host": session.serverAddress, "country": session.country}).Inc() 656 | 657 | err := kickRejoin(conn) 658 | if err != nil { 659 | return err 660 | } 661 | } 662 | } 663 | } 664 | } else { 665 | if err != nil { 666 | if err == redis.ErrClosed { 667 | err := gateway.ConnectRedis() 668 | if err != nil { 669 | return err 670 | } 671 | } else { 672 | return err 673 | } 674 | } 675 | results := strings.Split(result, ",") 676 | session.country = results[1] 677 | 678 | if results[0] == "false" { 679 | err := kickBlocked(conn) 680 | if err != nil { 681 | return err 682 | } 683 | handshakeCount.With(prometheus.Labels{"type": "cancelled_cache", "host": session.serverAddress, "country": session.country}).Inc() 684 | gateway.rdb.TTL(ctx, "ip:"+session.ip).SetVal(time.Hour * 12) 685 | return errors.New("blocked because ip cached as false") 686 | } 687 | 688 | if gateway.underAttack { 689 | if Config.MojangAPIenabled && !session.config.AllowCracked { 690 | err := gateway.loginCheck(conn, session) 691 | if err != nil { 692 | return err 693 | } 694 | } 695 | } 696 | } 697 | return nil 698 | } 699 | 700 | func (gateway *Gateway) usernameCheck(session *Session) error { 701 | _, err := gateway.rdb.Get(ctx, "username:"+session.username).Result() 702 | if err == redis.Nil { 703 | _, err := gateway.api.FetchUUID(session.username) 704 | if err != nil { 705 | if err == mojango.ErrNoContent || err == mojango.ErrTooManyRequests { 706 | handshakeCount.With(prometheus.Labels{"type": "cancelled_name", "host": session.serverAddress, "country": session.country}).Inc() 707 | return errors.New("blocked because name") 708 | } else { 709 | return errors.New("Could not query Mojang: " + err.Error()) 710 | } 711 | } else { 712 | err = gateway.rdb.Set(ctx, "username:"+session.username, "half", time.Hour*12).Err() 713 | if err != nil { 714 | log.Println(err) 715 | } 716 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "half,"+session.country, time.Hour*24).Err() 717 | if err != nil { 718 | log.Println(err) 719 | } 720 | } 721 | } else { 722 | if err != nil { 723 | if err == redis.ErrClosed { 724 | err := gateway.ConnectRedis() 725 | if err != nil { 726 | return err 727 | } 728 | } else { 729 | return err 730 | } 731 | } 732 | gateway.rdb.TTL(ctx, "username:"+session.username).SetVal(time.Hour * 12) 733 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "half,"+session.country, time.Hour*24).Err() 734 | if err != nil { 735 | log.Println(err) 736 | } 737 | } 738 | return nil 739 | } 740 | 741 | func (gateway *Gateway) loginCheck(conn Conn, session *Session) error { 742 | result, err := gateway.rdb.Get(ctx, "ip:"+session.ip).Result() 743 | if err != nil { 744 | if err == redis.ErrClosed { 745 | err := gateway.ConnectRedis() 746 | if err != nil { 747 | return err 748 | } 749 | } else { 750 | return err 751 | } 752 | } 753 | results := strings.Split(result, ",") 754 | if results[0] != "true" { 755 | verifyToken := make([]byte, 4) 756 | if _, err := rand.Read(verifyToken); err != nil { 757 | return err 758 | } 759 | 760 | err = conn.WritePacket(login.ClientBoundEncryptionRequest{ 761 | ServerID: "", 762 | PublicKey: gateway.publicKey, 763 | VerifyToken: verifyToken, 764 | }.Marshal()) 765 | if err != nil { 766 | return err 767 | } 768 | 769 | encryptionResponse, err := conn.ReadPacket(true) 770 | if err != nil { 771 | err := kickBlocked(conn) 772 | if err != nil { 773 | return err 774 | } 775 | handshakeCount.With(prometheus.Labels{"type": "cancelled_encryption", "host": session.serverAddress, "country": session.country}).Inc() 776 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 777 | return errors.New("cannot read encryption response") 778 | } 779 | 780 | encryptionRes, encryptionResNew, err := login.UnmarshalServerBoundEncryptionResponse(encryptionResponse, session.ProtocolVersion) 781 | if err != nil { 782 | err := kickBlocked(conn) 783 | if err != nil { 784 | return err 785 | } 786 | handshakeCount.With(prometheus.Labels{"type": "cancelled_encryption", "host": session.serverAddress, "country": session.country}).Inc() 787 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 788 | return errors.New("cannot parse encryption response") 789 | } 790 | 791 | var decryptedSharedSecret []byte 792 | if !reflect.ValueOf(encryptionResNew).IsZero() { 793 | decryptedSharedSecret, err = gateway.privateKey.Decrypt(rand.Reader, encryptionResNew.SharedSecret, nil) 794 | if err != nil { 795 | err := kickBlocked(conn) 796 | if err != nil { 797 | return err 798 | } 799 | handshakeCount.With(prometheus.Labels{"type": "cancelled_encryption", "host": session.serverAddress, "country": session.country}).Inc() 800 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 801 | return errors.New("failed to decrypt shared secret") 802 | } 803 | //TODO check signature and salt 804 | } else { 805 | decryptedVerifyToken, err := gateway.privateKey.Decrypt(rand.Reader, encryptionRes.VerifyToken, nil) 806 | if err != nil { 807 | err := kickBlocked(conn) 808 | if err != nil { 809 | return err 810 | } 811 | handshakeCount.With(prometheus.Labels{"type": "cancelled_encryption", "host": session.serverAddress, "country": session.country}).Inc() 812 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 813 | return errors.New("failed to decrypt verify token") 814 | } 815 | 816 | if !bytes.Equal(decryptedVerifyToken, verifyToken) { 817 | err := kickBlocked(conn) 818 | if err != nil { 819 | return err 820 | } 821 | handshakeCount.With(prometheus.Labels{"type": "cancelled_encryption", "host": session.serverAddress, "country": session.country}).Inc() 822 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 823 | return errors.New("invalid verify token") 824 | } 825 | 826 | decryptedSharedSecret, err = gateway.privateKey.Decrypt(rand.Reader, encryptionRes.SharedSecret, nil) 827 | if err != nil { 828 | err := kickBlocked(conn) 829 | if err != nil { 830 | return err 831 | } 832 | handshakeCount.With(prometheus.Labels{"type": "cancelled_encryption", "host": session.serverAddress, "country": session.country}).Inc() 833 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 834 | return errors.New("failed to decrypt shared secret") 835 | } 836 | } 837 | 838 | block, err := aes.NewCipher(decryptedSharedSecret) 839 | if err != nil { 840 | return errors.New("failed to start cypher") 841 | } 842 | 843 | notchHash := NewSha1Hash() 844 | notchHash.Update([]byte("")) 845 | notchHash.Update(decryptedSharedSecret) 846 | notchHash.Update(gateway.publicKey) 847 | hash := notchHash.HexDigest() 848 | 849 | url := "https://sessionserver.mojang.com/session/minecraft/hasJoined?username=" + session.username + "&serverId=" + hash 850 | 851 | resp, err := http.Get(url) 852 | if err != nil { 853 | return errors.New("failed to validate player with session server") 854 | } 855 | 856 | if resp.StatusCode != http.StatusOK { 857 | err := kickBlocked(conn) 858 | if err != nil { 859 | return err 860 | } 861 | handshakeCount.With(prometheus.Labels{"type": "cancelled_authentication", "host": session.serverAddress, "country": session.country}).Inc() 862 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 863 | return errors.New("unable to authenticate session " + resp.Status) 864 | } 865 | 866 | var p struct { 867 | ID string `json:"id"` 868 | Name string `json:"name"` 869 | } 870 | 871 | if err := json.NewDecoder(resp.Body).Decode(&p); err != nil { 872 | return errors.New("failed to parse session server response") 873 | } 874 | _ = resp.Body.Close() 875 | 876 | if session.username != p.Name { 877 | err := kickBlocked(conn) 878 | if err != nil { 879 | return err 880 | } 881 | handshakeCount.With(prometheus.Labels{"type": "cancelled_authentication", "host": session.serverAddress, "country": session.country}).Inc() 882 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "false,"+session.country, time.Hour*12).Err() 883 | return errors.New("invalid username: " + session.username + " != " + p.Name) 884 | } 885 | 886 | playerUUID, err := uuid.FromString(p.ID) 887 | if err != nil { 888 | return errors.New("failed to parse player UUID") 889 | } 890 | 891 | conn.SetCipher(cfb8.NewEncrypter(block, decryptedSharedSecret), cfb8.NewDecrypter(block, decryptedSharedSecret)) 892 | 893 | log.Printf("[i] %s finished encryption check with uuid %s", p.Name, playerUUID) 894 | 895 | err = kickRejoin(conn) 896 | if err != nil { 897 | return err 898 | } 899 | 900 | err = gateway.rdb.Set(ctx, "username:"+session.username, "true", time.Hour*12).Err() 901 | if err != nil { 902 | log.Println(err) 903 | } 904 | err = gateway.rdb.Set(ctx, "ip:"+session.ip, "true,"+session.country, time.Hour*24).Err() 905 | if err != nil { 906 | log.Println(err) 907 | } 908 | 909 | handshakeCount.With(prometheus.Labels{"type": "cancelled", "host": session.serverAddress, "country": session.country}).Inc() 910 | return errors.New("blocked for rejoin (auth)") 911 | } 912 | return nil 913 | } 914 | 915 | func (gateway *Gateway) ClearCps() { 916 | if gateway.connections >= Config.ConnectionThreshold { 917 | gateway.underAttack = true 918 | underAttackStatus.Set(1) 919 | log.Printf("[i] Reached connections treshold: %s", strconv.FormatUint(gateway.connections, 10)) 920 | time.Sleep(time.Minute) 921 | } else { 922 | if gateway.underAttack { 923 | log.Printf("[i] Disabled connections treshold: %s", strconv.FormatUint(gateway.connections, 10)) 924 | gateway.underAttack = false 925 | underAttackStatus.Set(0) 926 | } 927 | } 928 | gateway.connections = 0 929 | time.Sleep(time.Second) 930 | } 931 | 932 | func (gateway *Gateway) TrackBandwith() { 933 | gateway.Proxies.Range(func(k, v interface{}) bool { 934 | proxy := v.(*Proxy) 935 | name := proxy.DomainName() 936 | proxy.mu.Lock() 937 | usedBandwith.WithLabelValues(name).Add(float64(proxy.usedBandwith)) 938 | proxy.usedBandwith = 0 939 | proxy.mu.Unlock() 940 | return false 941 | }) 942 | time.Sleep(5 * time.Second) 943 | } 944 | 945 | func kickRejoin(conn Conn) error { 946 | return conn.WritePacket(login.ClientBoundDisconnect{ 947 | Reason: protocol.Chat(fmt.Sprintf("{\"text\":\"%s\"}", Config.RejoinMessage)), 948 | }.Marshal()) 949 | } 950 | 951 | func kickBlocked(conn Conn) error { 952 | return conn.WritePacket(login.ClientBoundDisconnect{ 953 | Reason: protocol.Chat(fmt.Sprintf("{\"text\":\"%s\"}", Config.BlockedMessage)), 954 | }.Marshal()) 955 | } 956 | -------------------------------------------------------------------------------- /gateway_test.go: -------------------------------------------------------------------------------- 1 | package infrared 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net" 7 | "strings" 8 | "sync" 9 | "testing" 10 | 11 | "github.com/haveachin/infrared/protocol" 12 | "github.com/haveachin/infrared/protocol/handshaking" 13 | "github.com/haveachin/infrared/protocol/status" 14 | "github.com/pires/go-proxyproto" 15 | ) 16 | 17 | var serverDomain string = "infrared.gateway" 18 | 19 | type testError struct { 20 | Error error 21 | Message string 22 | } 23 | 24 | func gatewayPort(portEnd int) int { 25 | return 30000 + portEnd 26 | } 27 | 28 | func gatewayAddr(portEnd int) string { 29 | return portToAddr(gatewayPort(portEnd)) 30 | } 31 | 32 | func serverPort(portEnd int) int { 33 | return 20000 + portEnd 34 | } 35 | 36 | func serverAddr(portEnd int) string { 37 | return portToAddr(serverPort(portEnd)) 38 | } 39 | 40 | func dialerPort(portEnd int) int { 41 | return 10000 + portEnd 42 | } 43 | 44 | func portToAddr(port int) string { 45 | return fmt.Sprintf(":%d", port) 46 | } 47 | 48 | func routeVersionName(index int) string { 49 | return fmt.Sprintf("infrared.gateway-%d", index) 50 | } 51 | 52 | func getIpFromAddr(addr net.Addr) string { 53 | return strings.Split(addr.String(), ":")[0] 54 | } 55 | 56 | func proxyConfigWithPortEnd(portEnd int) *ProxyConfig { 57 | serverAddr := serverAddr(portEnd) 58 | gatewayAddr := gatewayAddr(portEnd) 59 | return createBasicProxyConfig(serverDomain, gatewayAddr, serverAddr) 60 | } 61 | 62 | func createBasicProxyConfig(serverDomain, gatewayAddr, serverAddr string) *ProxyConfig { 63 | return &ProxyConfig{ 64 | DomainNames: []string{serverDomain}, 65 | ListenTo: gatewayAddr, 66 | ProxyTo: serverAddr, 67 | } 68 | } 69 | 70 | func createProxyProtocolConfig(portEnd int, proxyproto bool) *ProxyConfig { 71 | config := proxyConfigWithPortEnd(portEnd) 72 | config.ProxyProtocol = proxyproto 73 | return config 74 | } 75 | 76 | func statusHandshakePort(portEnd int) protocol.Packet { 77 | gatewayPort := gatewayPort(portEnd) 78 | return serverHandshake(serverDomain, gatewayPort) 79 | } 80 | 81 | func serverHandshake(domain string, port int) protocol.Packet { 82 | hs := handshaking.ServerBoundHandshake{ 83 | ProtocolVersion: 574, 84 | ServerAddress: protocol.String(domain), 85 | ServerPort: protocol.UnsignedShort(port), 86 | NextState: 1, 87 | } 88 | return hs.Marshal() 89 | } 90 | 91 | func configToProxies(config *ProxyConfig) []*Proxy { 92 | proxyConfigs := make([]*ProxyConfig, 0) 93 | proxyConfigs = append(proxyConfigs, config) 94 | return configsToProxies(proxyConfigs) 95 | } 96 | 97 | func configsToProxies(config []*ProxyConfig) []*Proxy { 98 | var proxies []*Proxy 99 | for _, c := range config { 100 | proxy := &Proxy{Config: c} 101 | proxies = append(proxies, proxy) 102 | } 103 | return proxies 104 | } 105 | 106 | func sendHandshake(conn Conn, pk protocol.Packet) *testError { 107 | if err := conn.WritePacket(pk); err != nil { 108 | return &testError{err, "Can't write handshake"} 109 | } 110 | return nil 111 | } 112 | 113 | func statusPKWithVersion(name string) StatusConfig { 114 | samples := make([]PlayerSample, 0) 115 | return StatusConfig{VersionName: name, ProtocolNumber: 754, 116 | MaxPlayers: 20, PlayersOnline: 0, PlayerSamples: samples, MOTD: "Server MOTD"} 117 | } 118 | 119 | func sendProxyProtocolHeader(rconn Conn) *testError { 120 | header := createProxyProtocolHeader() 121 | if _, err := header.WriteTo(rconn); err != nil { 122 | return &testError{err, "Can't write proxy protocol header"} 123 | } 124 | return nil 125 | } 126 | 127 | var serverVersionName = "Infrared-test-online" 128 | 129 | var onlineStatus = StatusConfig{ 130 | VersionName: "Infrared 1.16.5 Online", 131 | ProtocolNumber: 754, 132 | MaxPlayers: 20, 133 | MOTD: "Powered by Infrared", 134 | } 135 | 136 | var offlineStatus = StatusConfig{ 137 | VersionName: "Infrared 1.16.5 Offline", 138 | ProtocolNumber: 754, 139 | MaxPlayers: 20, 140 | MOTD: "Powered by Infrared", 141 | } 142 | 143 | type statusListenerConfig struct { 144 | id int 145 | addr string 146 | status StatusConfig 147 | } 148 | 149 | func statusListen(c statusListenerConfig, errorCh chan *testError) { 150 | listener, err := Listen(c.addr) 151 | if err != nil { 152 | errorCh <- &testError{err, fmt.Sprintf("Can't listen to %v", c.addr)} 153 | } 154 | 155 | go func() { 156 | defer listener.Close() 157 | for { 158 | conn, err := listener.Accept() 159 | if err != nil { 160 | errorCh <- &testError{err, "Can't accept connection on listener"} 161 | } 162 | pk, err := c.status.StatusResponsePacket() 163 | if err != nil { 164 | errorCh <- &testError{err, "Can't create status response packet"} 165 | } 166 | go func() { 167 | if err := conn.WritePacket(pk); err != nil { 168 | errorCh <- &testError{err, "Can't write status response packet on connection"} 169 | } 170 | }() 171 | } 172 | }() 173 | } 174 | 175 | type statusDialConfig struct { 176 | pk protocol.Packet 177 | gatewayAddr string 178 | dialerPort int 179 | sendProxyProtocolHeader bool 180 | useProxyProtocol bool 181 | } 182 | 183 | func statusDial(c statusDialConfig) (string, *testError) { 184 | var conn Conn 185 | var err error 186 | if c.useProxyProtocol { 187 | conn, err = createConnWithFakeIP(c.dialerPort, c.gatewayAddr) 188 | } else { 189 | conn, err = Dialer{}.Dial(c.gatewayAddr) 190 | } 191 | 192 | if err != nil { 193 | return "", &testError{err, "Can't make a connection with gateway"} 194 | } 195 | defer conn.Close() 196 | 197 | if c.sendProxyProtocolHeader { 198 | if err := sendProxyProtocolHeader(conn); err != nil { 199 | return "", err 200 | } 201 | } 202 | 203 | if err := sendHandshake(conn, c.pk); err != nil { 204 | return "", err 205 | } 206 | 207 | statusPk := status.ServerBoundRequest{}.Marshal() 208 | if err := conn.WritePacket(statusPk); err != nil { 209 | return "", &testError{err, "Can't write status request packet"} 210 | } 211 | 212 | receivedPk, err := conn.ReadPacket() 213 | if err != nil { 214 | return "", &testError{err, "Can't read status reponse packet"} 215 | } 216 | 217 | response, err := status.UnmarshalClientBoundResponse(receivedPk) 218 | if err != nil { 219 | return "", &testError{err, "Can't unmarshal status reponse packet"} 220 | } 221 | 222 | res := &status.ResponseJSON{} 223 | json.Unmarshal([]byte(response.JSONResponse), &res) 224 | return res.Version.Name, nil 225 | } 226 | 227 | func createConnWithFakeIP(dialerPort int, gatewayAddr string) (Conn, error) { 228 | dialer := &net.Dialer{ 229 | LocalAddr: &net.TCPAddr{ 230 | IP: net.ParseIP("127.0.0.1"), 231 | Port: dialerPort, 232 | }, 233 | } 234 | netConn, err := dialer.Dial("tcp", gatewayAddr) 235 | if err != nil { 236 | return nil, err 237 | } 238 | return wrapConn(netConn), nil 239 | } 240 | 241 | func createProxyProtocolHeader() proxyproto.Header { 242 | return proxyproto.Header{ 243 | Version: 2, 244 | Command: proxyproto.PROXY, 245 | TransportProtocol: proxyproto.TCPv4, 246 | SourceAddr: &net.TCPAddr{ 247 | IP: net.ParseIP("109.226.143.210"), 248 | Port: 0, 249 | }, 250 | DestinationAddr: &net.TCPAddr{ 251 | IP: net.ParseIP("210.223.216.109"), 252 | Port: 0, 253 | }, 254 | } 255 | } 256 | 257 | func proxyProtoListen(portEnd int) (string, *testError) { 258 | listenAddr := serverAddr(portEnd) 259 | listener, err := Listen(listenAddr) 260 | if err != nil { 261 | return "", &testError{err, fmt.Sprintf("Can't listen to %v", listenAddr)} 262 | } 263 | defer listener.Close() 264 | 265 | proxyListener := &proxyproto.Listener{Listener: listener.Listener} 266 | defer proxyListener.Close() 267 | 268 | conn, err := proxyListener.Accept() 269 | if err != nil { 270 | return "", &testError{err, "Can't accept connection on listener"} 271 | } 272 | defer conn.Close() 273 | return getIpFromAddr(conn.RemoteAddr()), nil 274 | } 275 | 276 | func TestStatusRequest(t *testing.T) { 277 | tt := []struct { 278 | name string 279 | portEnd int 280 | onlineStatus StatusConfig 281 | offlineStatus StatusConfig 282 | activeServer bool 283 | expectedVersion string 284 | }{ 285 | { 286 | name: "ServerOnlineWithoutConfig", 287 | portEnd: 570, 288 | activeServer: true, 289 | expectedVersion: serverVersionName, 290 | }, 291 | { 292 | name: "ServerOfflineWithoutConfig", 293 | portEnd: 571, 294 | activeServer: false, 295 | expectedVersion: "", 296 | }, 297 | { 298 | name: "ServerOnlineWithConfig", 299 | portEnd: 572, 300 | onlineStatus: onlineStatus, 301 | offlineStatus: offlineStatus, 302 | activeServer: true, 303 | expectedVersion: onlineStatus.VersionName, 304 | }, 305 | { 306 | name: "ServerOfflineWithConfig", 307 | portEnd: 573, 308 | onlineStatus: onlineStatus, 309 | offlineStatus: offlineStatus, 310 | activeServer: false, 311 | expectedVersion: offlineStatus.VersionName, 312 | }, 313 | } 314 | 315 | for _, tc := range tt { 316 | t.Run(tc.name, func(t *testing.T) { 317 | wg := &sync.WaitGroup{} 318 | errorCh := make(chan *testError) 319 | resultCh := make(chan bool) 320 | wg.Add(1) 321 | go func(wg *sync.WaitGroup) { 322 | config := proxyConfigWithPortEnd(tc.portEnd) 323 | config.OnlineStatus = tc.onlineStatus 324 | config.OfflineStatus = tc.offlineStatus 325 | 326 | gateway := Gateway{} 327 | proxies := configToProxies(config) 328 | if err := gateway.ListenAndServe(proxies); err != nil { 329 | errorCh <- &testError{err, "Can't start gateway"} 330 | } 331 | wg.Done() 332 | gateway.KeepProcessActive() 333 | }(wg) 334 | 335 | if tc.activeServer { 336 | wg.Add(1) 337 | serverCfg := statusListenerConfig{} 338 | serverCfg.status = statusPKWithVersion(serverVersionName) 339 | serverCfg.addr = serverAddr(tc.portEnd) 340 | go func() { 341 | statusListen(serverCfg, errorCh) 342 | wg.Done() 343 | }() 344 | } 345 | 346 | wg.Wait() 347 | go func() { 348 | pk := statusHandshakePort(tc.portEnd) 349 | config := statusDialConfig{ 350 | pk: pk, 351 | gatewayAddr: gatewayAddr(tc.portEnd), 352 | dialerPort: dialerPort(tc.portEnd), 353 | } 354 | receivedVersion, err := statusDial(config) 355 | if err != nil { 356 | errorCh <- err 357 | return 358 | } 359 | 360 | resultCh <- receivedVersion == tc.expectedVersion 361 | }() 362 | 363 | select { 364 | case err := <-errorCh: 365 | t.Fatalf("Unexpected Error in test: %s\n%v", err.Message, err.Error) 366 | case r := <-resultCh: 367 | if !r { 368 | t.Fail() 369 | } 370 | } 371 | }) 372 | } 373 | } 374 | 375 | func TestProxyProtocol(t *testing.T) { 376 | tt := []struct { 377 | name string 378 | proxyproto bool 379 | receiveProxyproto bool 380 | portEnd int 381 | shouldMatch bool 382 | expectingIp string 383 | }{ 384 | { 385 | name: "ProxyProtocolOn", 386 | proxyproto: true, 387 | receiveProxyproto: false, 388 | portEnd: 581, 389 | shouldMatch: true, 390 | expectingIp: "127.0.0.1", 391 | }, 392 | { 393 | name: "ProxyProtocolOff", 394 | proxyproto: false, 395 | receiveProxyproto: false, 396 | portEnd: 582, 397 | shouldMatch: true, 398 | expectingIp: "127.0.0.1", 399 | }, 400 | { 401 | name: "ProxyProtocol Receive", 402 | proxyproto: true, 403 | receiveProxyproto: true, 404 | portEnd: 583, 405 | shouldMatch: true, 406 | expectingIp: "109.226.143.210", 407 | }, 408 | } 409 | 410 | for _, tc := range tt { 411 | t.Run(tc.name, func(t *testing.T) { 412 | errorCh := make(chan *testError) 413 | resultCh := make(chan bool) 414 | wg := &sync.WaitGroup{} 415 | 416 | wg.Add(1) 417 | go func(wg *sync.WaitGroup) { 418 | config := createProxyProtocolConfig(tc.portEnd, tc.proxyproto) 419 | gateway := Gateway{ 420 | ReceiveProxyProtocol: tc.receiveProxyproto, 421 | } 422 | proxies := configToProxies(config) 423 | if err := gateway.ListenAndServe(proxies); err != nil { 424 | errorCh <- &testError{err, "Can't start gateway"} 425 | } 426 | wg.Done() 427 | gateway.KeepProcessActive() 428 | }(wg) 429 | 430 | go func() { 431 | ip, err := proxyProtoListen(tc.portEnd) 432 | if err != nil { 433 | errorCh <- err 434 | return 435 | } 436 | resultCh <- ip == tc.expectingIp 437 | }() 438 | wg.Wait() 439 | go func() { 440 | 441 | pk := statusHandshakePort(tc.portEnd) 442 | config := statusDialConfig{ 443 | pk: pk, 444 | gatewayAddr: gatewayAddr(tc.portEnd), 445 | dialerPort: dialerPort(tc.portEnd), 446 | useProxyProtocol: tc.proxyproto, 447 | sendProxyProtocolHeader: tc.receiveProxyproto, 448 | } 449 | 450 | _, err := statusDial(config) 451 | if err != nil { 452 | errorCh <- err 453 | } 454 | }() 455 | 456 | select { 457 | case err := <-errorCh: 458 | t.Fatalf("Unexpected Error in test: %s\n%v", err.Message, err.Error) 459 | case r := <-resultCh: 460 | if r != tc.shouldMatch { 461 | t.Errorf("got: %v; want: %v", r, tc.shouldMatch) 462 | } 463 | } 464 | 465 | }) 466 | } 467 | } 468 | 469 | func TestRouting(t *testing.T) { 470 | wg := &sync.WaitGroup{} 471 | errorCh := make(chan *testError) 472 | 473 | basePort := 540 474 | routingConfig := make([]*ProxyConfig, 0) 475 | serverConfigs := make([]statusListenerConfig, 0) 476 | 477 | servers := []struct { 478 | id int 479 | domain string 480 | portEnd int 481 | }{ 482 | { 483 | id: 0, 484 | domain: "infrared", 485 | portEnd: 530, 486 | }, 487 | { 488 | id: 9, 489 | domain: "infrared", 490 | portEnd: 531, 491 | }, 492 | { 493 | id: 1, 494 | domain: "infrared-dash", 495 | portEnd: 530, 496 | }, 497 | { 498 | id: 2, 499 | domain: ".dottedInfrared.", 500 | portEnd: 530, 501 | }, 502 | } 503 | 504 | tt := []struct { 505 | name string 506 | expectedId int 507 | requestDomain string 508 | portEnd int 509 | expectError bool 510 | shouldMatch bool 511 | }{ 512 | { 513 | name: "Single word domain", 514 | expectedId: 0, 515 | requestDomain: "infrared", 516 | portEnd: 530, 517 | expectError: false, 518 | shouldMatch: true, 519 | }, 520 | { 521 | name: "Single word domain but wrong id", 522 | expectedId: 1, 523 | requestDomain: "infrared", 524 | portEnd: 530, 525 | expectError: false, 526 | shouldMatch: false, 527 | }, 528 | { 529 | name: "duplicated domain but other port", 530 | expectedId: 9, 531 | requestDomain: "infrared", 532 | portEnd: 531, 533 | expectError: false, 534 | shouldMatch: true, 535 | }, 536 | { 537 | name: "Domain with a dash", 538 | expectedId: 1, 539 | requestDomain: "infrared-dash", 540 | portEnd: 530, 541 | expectError: false, 542 | shouldMatch: true, 543 | }, 544 | { 545 | name: "Domain with points at both ends", 546 | expectedId: 2, 547 | requestDomain: ".dottedInfrared.", 548 | portEnd: 530, 549 | expectError: true, 550 | shouldMatch: false, 551 | }, 552 | } 553 | 554 | for i, server := range servers { 555 | port := basePort + i 556 | proxyC := &ProxyConfig{} 557 | serverC := statusListenerConfig{} 558 | 559 | serverAddr := serverAddr(port) 560 | proxyC.ListenTo = gatewayAddr(server.portEnd) 561 | proxyC.ProxyTo = serverAddr 562 | proxyC.DomainNames = []string{server.domain} 563 | routingConfig = append(routingConfig, proxyC) 564 | 565 | serverC.id = server.id 566 | serverC.addr = serverAddr 567 | serverC.status = statusPKWithVersion(routeVersionName(server.id)) 568 | serverConfigs = append(serverConfigs, serverC) 569 | } 570 | 571 | wg.Add(1) 572 | go func() { 573 | gateway := Gateway{} 574 | proxies := configsToProxies(routingConfig) 575 | if err := gateway.ListenAndServe(proxies); err != nil { 576 | errorCh <- &testError{err, "Can't start gateway"} 577 | } 578 | wg.Done() 579 | gateway.KeepProcessActive() 580 | }() 581 | 582 | for _, c := range serverConfigs { 583 | wg.Add(1) 584 | go func(config statusListenerConfig) { 585 | statusListen(config, errorCh) 586 | wg.Done() 587 | }(c) 588 | } 589 | 590 | wg.Wait() 591 | 592 | select { 593 | case err := <-errorCh: 594 | t.Fatalf("Unexpected Error before tests: %s\n%v", err.Message, err.Error) 595 | default: 596 | } 597 | 598 | for _, tc := range tt { 599 | t.Run(tc.name, func(t *testing.T) { 600 | resultCh := make(chan bool) 601 | 602 | go func() { 603 | expectedName := routeVersionName(tc.expectedId) 604 | pk := serverHandshake(tc.requestDomain, tc.portEnd) 605 | config := statusDialConfig{ 606 | pk: pk, 607 | gatewayAddr: gatewayAddr(tc.portEnd), 608 | dialerPort: dialerPort(tc.portEnd), 609 | } 610 | 611 | receivedVersion, err := statusDial(config) 612 | if err != nil { 613 | errorCh <- err 614 | return 615 | } 616 | resultCh <- receivedVersion == expectedName 617 | }() 618 | 619 | select { 620 | case err := <-errorCh: 621 | if !tc.expectError { 622 | t.Fatalf("Unexpected Error in test: %s\n%v", err.Message, err.Error) 623 | } 624 | case r := <-resultCh: 625 | if r != tc.shouldMatch { 626 | t.Fail() 627 | } 628 | } 629 | }) 630 | } 631 | } 632 | 633 | func TestProxyBind(t *testing.T) { 634 | // TODO: Figure out a way to test this 635 | } 636 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/haveachin/infrared 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/Lukaesebrot/mojango v0.0.0-20200623100037-76cbec69139f 7 | github.com/Microsoft/go-winio v0.4.16 // indirect 8 | github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d 9 | github.com/cloudflare/tableflip v1.2.3 10 | github.com/containerd/containerd v1.4.3 // indirect 11 | github.com/docker/distribution v2.7.1+incompatible // indirect 12 | github.com/docker/docker v20.10.3+incompatible 13 | github.com/docker/go-connections v0.4.0 // indirect 14 | github.com/docker/go-units v0.4.0 // indirect 15 | github.com/fsnotify/fsnotify v1.4.9 16 | github.com/go-redis/redis/v8 v8.11.4 17 | github.com/gofrs/uuid v4.0.0+incompatible 18 | github.com/gogo/protobuf v1.3.2 // indirect 19 | github.com/gorilla/mux v1.8.0 20 | github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect 21 | github.com/morikuni/aec v1.0.0 // indirect 22 | github.com/opencontainers/go-digest v1.0.0 // indirect 23 | github.com/opencontainers/image-spec v1.0.1 // indirect 24 | github.com/oschwald/geoip2-golang v1.6.1 25 | github.com/pires/go-proxyproto v0.6.1 26 | github.com/prometheus/client_golang v1.10.0 27 | github.com/sirupsen/logrus v1.7.0 // indirect 28 | golang.org/x/net v0.0.0-20210428140749-89ef3d95e781 29 | golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect 30 | google.golang.org/grpc v1.35.0 // indirect 31 | gopkg.in/yaml.v2 v2.4.0 32 | gotest.tools/v3 v3.0.3 // indirect 33 | ) 34 | -------------------------------------------------------------------------------- /grafana/README.md: -------------------------------------------------------------------------------- 1 | # Grafana Dashboard 2 | We provide a Grafana dashboard that visualizes the infrared prometheus exporters metrics. You can see all values per instance or globally across all instances. 3 | 4 | ## Prerequisites 5 | 6 | * Infrared >= 1.1.0 with `-enable-prometheus` active 7 | * Grafana >= 7.0.0 8 | * Prometheus >= 2.0.0 9 | * [Pie Chart plugin](https://grafana.com/grafana/plugins/grafana-piechart-panel/) 10 | 11 | A Prometheus data source needs to be [added](https://prometheus.io/docs/visualization/grafana/#using) before installing the dashboard. 12 | 13 | ## Installing the Dashboard 14 | 15 | In the Grafana UI complete the following steps: 16 | 17 | 1. Use the *New Dashboard* button and click *Import*. 18 | 2. Upload `dashboard.json` or copy and paste the contents of the file in the textbox and click *Load*. 19 | 3. You can change the name and folder and click *Import*. 20 | 4. The dashboard will appear. Under *Dashboard settings*, *Variables* and *instance* you can choose your Data source and click 'Update' to refresh the list of instances. 21 | 22 | ![dashboard](./dashboard.png) 23 | 24 | ## Graphs 25 | 26 | The dashboard comes with 2 rows with the following graphs: 27 | 28 | * Individual 29 | * Total and average player count per instance. 30 | * Amount of active proxies. 31 | * Player distribution pie chart ([Pie Chart plugin](https://grafana.com/grafana/plugins/grafana-piechart-panel/) required). 32 | * Player distribution graph. 33 | * Global 34 | * Total and average player count for all instances. 35 | * Amount of active proxies on all instances. 36 | * Player distribution pie chart ([Pie Chart plugin](https://grafana.com/grafana/plugins/grafana-piechart-panel/) required). 37 | * Instance distribution pie chart ([Pie Chart plugin](https://grafana.com/grafana/plugins/grafana-piechart-panel/) required). 38 | * Player distribution graph. -------------------------------------------------------------------------------- /grafana/dashboard.json: -------------------------------------------------------------------------------- 1 | { 2 | "annotations": { 3 | "list": [ 4 | { 5 | "$$hashKey": "object:1058", 6 | "builtIn": 1, 7 | "datasource": "-- Grafana --", 8 | "enable": true, 9 | "hide": true, 10 | "iconColor": "rgba(0, 211, 255, 1)", 11 | "limit": 100, 12 | "name": "Annotations & Alerts", 13 | "showIn": 0, 14 | "type": "dashboard" 15 | } 16 | ] 17 | }, 18 | "description": "", 19 | "editable": true, 20 | "gnetId": 1860, 21 | "graphTooltip": 0, 22 | "id": 10, 23 | "iteration": 1622370959805, 24 | "links": [], 25 | "panels": [ 26 | { 27 | "collapsed": false, 28 | "datasource": null, 29 | "gridPos": { 30 | "h": 1, 31 | "w": 24, 32 | "x": 0, 33 | "y": 0 34 | }, 35 | "id": 367, 36 | "panels": [], 37 | "title": "Individual", 38 | "type": "row" 39 | }, 40 | { 41 | "datasource": null, 42 | "fieldConfig": { 43 | "defaults": { 44 | "color": { 45 | "fixedColor": "green", 46 | "mode": "fixed" 47 | }, 48 | "custom": {}, 49 | "mappings": [], 50 | "thresholds": { 51 | "mode": "absolute", 52 | "steps": [ 53 | { 54 | "color": "green", 55 | "value": null 56 | } 57 | ] 58 | } 59 | }, 60 | "overrides": [] 61 | }, 62 | "gridPos": { 63 | "h": 7, 64 | "w": 4, 65 | "x": 0, 66 | "y": 1 67 | }, 68 | "id": 369, 69 | "options": { 70 | "colorMode": "value", 71 | "graphMode": "area", 72 | "justifyMode": "auto", 73 | "orientation": "auto", 74 | "reduceOptions": { 75 | "calcs": [ 76 | "lastNotNull" 77 | ], 78 | "fields": "", 79 | "values": false 80 | }, 81 | "text": {}, 82 | "textMode": "auto" 83 | }, 84 | "pluginVersion": "7.4.2", 85 | "targets": [ 86 | { 87 | "expr": "sum(infrared_connected{instance=\"$instance\"})", 88 | "interval": "", 89 | "legendFormat": "Total", 90 | "refId": "A" 91 | }, 92 | { 93 | "expr": "sum(avg_over_time(infrared_connected{instance=\"$instance\"}[${__range_s}s]))", 94 | "hide": false, 95 | "interval": "", 96 | "legendFormat": "Average", 97 | "refId": "B" 98 | } 99 | ], 100 | "title": "Players", 101 | "type": "stat" 102 | }, 103 | { 104 | "aliasColors": {}, 105 | "breakPoint": "50%", 106 | "cacheTimeout": null, 107 | "combine": { 108 | "label": "Others", 109 | "threshold": 0 110 | }, 111 | "datasource": null, 112 | "fieldConfig": { 113 | "defaults": { 114 | "custom": {} 115 | }, 116 | "overrides": [] 117 | }, 118 | "fontSize": "80%", 119 | "format": "short", 120 | "gridPos": { 121 | "h": 13, 122 | "w": 5, 123 | "x": 4, 124 | "y": 1 125 | }, 126 | "id": 370, 127 | "interval": null, 128 | "legend": { 129 | "percentage": true, 130 | "percentageDecimals": 1, 131 | "show": true, 132 | "values": true 133 | }, 134 | "legendType": "Under graph", 135 | "links": [], 136 | "nullPointMode": "connected", 137 | "pieType": "pie", 138 | "pluginVersion": "7.4.2", 139 | "strokeWidth": 1, 140 | "targets": [ 141 | { 142 | "expr": "sum by (host)(infrared_connected{instance=\"$instance\"})", 143 | "interval": "", 144 | "legendFormat": "{{host}}", 145 | "refId": "A" 146 | } 147 | ], 148 | "title": "Player Distribution", 149 | "type": "grafana-piechart-panel", 150 | "valueName": "current" 151 | }, 152 | { 153 | "aliasColors": {}, 154 | "bars": false, 155 | "dashLength": 10, 156 | "dashes": false, 157 | "datasource": null, 158 | "fieldConfig": { 159 | "defaults": { 160 | "color": {}, 161 | "custom": {}, 162 | "thresholds": { 163 | "mode": "absolute", 164 | "steps": [] 165 | } 166 | }, 167 | "overrides": [] 168 | }, 169 | "fill": 1, 170 | "fillGradient": 0, 171 | "gridPos": { 172 | "h": 13, 173 | "w": 15, 174 | "x": 9, 175 | "y": 1 176 | }, 177 | "hiddenSeries": false, 178 | "id": 371, 179 | "legend": { 180 | "alignAsTable": true, 181 | "avg": true, 182 | "current": true, 183 | "hideEmpty": false, 184 | "max": true, 185 | "min": true, 186 | "show": true, 187 | "total": false, 188 | "values": true 189 | }, 190 | "lines": true, 191 | "linewidth": 1, 192 | "nullPointMode": "null", 193 | "options": { 194 | "alertThreshold": true 195 | }, 196 | "percentage": false, 197 | "pluginVersion": "7.4.2", 198 | "pointradius": 2, 199 | "points": false, 200 | "renderer": "flot", 201 | "seriesOverrides": [], 202 | "spaceLength": 10, 203 | "stack": false, 204 | "steppedLine": false, 205 | "targets": [ 206 | { 207 | "expr": "sum by (host)(infrared_connected{instance=\"$instance\"})", 208 | "interval": "", 209 | "legendFormat": "{{host}}", 210 | "refId": "A" 211 | }, 212 | { 213 | "expr": "sum(infrared_connected)", 214 | "hide": false, 215 | "interval": "", 216 | "legendFormat": "Total", 217 | "refId": "B" 218 | } 219 | ], 220 | "thresholds": [], 221 | "timeFrom": null, 222 | "timeRegions": [], 223 | "timeShift": null, 224 | "title": "Players", 225 | "tooltip": { 226 | "shared": true, 227 | "sort": 2, 228 | "value_type": "individual" 229 | }, 230 | "type": "graph", 231 | "xaxis": { 232 | "buckets": null, 233 | "mode": "time", 234 | "name": null, 235 | "show": true, 236 | "values": [] 237 | }, 238 | "yaxes": [ 239 | { 240 | "$$hashKey": "object:272", 241 | "format": "short", 242 | "label": null, 243 | "logBase": 1, 244 | "max": null, 245 | "min": "0", 246 | "show": true 247 | }, 248 | { 249 | "$$hashKey": "object:273", 250 | "format": "short", 251 | "label": null, 252 | "logBase": 1, 253 | "max": null, 254 | "min": null, 255 | "show": true 256 | } 257 | ], 258 | "yaxis": { 259 | "align": false, 260 | "alignLevel": null 261 | } 262 | }, 263 | { 264 | "datasource": null, 265 | "fieldConfig": { 266 | "defaults": { 267 | "color": { 268 | "mode": "thresholds" 269 | }, 270 | "custom": {}, 271 | "mappings": [], 272 | "thresholds": { 273 | "mode": "absolute", 274 | "steps": [ 275 | { 276 | "color": "green", 277 | "value": null 278 | }, 279 | { 280 | "color": "red", 281 | "value": 80 282 | } 283 | ] 284 | } 285 | }, 286 | "overrides": [] 287 | }, 288 | "gridPos": { 289 | "h": 6, 290 | "w": 4, 291 | "x": 0, 292 | "y": 8 293 | }, 294 | "id": 368, 295 | "options": { 296 | "colorMode": "value", 297 | "graphMode": "area", 298 | "justifyMode": "auto", 299 | "orientation": "auto", 300 | "reduceOptions": { 301 | "calcs": [ 302 | "lastNotNull" 303 | ], 304 | "fields": "", 305 | "values": false 306 | }, 307 | "text": {}, 308 | "textMode": "auto" 309 | }, 310 | "pluginVersion": "7.4.2", 311 | "targets": [ 312 | { 313 | "expr": "sum(infrared_proxies{instance=\"$instance\"})", 314 | "interval": "", 315 | "legendFormat": "", 316 | "refId": "A" 317 | } 318 | ], 319 | "title": "Proxies", 320 | "type": "stat" 321 | }, 322 | { 323 | "collapsed": false, 324 | "datasource": null, 325 | "gridPos": { 326 | "h": 1, 327 | "w": 24, 328 | "x": 0, 329 | "y": 14 330 | }, 331 | "id": 364, 332 | "panels": [], 333 | "title": "Global", 334 | "type": "row" 335 | }, 336 | { 337 | "datasource": null, 338 | "fieldConfig": { 339 | "defaults": { 340 | "color": { 341 | "mode": "thresholds" 342 | }, 343 | "custom": {}, 344 | "mappings": [], 345 | "thresholds": { 346 | "mode": "absolute", 347 | "steps": [ 348 | { 349 | "color": "green", 350 | "value": null 351 | }, 352 | { 353 | "color": "red", 354 | "value": 80 355 | } 356 | ] 357 | } 358 | }, 359 | "overrides": [] 360 | }, 361 | "gridPos": { 362 | "h": 7, 363 | "w": 3, 364 | "x": 0, 365 | "y": 15 366 | }, 367 | "id": 357, 368 | "options": { 369 | "colorMode": "value", 370 | "graphMode": "area", 371 | "justifyMode": "auto", 372 | "orientation": "auto", 373 | "reduceOptions": { 374 | "calcs": [ 375 | "lastNotNull" 376 | ], 377 | "fields": "", 378 | "values": false 379 | }, 380 | "text": {}, 381 | "textMode": "auto" 382 | }, 383 | "pluginVersion": "7.4.2", 384 | "targets": [ 385 | { 386 | "expr": "sum(infrared_proxies)", 387 | "interval": "", 388 | "legendFormat": "", 389 | "refId": "A" 390 | } 391 | ], 392 | "title": "Total Proxies", 393 | "type": "stat" 394 | }, 395 | { 396 | "datasource": null, 397 | "fieldConfig": { 398 | "defaults": { 399 | "color": { 400 | "fixedColor": "green", 401 | "mode": "fixed" 402 | }, 403 | "custom": {}, 404 | "mappings": [], 405 | "thresholds": { 406 | "mode": "absolute", 407 | "steps": [ 408 | { 409 | "color": "green", 410 | "value": null 411 | } 412 | ] 413 | } 414 | }, 415 | "overrides": [] 416 | }, 417 | "gridPos": { 418 | "h": 7, 419 | "w": 6, 420 | "x": 3, 421 | "y": 15 422 | }, 423 | "id": 360, 424 | "options": { 425 | "colorMode": "value", 426 | "graphMode": "area", 427 | "justifyMode": "auto", 428 | "orientation": "auto", 429 | "reduceOptions": { 430 | "calcs": [ 431 | "lastNotNull" 432 | ], 433 | "fields": "", 434 | "values": false 435 | }, 436 | "text": {}, 437 | "textMode": "auto" 438 | }, 439 | "pluginVersion": "7.4.2", 440 | "targets": [ 441 | { 442 | "expr": "sum(infrared_connected)", 443 | "interval": "", 444 | "legendFormat": "Total", 445 | "refId": "A" 446 | }, 447 | { 448 | "expr": "sum(avg_over_time(infrared_connected[${__range_s}s]))", 449 | "hide": false, 450 | "interval": "", 451 | "legendFormat": "Average", 452 | "refId": "B" 453 | } 454 | ], 455 | "title": "Total Players", 456 | "type": "stat" 457 | }, 458 | { 459 | "aliasColors": {}, 460 | "bars": false, 461 | "dashLength": 10, 462 | "dashes": false, 463 | "datasource": null, 464 | "fieldConfig": { 465 | "defaults": { 466 | "color": {}, 467 | "custom": {}, 468 | "thresholds": { 469 | "mode": "absolute", 470 | "steps": [] 471 | } 472 | }, 473 | "overrides": [] 474 | }, 475 | "fill": 1, 476 | "fillGradient": 0, 477 | "gridPos": { 478 | "h": 21, 479 | "w": 15, 480 | "x": 9, 481 | "y": 15 482 | }, 483 | "hiddenSeries": false, 484 | "id": 359, 485 | "legend": { 486 | "alignAsTable": true, 487 | "avg": true, 488 | "current": true, 489 | "hideEmpty": false, 490 | "max": true, 491 | "min": true, 492 | "show": true, 493 | "total": false, 494 | "values": true 495 | }, 496 | "lines": true, 497 | "linewidth": 1, 498 | "nullPointMode": "null", 499 | "options": { 500 | "alertThreshold": true 501 | }, 502 | "percentage": false, 503 | "pluginVersion": "7.4.2", 504 | "pointradius": 2, 505 | "points": false, 506 | "renderer": "flot", 507 | "seriesOverrides": [], 508 | "spaceLength": 10, 509 | "stack": false, 510 | "steppedLine": false, 511 | "targets": [ 512 | { 513 | "expr": "sum by (host)(infrared_connected)", 514 | "interval": "", 515 | "legendFormat": " {{host}}", 516 | "refId": "A" 517 | }, 518 | { 519 | "expr": "sum(infrared_connected)", 520 | "hide": false, 521 | "interval": "", 522 | "legendFormat": "Total", 523 | "refId": "B" 524 | } 525 | ], 526 | "thresholds": [], 527 | "timeFrom": null, 528 | "timeRegions": [], 529 | "timeShift": null, 530 | "title": "Total Players", 531 | "tooltip": { 532 | "shared": true, 533 | "sort": 2, 534 | "value_type": "individual" 535 | }, 536 | "type": "graph", 537 | "xaxis": { 538 | "buckets": null, 539 | "mode": "time", 540 | "name": null, 541 | "show": true, 542 | "values": [] 543 | }, 544 | "yaxes": [ 545 | { 546 | "$$hashKey": "object:272", 547 | "format": "short", 548 | "label": null, 549 | "logBase": 1, 550 | "max": null, 551 | "min": "0", 552 | "show": true 553 | }, 554 | { 555 | "$$hashKey": "object:273", 556 | "format": "short", 557 | "label": null, 558 | "logBase": 1, 559 | "max": null, 560 | "min": null, 561 | "show": true 562 | } 563 | ], 564 | "yaxis": { 565 | "align": false, 566 | "alignLevel": null 567 | } 568 | }, 569 | { 570 | "aliasColors": {}, 571 | "breakPoint": "50%", 572 | "cacheTimeout": null, 573 | "combine": { 574 | "label": "Others", 575 | "threshold": 0 576 | }, 577 | "datasource": null, 578 | "fieldConfig": { 579 | "defaults": { 580 | "custom": {} 581 | }, 582 | "overrides": [] 583 | }, 584 | "fontSize": "80%", 585 | "format": "short", 586 | "gridPos": { 587 | "h": 14, 588 | "w": 5, 589 | "x": 0, 590 | "y": 22 591 | }, 592 | "id": 362, 593 | "interval": null, 594 | "legend": { 595 | "percentage": true, 596 | "percentageDecimals": 1, 597 | "show": true, 598 | "values": true 599 | }, 600 | "legendType": "Under graph", 601 | "links": [], 602 | "nullPointMode": "connected", 603 | "pieType": "pie", 604 | "pluginVersion": "7.4.2", 605 | "strokeWidth": 1, 606 | "targets": [ 607 | { 608 | "expr": "sum by (host)(infrared_connected)", 609 | "interval": "", 610 | "legendFormat": "{{host}}", 611 | "refId": "A" 612 | } 613 | ], 614 | "title": "Player Distribution", 615 | "type": "grafana-piechart-panel", 616 | "valueName": "current" 617 | }, 618 | { 619 | "aliasColors": {}, 620 | "breakPoint": "50%", 621 | "cacheTimeout": null, 622 | "combine": { 623 | "label": "Others", 624 | "threshold": 0 625 | }, 626 | "datasource": null, 627 | "fieldConfig": { 628 | "defaults": { 629 | "custom": {} 630 | }, 631 | "overrides": [] 632 | }, 633 | "fontSize": "80%", 634 | "format": "short", 635 | "gridPos": { 636 | "h": 14, 637 | "w": 4, 638 | "x": 5, 639 | "y": 22 640 | }, 641 | "id": 365, 642 | "interval": null, 643 | "legend": { 644 | "percentage": true, 645 | "percentageDecimals": 1, 646 | "show": true, 647 | "values": true 648 | }, 649 | "legendType": "Under graph", 650 | "links": [], 651 | "nullPointMode": "connected", 652 | "pieType": "pie", 653 | "pluginVersion": "7.4.2", 654 | "strokeWidth": 1, 655 | "targets": [ 656 | { 657 | "expr": "sum by (instance)(infrared_connected)", 658 | "interval": "", 659 | "legendFormat": "{{instance}}", 660 | "refId": "A" 661 | } 662 | ], 663 | "title": "Instance Distribution", 664 | "type": "grafana-piechart-panel", 665 | "valueName": "current" 666 | } 667 | ], 668 | "refresh": "5s", 669 | "schemaVersion": 27, 670 | "style": "dark", 671 | "tags": [ 672 | "linux" 673 | ], 674 | "templating": { 675 | "list": [ 676 | { 677 | "allValue": null, 678 | "current": { 679 | "selected": false, 680 | "text": "default", 681 | "value": "default" 682 | }, 683 | "datasource": "default", 684 | "definition": "label_values({job=\"infrared\"},instance)", 685 | "description": null, 686 | "error": null, 687 | "hide": 0, 688 | "includeAll": false, 689 | "label": null, 690 | "multi": false, 691 | "name": "instance", 692 | "query": { 693 | "query": "label_values({job=\"infrared\"},instance)", 694 | "refId": "StandardVariableQuery" 695 | }, 696 | "refresh": 0, 697 | "regex": "", 698 | "skipUrlSync": false, 699 | "sort": 3, 700 | "tagValuesQuery": "", 701 | "tags": [], 702 | "tagsQuery": "", 703 | "type": "query", 704 | "useTags": false 705 | } 706 | ] 707 | }, 708 | "time": { 709 | "from": "now-15m", 710 | "to": "now" 711 | }, 712 | "timepicker": { 713 | "refresh_intervals": [ 714 | "5s", 715 | "10s", 716 | "30s", 717 | "1m", 718 | "5m", 719 | "15m", 720 | "30m", 721 | "1h", 722 | "2h", 723 | "1d" 724 | ], 725 | "time_options": [ 726 | "5m", 727 | "15m", 728 | "1h", 729 | "6h", 730 | "12h", 731 | "24h", 732 | "2d", 733 | "7d", 734 | "30d" 735 | ] 736 | }, 737 | "timezone": "browser", 738 | "title": "infrared", 739 | "uid": "12312312", 740 | "version": 3 741 | } -------------------------------------------------------------------------------- /grafana/dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lhridder/infrared/9d4a65593aab015c3af317eb14ef33c988446721/grafana/dashboard.png -------------------------------------------------------------------------------- /process/docker.go: -------------------------------------------------------------------------------- 1 | package process 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | 7 | "github.com/docker/docker/api/types" 8 | "github.com/docker/docker/client" 9 | "golang.org/x/net/context" 10 | ) 11 | 12 | type docker struct { 13 | client *client.Client 14 | containerName string 15 | } 16 | 17 | // NewDocker create a new docker process that manages a container 18 | func NewDocker(containerName string) (Process, error) { 19 | cli, err := client.NewClientWithOpts(client.FromEnv) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | return docker{ 25 | client: cli, 26 | containerName: fmt.Sprintf("/%s", containerName), 27 | }, nil 28 | } 29 | 30 | func (proc docker) Start() error { 31 | containerID, err := proc.resolveContainerName() 32 | if err != nil { 33 | return err 34 | } 35 | 36 | ctx, cancel := context.WithTimeout(context.Background(), contextTimeout) 37 | defer cancel() 38 | 39 | return proc.client.ContainerStart(ctx, containerID, types.ContainerStartOptions{}) 40 | } 41 | 42 | func (proc docker) Stop() error { 43 | containerID, err := proc.resolveContainerName() 44 | if err != nil { 45 | return err 46 | } 47 | 48 | ctx, cancel := context.WithTimeout(context.Background(), contextTimeout) 49 | defer cancel() 50 | 51 | return proc.client.ContainerStop(ctx, containerID, nil) 52 | } 53 | 54 | func (proc docker) IsRunning() (bool, error) { 55 | containerID, err := proc.resolveContainerName() 56 | if err != nil { 57 | return false, err 58 | } 59 | 60 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 61 | defer cancel() 62 | 63 | info, err := proc.client.ContainerInspect(ctx, containerID) 64 | if err != nil { 65 | return false, err 66 | } 67 | 68 | return info.State.Running, nil 69 | } 70 | 71 | func (proc docker) resolveContainerName() (string, error) { 72 | ctx, cancel := context.WithTimeout(context.Background(), contextTimeout) 73 | defer cancel() 74 | 75 | containers, err := proc.client.ContainerList(ctx, types.ContainerListOptions{All: true}) 76 | if err != nil { 77 | return "", err 78 | } 79 | 80 | for _, container := range containers { 81 | for _, name := range container.Names { 82 | if name != proc.containerName { 83 | continue 84 | } 85 | return container.ID, nil 86 | } 87 | } 88 | 89 | return "", fmt.Errorf("container with name \"%s\" not found", proc.containerName) 90 | } 91 | -------------------------------------------------------------------------------- /process/portainer.go: -------------------------------------------------------------------------------- 1 | package process 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "github.com/docker/docker/client" 9 | "github.com/docker/docker/errdefs" 10 | "io/ioutil" 11 | "net/http" 12 | ) 13 | 14 | const ( 15 | contentType = "application/json" 16 | authenticationEndpoint = "http://%s/api/auth" 17 | dockerEndpoint = "tcp://%s/api/endpoints/%s/docker" 18 | ) 19 | 20 | type portainer struct { 21 | docker docker 22 | address string 23 | username string 24 | password string 25 | header map[string]string 26 | } 27 | 28 | // NewPortainer creates a new portainer process that manages a docker container 29 | func NewPortainer(containerName, address, endpointID, username, password string) (Process, error) { 30 | baseURL := fmt.Sprintf(dockerEndpoint, address, endpointID) 31 | header := map[string]string{} 32 | cli, err := client.NewClientWithOpts( 33 | client.WithHost(baseURL), 34 | client.WithScheme("http"), 35 | client.WithAPIVersionNegotiation(), 36 | client.WithHTTPHeaders(header), 37 | ) 38 | if err != nil { 39 | return nil, err 40 | } 41 | 42 | return portainer{ 43 | docker: docker{ 44 | client: cli, 45 | containerName: "/" + containerName, 46 | }, 47 | address: address, 48 | username: username, 49 | password: password, 50 | header: header, 51 | }, nil 52 | } 53 | 54 | func (portainer portainer) Start() error { 55 | err := portainer.docker.Start() 56 | if err == nil { 57 | return nil 58 | } 59 | 60 | if !isUnauthorized(err) { 61 | return err 62 | } 63 | 64 | if err := portainer.authenticate(); err != nil { 65 | return fmt.Errorf("could not authorize; %s", err) 66 | } 67 | 68 | return portainer.docker.Start() 69 | } 70 | 71 | func (portainer portainer) Stop() error { 72 | err := portainer.docker.Stop() 73 | if err == nil { 74 | return nil 75 | } 76 | 77 | if !isUnauthorized(err) { 78 | return err 79 | } 80 | 81 | if err := portainer.authenticate(); err != nil { 82 | return fmt.Errorf("could not authorize; %s", err) 83 | } 84 | 85 | return portainer.docker.Stop() 86 | } 87 | 88 | func (portainer portainer) IsRunning() (bool, error) { 89 | isRunning, err := portainer.docker.IsRunning() 90 | if err == nil { 91 | return isRunning, nil 92 | } 93 | 94 | if !isUnauthorized(err) { 95 | return false, err 96 | } 97 | 98 | if err := portainer.authenticate(); err != nil { 99 | return false, fmt.Errorf("could not authorize; %s", err) 100 | } 101 | 102 | return portainer.docker.IsRunning() 103 | } 104 | 105 | func isUnauthorized(err error) bool { 106 | return errdefs.GetHTTPErrorStatusCode(err) == http.StatusUnauthorized 107 | } 108 | 109 | func (portainer *portainer) authenticate() error { 110 | var credentials = struct { 111 | Username string `json:"Username"` 112 | Password string `json:"Password"` 113 | }{ 114 | Username: portainer.username, 115 | Password: portainer.password, 116 | } 117 | 118 | bodyJSON, err := json.Marshal(credentials) 119 | if err != nil { 120 | return err 121 | } 122 | 123 | url := fmt.Sprintf(authenticationEndpoint, portainer.address) 124 | response, err := http.Post(url, contentType, bytes.NewBuffer(bodyJSON)) 125 | if err != nil { 126 | return err 127 | } 128 | 129 | if response.StatusCode != http.StatusOK { 130 | return errors.New(http.StatusText(response.StatusCode)) 131 | } 132 | 133 | data, err := ioutil.ReadAll(response.Body) 134 | if err != nil { 135 | return err 136 | } 137 | 138 | var jwtResponse = struct { 139 | JWT string `json:"jwt"` 140 | }{} 141 | 142 | if err := json.Unmarshal(data, &jwtResponse); err != nil { 143 | return err 144 | } 145 | 146 | portainer.header["Authorization"] = fmt.Sprintf("Bearer %s", jwtResponse.JWT) 147 | return nil 148 | } 149 | -------------------------------------------------------------------------------- /process/process.go: -------------------------------------------------------------------------------- 1 | package process 2 | 3 | import ( 4 | "time" 5 | ) 6 | 7 | const contextTimeout = 10 * time.Second 8 | 9 | // Process is an arbitrary process that can be started or stopped 10 | type Process interface { 11 | Start() error 12 | Stop() error 13 | IsRunning() (bool, error) 14 | } 15 | -------------------------------------------------------------------------------- /protocol/cfb8/cfb8.go: -------------------------------------------------------------------------------- 1 | // All credits go to Ilmari Karonen 2 | // Source: https://stackoverflow.com/questions/23897809/different-results-in-go-and-pycrypto-when-using-aes-cfb/37234233#37234233 3 | package cfb8 4 | 5 | import ( 6 | "crypto/cipher" 7 | ) 8 | 9 | // CFB stream with 8 bit segment size 10 | // See http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf 11 | type cfb8 struct { 12 | b cipher.Block 13 | blockSize int 14 | in []byte 15 | out []byte 16 | 17 | decrypt bool 18 | } 19 | 20 | func (x *cfb8) XORKeyStream(dst, src []byte) { 21 | for i := range src { 22 | x.b.Encrypt(x.out, x.in) 23 | copy(x.in[:x.blockSize-1], x.in[1:]) 24 | if x.decrypt { 25 | x.in[x.blockSize-1] = src[i] 26 | } 27 | dst[i] = src[i] ^ x.out[0] 28 | if !x.decrypt { 29 | x.in[x.blockSize-1] = dst[i] 30 | } 31 | } 32 | } 33 | 34 | // NewEncrypter NewCFB8Encrypter returns a Stream which encrypts with cipher feedback mode 35 | // (segment size = 8), using the given Block. The iv must be the same length as 36 | // the Block's block size. 37 | func NewEncrypter(block cipher.Block, iv []byte) cipher.Stream { 38 | return newCFB8(block, iv, false) 39 | } 40 | 41 | // NewDecrypter NewCFB8Decrypter returns a Stream which decrypts with cipher feedback mode 42 | // (segment size = 8), using the given Block. The iv must be the same length as 43 | // the Block's block size. 44 | func NewDecrypter(block cipher.Block, iv []byte) cipher.Stream { 45 | return newCFB8(block, iv, true) 46 | } 47 | 48 | func newCFB8(block cipher.Block, iv []byte, decrypt bool) cipher.Stream { 49 | blockSize := block.BlockSize() 50 | if len(iv) != blockSize { 51 | // stack trace will indicate whether it was de or encryption 52 | panic("cipher.newCFB: IV length must equal block size") 53 | } 54 | x := &cfb8{ 55 | b: block, 56 | blockSize: blockSize, 57 | out: make([]byte, blockSize), 58 | in: make([]byte, blockSize), 59 | decrypt: decrypt, 60 | } 61 | copy(x.in, iv) 62 | 63 | return x 64 | } 65 | -------------------------------------------------------------------------------- /protocol/errors.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | var ( 8 | ErrInvalidPacketID = errors.New("invalid packet id") 9 | ErrInvalidPacketLength = errors.New("packet length incorrect") 10 | ) 11 | -------------------------------------------------------------------------------- /protocol/handshaking/serverbound_handshake.go: -------------------------------------------------------------------------------- 1 | package handshaking 2 | 3 | import ( 4 | "fmt" 5 | "github.com/haveachin/infrared/protocol" 6 | "net" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | const ( 12 | ServerBoundHandshakePacketID byte = 0x00 13 | 14 | ServerBoundHandshakeStatusState = protocol.Byte(1) 15 | ServerBoundHandshakeLoginState = protocol.Byte(2) 16 | 17 | ForgeSeparator = "\x00" 18 | RealIPSeparator = "///" 19 | ) 20 | 21 | type ServerBoundHandshake struct { 22 | ProtocolVersion protocol.VarInt 23 | ServerAddress protocol.String 24 | ServerPort protocol.UnsignedShort 25 | NextState protocol.Byte 26 | } 27 | 28 | func (pk ServerBoundHandshake) Marshal() protocol.Packet { 29 | return protocol.MarshalPacket( 30 | ServerBoundHandshakePacketID, 31 | pk.ProtocolVersion, 32 | pk.ServerAddress, 33 | pk.ServerPort, 34 | pk.NextState, 35 | ) 36 | } 37 | 38 | func UnmarshalServerBoundHandshake(packet protocol.Packet) (ServerBoundHandshake, error) { 39 | var pk ServerBoundHandshake 40 | 41 | if packet.ID != ServerBoundHandshakePacketID { 42 | return pk, protocol.ErrInvalidPacketID 43 | } 44 | 45 | if err := packet.Scan( 46 | &pk.ProtocolVersion, 47 | &pk.ServerAddress, 48 | &pk.ServerPort, 49 | &pk.NextState, 50 | ); err != nil { 51 | return pk, err 52 | } 53 | 54 | return pk, nil 55 | } 56 | 57 | func (pk ServerBoundHandshake) IsStatusRequest() bool { 58 | return pk.NextState == ServerBoundHandshakeStatusState 59 | } 60 | 61 | func (pk ServerBoundHandshake) IsLoginRequest() bool { 62 | return pk.NextState == ServerBoundHandshakeLoginState 63 | } 64 | 65 | func (pk ServerBoundHandshake) IsForgeAddress() bool { 66 | addr := string(pk.ServerAddress) 67 | return len(strings.Split(addr, ForgeSeparator)) > 1 68 | } 69 | 70 | func (pk ServerBoundHandshake) IsRealIPAddress() bool { 71 | addr := string(pk.ServerAddress) 72 | return len(strings.Split(addr, RealIPSeparator)) > 1 73 | } 74 | 75 | func (pk ServerBoundHandshake) ParseServerAddress() string { 76 | addr := string(pk.ServerAddress) 77 | addr = strings.Split(addr, ForgeSeparator)[0] 78 | addr = strings.Split(addr, RealIPSeparator)[0] 79 | // Resolves an issue with some proxies 80 | addr = strings.Trim(addr, ".") 81 | return addr 82 | } 83 | 84 | func (pk *ServerBoundHandshake) UpgradeToRealIP(clientAddr net.Addr, timestamp time.Time) { 85 | if pk.IsRealIPAddress() { 86 | return 87 | } 88 | 89 | addr := string(pk.ServerAddress) 90 | addrWithForge := strings.SplitN(addr, ForgeSeparator, 3) 91 | 92 | addr = fmt.Sprintf("%s///%s///%d", addrWithForge[0], clientAddr.String(), timestamp.Unix()) 93 | 94 | if len(addrWithForge) > 1 { 95 | addr = fmt.Sprintf("%s\x00%s\x00", addr, addrWithForge[1]) 96 | } 97 | 98 | pk.ServerAddress = protocol.String(addr) 99 | } 100 | -------------------------------------------------------------------------------- /protocol/handshaking/serverbound_handshake_test.go: -------------------------------------------------------------------------------- 1 | package handshaking 2 | 3 | import ( 4 | "bytes" 5 | "github.com/haveachin/infrared/protocol" 6 | "net" 7 | "strconv" 8 | "strings" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | func TestServerBoundHandshake_Marshal(t *testing.T) { 14 | tt := []struct { 15 | packet ServerBoundHandshake 16 | marshaledPacket protocol.Packet 17 | }{ 18 | { 19 | packet: ServerBoundHandshake{ 20 | ProtocolVersion: 578, 21 | ServerAddress: "spook.space", 22 | ServerPort: 25565, 23 | NextState: ServerBoundHandshakeStatusState, 24 | }, 25 | marshaledPacket: protocol.Packet{ 26 | ID: 0x00, 27 | Data: []byte{0xC2, 0x04, 0x0B, 0x73, 0x70, 0x6F, 0x6F, 0x6B, 0x2E, 0x73, 0x70, 0x61, 0x63, 0x65, 0x63, 0xDD, 0x01}, 28 | }, 29 | }, 30 | { 31 | packet: ServerBoundHandshake{ 32 | ProtocolVersion: 578, 33 | ServerAddress: "example.com", 34 | ServerPort: 1337, 35 | NextState: ServerBoundHandshakeStatusState, 36 | }, 37 | marshaledPacket: protocol.Packet{ 38 | ID: 0x00, 39 | Data: []byte{0xC2, 0x04, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x05, 0x39, 0x01}, 40 | }, 41 | }, 42 | } 43 | 44 | for _, tc := range tt { 45 | pk := tc.packet.Marshal() 46 | 47 | if pk.ID != ServerBoundHandshakePacketID { 48 | t.Error("invalid packet id") 49 | } 50 | 51 | if !bytes.Equal(pk.Data, tc.marshaledPacket.Data) { 52 | t.Errorf("got: %v, want: %v", pk.Data, tc.marshaledPacket.Data) 53 | } 54 | } 55 | } 56 | 57 | func TestUnmarshalServerBoundHandshake(t *testing.T) { 58 | tt := []struct { 59 | packet protocol.Packet 60 | unmarshalledPacket ServerBoundHandshake 61 | }{ 62 | { 63 | packet: protocol.Packet{ 64 | ID: 0x00, 65 | // ProtoVer. | Server Address |Serv. Port | Nxt State 66 | Data: []byte{0xC2, 0x04, 0x0B, 0x73, 0x70, 0x6F, 0x6F, 0x6B, 0x2E, 0x73, 0x70, 0x61, 0x63, 0x65, 0x63, 0xDD, 0x01}, 67 | }, 68 | unmarshalledPacket: ServerBoundHandshake{ 69 | ProtocolVersion: 578, 70 | ServerAddress: "spook.space", 71 | ServerPort: 25565, 72 | NextState: ServerBoundHandshakeStatusState, 73 | }, 74 | }, 75 | { 76 | packet: protocol.Packet{ 77 | ID: 0x00, 78 | // ProtoVer. | Server Address |Serv. Port | Nxt State 79 | Data: []byte{0xC2, 0x04, 0x0B, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x05, 0x39, 0x01}, 80 | }, 81 | unmarshalledPacket: ServerBoundHandshake{ 82 | ProtocolVersion: 578, 83 | ServerAddress: "example.com", 84 | ServerPort: 1337, 85 | NextState: ServerBoundHandshakeStatusState, 86 | }, 87 | }, 88 | } 89 | 90 | for _, tc := range tt { 91 | actual, err := UnmarshalServerBoundHandshake(tc.packet) 92 | if err != nil { 93 | t.Error(err) 94 | } 95 | 96 | expected := tc.unmarshalledPacket 97 | 98 | if actual.ProtocolVersion != expected.ProtocolVersion || 99 | actual.ServerAddress != expected.ServerAddress || 100 | actual.ServerPort != expected.ServerPort || 101 | actual.NextState != expected.NextState { 102 | t.Errorf("got: %v, want: %v", actual, tc.unmarshalledPacket) 103 | } 104 | } 105 | } 106 | 107 | func TestServerBoundHandshake_IsStatusRequest(t *testing.T) { 108 | tt := []struct { 109 | handshake ServerBoundHandshake 110 | result bool 111 | }{ 112 | { 113 | handshake: ServerBoundHandshake{ 114 | NextState: ServerBoundHandshakeStatusState, 115 | }, 116 | result: true, 117 | }, 118 | { 119 | handshake: ServerBoundHandshake{ 120 | NextState: ServerBoundHandshakeLoginState, 121 | }, 122 | result: false, 123 | }, 124 | } 125 | 126 | for _, tc := range tt { 127 | if tc.handshake.IsStatusRequest() != tc.result { 128 | t.Fail() 129 | } 130 | } 131 | } 132 | 133 | func TestServerBoundHandshake_IsLoginRequest(t *testing.T) { 134 | tt := []struct { 135 | handshake ServerBoundHandshake 136 | result bool 137 | }{ 138 | { 139 | handshake: ServerBoundHandshake{ 140 | NextState: ServerBoundHandshakeStatusState, 141 | }, 142 | result: false, 143 | }, 144 | { 145 | handshake: ServerBoundHandshake{ 146 | NextState: ServerBoundHandshakeLoginState, 147 | }, 148 | result: true, 149 | }, 150 | } 151 | 152 | for _, tc := range tt { 153 | if tc.handshake.IsLoginRequest() != tc.result { 154 | t.Fail() 155 | } 156 | } 157 | } 158 | 159 | func TestServerBoundHandshake_IsForgeAddress(t *testing.T) { 160 | tt := []struct { 161 | addr string 162 | result bool 163 | }{ 164 | { 165 | addr: ForgeSeparator, 166 | result: true, 167 | }, 168 | { 169 | addr: "example.com:1234" + ForgeSeparator, 170 | result: true, 171 | }, 172 | { 173 | addr: "example.com" + ForgeSeparator + "some data", 174 | result: true, 175 | }, 176 | { 177 | addr: "example.com" + ForgeSeparator + "some data" + RealIPSeparator + "more", 178 | result: true, 179 | }, 180 | { 181 | addr: "example.com", 182 | result: false, 183 | }, 184 | { 185 | addr: "", 186 | result: false, 187 | }, 188 | } 189 | 190 | for _, tc := range tt { 191 | hs := ServerBoundHandshake{ServerAddress: protocol.String(tc.addr)} 192 | if hs.IsForgeAddress() != tc.result { 193 | t.Errorf("%s: got: %v; want: %v", tc.addr, !tc.result, tc.result) 194 | } 195 | } 196 | } 197 | 198 | func TestServerBoundHandshake_IsRealIPAddress(t *testing.T) { 199 | tt := []struct { 200 | addr string 201 | result bool 202 | }{ 203 | { 204 | addr: RealIPSeparator, 205 | result: true, 206 | }, 207 | { 208 | addr: "example.com:25565" + RealIPSeparator, 209 | result: true, 210 | }, 211 | { 212 | addr: "example.com:1337" + RealIPSeparator + "some data", 213 | result: true, 214 | }, 215 | { 216 | addr: "example.com" + ForgeSeparator + "some data" + RealIPSeparator + "more", 217 | result: true, 218 | }, 219 | { 220 | addr: "example.com", 221 | result: false, 222 | }, 223 | { 224 | addr: ":1234", 225 | result: false, 226 | }, 227 | } 228 | 229 | for _, tc := range tt { 230 | hs := ServerBoundHandshake{ServerAddress: protocol.String(tc.addr)} 231 | if hs.IsRealIPAddress() != tc.result { 232 | t.Errorf("%s: got: %v; want: %v", tc.addr, !tc.result, tc.result) 233 | } 234 | } 235 | } 236 | 237 | func TestServerBoundHandshake_ParseServerAddress(t *testing.T) { 238 | tt := []struct { 239 | addr string 240 | expectedAddr string 241 | }{ 242 | { 243 | addr: "", 244 | expectedAddr: "", 245 | }, 246 | { 247 | addr: "example.com:25565", 248 | expectedAddr: "example.com:25565", 249 | }, 250 | { 251 | addr: ForgeSeparator, 252 | expectedAddr: "", 253 | }, 254 | { 255 | addr: RealIPSeparator, 256 | expectedAddr: "", 257 | }, 258 | { 259 | addr: "example.com" + ForgeSeparator, 260 | expectedAddr: "example.com", 261 | }, 262 | { 263 | addr: "example.com" + ForgeSeparator + "some data", 264 | expectedAddr: "example.com", 265 | }, 266 | { 267 | addr: "example.com:25565" + RealIPSeparator + "some data", 268 | expectedAddr: "example.com:25565", 269 | }, 270 | { 271 | addr: "example.com:1234" + ForgeSeparator + "some data" + RealIPSeparator + "more", 272 | expectedAddr: "example.com:1234", 273 | }, 274 | } 275 | 276 | for _, tc := range tt { 277 | hs := ServerBoundHandshake{ServerAddress: protocol.String(tc.addr)} 278 | if hs.ParseServerAddress() != tc.expectedAddr { 279 | t.Errorf("got: %v; want: %v", hs.ParseServerAddress(), tc.expectedAddr) 280 | } 281 | } 282 | } 283 | 284 | func TestServerBoundHandshake_UpgradeToRealIP(t *testing.T) { 285 | tt := []struct { 286 | addr string 287 | clientAddr net.TCPAddr 288 | timestamp time.Time 289 | }{ 290 | { 291 | addr: "example.com", 292 | clientAddr: net.TCPAddr{ 293 | IP: net.IPv4(127, 0, 0, 1), 294 | Port: 12345, 295 | }, 296 | timestamp: time.Now(), 297 | }, 298 | { 299 | addr: "sub.example.com:25565", 300 | clientAddr: net.TCPAddr{ 301 | IP: net.IPv4(127, 0, 1, 1), 302 | Port: 25565, 303 | }, 304 | timestamp: time.Now(), 305 | }, 306 | { 307 | addr: "example.com:25565", 308 | clientAddr: net.TCPAddr{ 309 | IP: net.IPv4(127, 0, 2, 1), 310 | Port: 6543, 311 | }, 312 | timestamp: time.Now(), 313 | }, 314 | { 315 | addr: "example.com", 316 | clientAddr: net.TCPAddr{ 317 | IP: net.IPv4(127, 0, 3, 1), 318 | Port: 7467, 319 | }, 320 | timestamp: time.Now(), 321 | }, 322 | } 323 | 324 | for _, tc := range tt { 325 | hs := ServerBoundHandshake{ServerAddress: protocol.String(tc.addr)} 326 | hs.UpgradeToRealIP(&tc.clientAddr, tc.timestamp) 327 | 328 | if hs.ParseServerAddress() != tc.addr { 329 | t.Errorf("got: %v; want: %v", hs.ParseServerAddress(), tc.addr) 330 | } 331 | 332 | realIpSegments := strings.Split(string(hs.ServerAddress), RealIPSeparator) 333 | 334 | if realIpSegments[1] != tc.clientAddr.String() { 335 | t.Errorf("got: %v; want: %v", realIpSegments[1], tc.addr) 336 | } 337 | 338 | unixTimestamp, err := strconv.ParseInt(realIpSegments[2], 10, 64) 339 | if err != nil { 340 | t.Error(err) 341 | } 342 | 343 | if unixTimestamp != tc.timestamp.Unix() { 344 | t.Errorf("timestamp is invalid: got: %d; want: %d", unixTimestamp, tc.timestamp.Unix()) 345 | } 346 | } 347 | } 348 | 349 | func BenchmarkHandshakingServerBoundHandshake_Marshal(b *testing.B) { 350 | isHandshakePk := ServerBoundHandshake{ 351 | ProtocolVersion: 578, 352 | ServerAddress: "spook.space", 353 | ServerPort: 25565, 354 | NextState: 1, 355 | } 356 | 357 | pk := isHandshakePk.Marshal() 358 | 359 | for n := 0; n < b.N; n++ { 360 | if _, err := UnmarshalServerBoundHandshake(pk); err != nil { 361 | b.Error(err) 362 | } 363 | } 364 | } 365 | -------------------------------------------------------------------------------- /protocol/login/clientbound_disconnect.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ClientBoundDisconnectPacketID byte = 0x00 8 | 9 | type ClientBoundDisconnect struct { 10 | Reason protocol.Chat 11 | } 12 | 13 | func (pk ClientBoundDisconnect) Marshal() protocol.Packet { 14 | return protocol.MarshalPacket( 15 | ClientBoundDisconnectPacketID, 16 | pk.Reason, 17 | ) 18 | } 19 | -------------------------------------------------------------------------------- /protocol/login/clientbound_disconnect_test.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import ( 4 | "bytes" 5 | "github.com/haveachin/infrared/protocol" 6 | "testing" 7 | ) 8 | 9 | func TestClientBoundDisconnect_Marshal(t *testing.T) { 10 | tt := []struct { 11 | packet ClientBoundDisconnect 12 | marshaledPacket protocol.Packet 13 | }{ 14 | { 15 | packet: ClientBoundDisconnect{ 16 | Reason: protocol.Chat(""), 17 | }, 18 | marshaledPacket: protocol.Packet{ 19 | ID: 0x00, 20 | Data: []byte{0x00}, 21 | }, 22 | }, 23 | { 24 | packet: ClientBoundDisconnect{ 25 | Reason: protocol.Chat("Hello, World!"), 26 | }, 27 | marshaledPacket: protocol.Packet{ 28 | ID: 0x00, 29 | Data: []byte{0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21}, 30 | }, 31 | }, 32 | } 33 | 34 | for _, tc := range tt { 35 | pk := tc.packet.Marshal() 36 | 37 | if pk.ID != ClientBoundDisconnectPacketID { 38 | t.Error("invalid packet id") 39 | } 40 | 41 | if !bytes.Equal(pk.Data, tc.marshaledPacket.Data) { 42 | t.Errorf("got: %v, want: %v", pk.Data, tc.marshaledPacket.Data) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /protocol/login/clientbound_encryptionrequest.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ClientBoundEncryptionRequestPacketID byte = 0x01 8 | 9 | type ClientBoundEncryptionRequest struct { 10 | ServerID protocol.String 11 | PublicKey protocol.ByteArray 12 | VerifyToken protocol.ByteArray 13 | } 14 | 15 | func (pk ClientBoundEncryptionRequest) Marshal() protocol.Packet { 16 | return protocol.MarshalPacket( 17 | ClientBoundEncryptionRequestPacketID, 18 | pk.ServerID, 19 | pk.PublicKey, 20 | pk.VerifyToken, 21 | ) 22 | } 23 | -------------------------------------------------------------------------------- /protocol/login/clientbound_loginsuccess.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import "github.com/haveachin/infrared/protocol" 4 | 5 | const ClientBoundLoginSuccessPacketID byte = 0x02 6 | 7 | type ClientBoundLoginSuccess struct { 8 | UUID protocol.UUID 9 | Username protocol.String 10 | } 11 | 12 | func (pk ClientBoundLoginSuccess) Marshal() protocol.Packet { 13 | return protocol.MarshalPacket( 14 | ClientBoundLoginSuccessPacketID, 15 | pk.UUID, 16 | pk.Username, 17 | ) 18 | } 19 | -------------------------------------------------------------------------------- /protocol/login/serverbound_encryptionresponse.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ServerBoundEncryptionResponsePacketID = 0x01 8 | 9 | type ServerBoundEncryptionResponse struct { 10 | SharedSecret protocol.ByteArray 11 | VerifyToken protocol.ByteArray 12 | } 13 | 14 | type ServerBoundEncryptionResponseNew struct { 15 | SharedSecret protocol.ByteArray 16 | Salt protocol.Long 17 | Signature protocol.ByteArray 18 | } 19 | 20 | func (pk ServerBoundEncryptionResponse) Marshal() protocol.Packet { 21 | return protocol.MarshalPacket( 22 | ServerBoundEncryptionResponsePacketID, 23 | pk.SharedSecret, 24 | pk.VerifyToken, 25 | ) 26 | } 27 | 28 | func UnmarshalServerBoundEncryptionResponse(packet protocol.Packet, protocolVersion protocol.VarInt) (ServerBoundEncryptionResponse, ServerBoundEncryptionResponseNew, error) { 29 | var pk ServerBoundEncryptionResponse 30 | var pknew ServerBoundEncryptionResponseNew 31 | 32 | if packet.ID != ServerBoundEncryptionResponsePacketID { 33 | return pk, pknew, protocol.ErrInvalidPacketID 34 | } 35 | 36 | if protocolVersion >= 759 { 37 | err := packet.Scan( 38 | &pknew.SharedSecret, 39 | &pknew.Salt, 40 | &pknew.Signature, 41 | ) 42 | if err != nil { 43 | return pk, pknew, err 44 | } 45 | } else { 46 | err := packet.Scan( 47 | &pk.SharedSecret, 48 | &pk.VerifyToken, 49 | ) 50 | if err != nil { 51 | return pk, pknew, err 52 | } 53 | } 54 | 55 | return pk, pknew, nil 56 | } 57 | -------------------------------------------------------------------------------- /protocol/login/serverbound_loginstart.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ServerBoundLoginStartPacketID byte = 0x00 8 | 9 | type ServerLoginStart struct { 10 | Name protocol.String 11 | } 12 | 13 | type ServerLoginStartNew struct { 14 | Name protocol.String 15 | HasSigData protocol.Boolean 16 | Timestamp protocol.Long 17 | PublicKey protocol.ByteArray 18 | Signature protocol.ByteArray 19 | } 20 | 21 | func UnmarshalServerBoundLoginStart(packet protocol.Packet) (ServerLoginStart, error) { 22 | var pk ServerLoginStart 23 | 24 | if packet.ID != ServerBoundLoginStartPacketID { 25 | return pk, protocol.ErrInvalidPacketID 26 | } 27 | 28 | if err := packet.Scan(&pk.Name); err != nil { 29 | return pk, err 30 | } 31 | 32 | return pk, nil 33 | } 34 | -------------------------------------------------------------------------------- /protocol/login/serverbound_loginstart_test.go: -------------------------------------------------------------------------------- 1 | package login 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | "testing" 6 | ) 7 | 8 | func TestUnmarshalServerBoundLoginStart(t *testing.T) { 9 | tt := []struct { 10 | packet protocol.Packet 11 | unmarshalledPacket ServerLoginStart 12 | }{ 13 | { 14 | packet: protocol.Packet{ 15 | ID: 0x00, 16 | Data: []byte{0x00}, 17 | }, 18 | unmarshalledPacket: ServerLoginStart{ 19 | Name: protocol.String(""), 20 | }, 21 | }, 22 | { 23 | packet: protocol.Packet{ 24 | ID: 0x00, 25 | Data: []byte{0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21}, 26 | }, 27 | unmarshalledPacket: ServerLoginStart{ 28 | Name: protocol.String("Hello, World!"), 29 | }, 30 | }, 31 | } 32 | 33 | for _, tc := range tt { 34 | loginStart, err := UnmarshalServerBoundLoginStart(tc.packet) 35 | if err != nil { 36 | t.Error(err) 37 | } 38 | 39 | if loginStart.Name != tc.unmarshalledPacket.Name { 40 | t.Errorf("got: %v, want: %v", loginStart.Name, tc.unmarshalledPacket.Name) 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /protocol/packet.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | ) 8 | 9 | // Packet is the raw representation of message that is send between the client and the server 10 | type Packet struct { 11 | ID byte 12 | Data []byte 13 | } 14 | 15 | // Scan decodes and copies the Packet data into the fields 16 | func (pk Packet) Scan(fields ...FieldDecoder) error { 17 | return ScanFields(bytes.NewReader(pk.Data), fields...) 18 | } 19 | 20 | // Marshal encodes the packet and all it's fields 21 | func (pk *Packet) Marshal() ([]byte, error) { 22 | var packedData []byte 23 | data := []byte{pk.ID} 24 | data = append(data, pk.Data...) 25 | 26 | packedData = append(packedData, VarInt(int32(len(data))).Encode()...) 27 | 28 | return append(packedData, data...), nil 29 | } 30 | 31 | // ScanFields decodes a byte stream into fields 32 | func ScanFields(r DecodeReader, fields ...FieldDecoder) error { 33 | for _, field := range fields { 34 | if err := field.Decode(r); err != nil { 35 | return err 36 | } 37 | } 38 | return nil 39 | } 40 | 41 | // MarshalPacket transforms an ID and Fields into a Packet 42 | func MarshalPacket(ID byte, fields ...FieldEncoder) Packet { 43 | var pkt Packet 44 | pkt.ID = ID 45 | 46 | for _, v := range fields { 47 | pkt.Data = append(pkt.Data, v.Encode()...) 48 | } 49 | 50 | return pkt 51 | } 52 | 53 | // ReadPacketBytes decodes a byte stream and cuts the first Packet as a byte array out 54 | func ReadPacketBytes(r DecodeReader, limit bool) ([]byte, error) { 55 | var packetLength VarInt 56 | if err := packetLength.Decode(r); err != nil { 57 | return nil, err 58 | } 59 | 60 | if limit && (packetLength < 1 || packetLength > 16384) { 61 | return nil, ErrInvalidPacketLength 62 | } 63 | 64 | data := make([]byte, packetLength) 65 | if _, err := io.ReadFull(r, data); err != nil { 66 | return nil, fmt.Errorf("reading the content of the packet failed: %v", err) 67 | } 68 | 69 | return data, nil 70 | } 71 | 72 | // ReadPacket decodes and decompresses a byte stream and cuts the first Packet out 73 | func ReadPacket(r DecodeReader, limit bool) (Packet, error) { 74 | data, err := ReadPacketBytes(r, limit) 75 | if err != nil { 76 | return Packet{}, err 77 | } 78 | 79 | return Packet{ 80 | ID: data[0], 81 | Data: data[1:], 82 | }, nil 83 | } 84 | 85 | // PeekPacket decodes and decompresses a byte stream and peeks the first Packet 86 | func PeekPacket(p PeekReader) (Packet, error) { 87 | r := bytePeeker{ 88 | PeekReader: p, 89 | cursor: 0, 90 | } 91 | 92 | return ReadPacket(&r, false) 93 | } 94 | -------------------------------------------------------------------------------- /protocol/packet_test.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "testing" 7 | ) 8 | 9 | func TestPacket_Marshal(t *testing.T) { 10 | tt := []struct { 11 | packet Packet 12 | expected []byte 13 | }{ 14 | { 15 | packet: Packet{ 16 | ID: 0x00, 17 | Data: []byte{0x00, 0xf2}, 18 | }, 19 | expected: []byte{0x03, 0x00, 0x00, 0xf2}, 20 | }, 21 | { 22 | packet: Packet{ 23 | ID: 0x0f, 24 | Data: []byte{0x00, 0xf2, 0x03, 0x50}, 25 | }, 26 | expected: []byte{0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50}, 27 | }, 28 | } 29 | 30 | for _, tc := range tt { 31 | actual, err := tc.packet.Marshal() 32 | if err != nil { 33 | t.Error(err) 34 | } 35 | 36 | if !bytes.Equal(actual, tc.expected) { 37 | t.Errorf("got: %v; want: %v", actual, tc.expected) 38 | } 39 | } 40 | } 41 | 42 | func TestPacket_Scan(t *testing.T) { 43 | // Arrange 44 | packet := Packet{ 45 | ID: 0x00, 46 | Data: []byte{0x00, 0xf2}, 47 | } 48 | 49 | var booleanField Boolean 50 | var byteField Byte 51 | 52 | // Act 53 | err := packet.Scan( 54 | &booleanField, 55 | &byteField, 56 | ) 57 | 58 | // Assert 59 | if err != nil { 60 | t.Error(err) 61 | } 62 | 63 | if booleanField != false { 64 | t.Error("got: true; want: false") 65 | } 66 | 67 | if !bytes.Equal(byteField.Encode(), []byte{0xf2}) { 68 | t.Errorf("got: %x; want: %x", byteField.Encode(), 0xf2) 69 | } 70 | } 71 | 72 | func TestScanFields(t *testing.T) { 73 | // Arrange 74 | packet := Packet{ 75 | ID: 0x00, 76 | Data: []byte{0x00, 0xf2}, 77 | } 78 | 79 | var booleanField Boolean 80 | var byteField Byte 81 | 82 | // Act 83 | err := ScanFields( 84 | bytes.NewReader(packet.Data), 85 | &booleanField, 86 | &byteField, 87 | ) 88 | 89 | // Assert 90 | if err != nil { 91 | t.Error(err) 92 | } 93 | 94 | if booleanField != false { 95 | t.Error("got: true; want: false") 96 | } 97 | 98 | if !bytes.Equal(byteField.Encode(), []byte{0xf2}) { 99 | t.Errorf("got: %x; want: %x", byteField.Encode(), 0xf2) 100 | } 101 | } 102 | 103 | func TestMarshalPacket(t *testing.T) { 104 | // Arrange 105 | packetId := byte(0x00) 106 | booleanField := Boolean(false) 107 | byteField := Byte(0x0f) 108 | packetData := []byte{0x00, 0x0f} 109 | 110 | // Act 111 | packet := MarshalPacket(packetId, booleanField, byteField) 112 | 113 | // Assert 114 | if packet.ID != packetId { 115 | t.Errorf("packet id: got: %v; want: %v", packet.ID, packetId) 116 | } 117 | 118 | if !bytes.Equal(packet.Data, packetData) { 119 | t.Errorf("got: %v; want: %v", packet.Data, packetData) 120 | } 121 | } 122 | 123 | func TestReadPacketBytes(t *testing.T) { 124 | tt := []struct { 125 | data []byte 126 | packetBytes []byte 127 | }{ 128 | { 129 | data: []byte{0x03, 0x00, 0x00, 0xf2, 0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50}, 130 | packetBytes: []byte{0x00, 0x00, 0xf2}, 131 | }, 132 | { 133 | data: []byte{0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50, 0x30, 0x01, 0xef, 0xaa}, 134 | packetBytes: []byte{0x0f, 0x00, 0xf2, 0x03, 0x50}, 135 | }, 136 | } 137 | 138 | for _, tc := range tt { 139 | readBytes, err := ReadPacketBytes(bytes.NewReader(tc.data)) 140 | if err != nil { 141 | t.Error(err) 142 | } 143 | 144 | if !bytes.Equal(readBytes, tc.packetBytes) { 145 | t.Errorf("got: %v; want: %v", readBytes, tc.packetBytes) 146 | } 147 | } 148 | } 149 | 150 | func TestReadPacket(t *testing.T) { 151 | tt := []struct { 152 | data []byte 153 | packet Packet 154 | dataAfterRead []byte 155 | }{ 156 | { 157 | data: []byte{0x03, 0x00, 0x00, 0xf2, 0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50}, 158 | packet: Packet{ 159 | ID: 0x00, 160 | Data: []byte{0x00, 0xf2}, 161 | }, 162 | dataAfterRead: []byte{0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50}, 163 | }, 164 | { 165 | data: []byte{0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50, 0x30, 0x01, 0xef, 0xaa}, 166 | packet: Packet{ 167 | ID: 0x0f, 168 | Data: []byte{0x00, 0xf2, 0x03, 0x50}, 169 | }, 170 | dataAfterRead: []byte{0x30, 0x01, 0xef, 0xaa}, 171 | }, 172 | } 173 | 174 | for _, tc := range tt { 175 | buf := bytes.NewBuffer(tc.data) 176 | pk, err := ReadPacket(buf) 177 | if err != nil { 178 | t.Error(err) 179 | } 180 | 181 | if pk.ID != tc.packet.ID { 182 | t.Errorf("packet ID: got: %v; want: %v", pk.ID, tc.packet.ID) 183 | } 184 | 185 | if !bytes.Equal(pk.Data, tc.packet.Data) { 186 | t.Errorf("packet data: got: %v; want: %v", pk.Data, tc.packet.Data) 187 | } 188 | 189 | if !bytes.Equal(buf.Bytes(), tc.dataAfterRead) { 190 | t.Errorf("data after read: got: %v; want: %v", tc.data, tc.dataAfterRead) 191 | } 192 | } 193 | } 194 | 195 | func TestPeekPacket(t *testing.T) { 196 | tt := []struct { 197 | data []byte 198 | packet Packet 199 | }{ 200 | { 201 | data: []byte{0x03, 0x00, 0x00, 0xf2, 0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50}, 202 | packet: Packet{ 203 | ID: 0x00, 204 | Data: []byte{0x00, 0xf2}, 205 | }, 206 | }, 207 | { 208 | data: []byte{0x05, 0x0f, 0x00, 0xf2, 0x03, 0x50, 0x30, 0x01, 0xef, 0xaa}, 209 | packet: Packet{ 210 | ID: 0x0f, 211 | Data: []byte{0x00, 0xf2, 0x03, 0x50}, 212 | }, 213 | }, 214 | } 215 | 216 | for _, tc := range tt { 217 | dataCopy := make([]byte, len(tc.data)) 218 | copy(dataCopy, tc.data) 219 | 220 | pk, err := PeekPacket(bufio.NewReader(bytes.NewReader(dataCopy))) 221 | if err != nil { 222 | t.Error(err) 223 | } 224 | 225 | if pk.ID != tc.packet.ID { 226 | t.Errorf("packet ID: got: %v; want: %v", pk.ID, tc.packet.ID) 227 | } 228 | 229 | if !bytes.Equal(pk.Data, tc.packet.Data) { 230 | t.Errorf("packet data: got: %v; want: %v", pk.Data, tc.packet.Data) 231 | } 232 | 233 | if !bytes.Equal(dataCopy, tc.data) { 234 | t.Errorf("data after read: got: %v; want: %v", dataCopy, tc.data) 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /protocol/peeker.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import "io" 4 | 5 | type PeekReader interface { 6 | Peek(n int) ([]byte, error) 7 | io.Reader 8 | } 9 | 10 | type bytePeeker struct { 11 | PeekReader 12 | cursor int 13 | } 14 | 15 | func (peeker *bytePeeker) Read(b []byte) (int, error) { 16 | buf, err := peeker.Peek(len(b) + peeker.cursor) 17 | if err != nil { 18 | return 0, err 19 | } 20 | 21 | for i := 0; i < len(b); i++ { 22 | b[i] = buf[i+peeker.cursor] 23 | } 24 | 25 | peeker.cursor += len(b) 26 | 27 | return len(b), nil 28 | } 29 | 30 | func (peeker *bytePeeker) ReadByte() (byte, error) { 31 | buf, err := peeker.Peek(1 + peeker.cursor) 32 | if err != nil { 33 | return 0x00, err 34 | } 35 | 36 | b := buf[peeker.cursor] 37 | peeker.cursor++ 38 | 39 | return b, nil 40 | } 41 | -------------------------------------------------------------------------------- /protocol/peeker_test.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "io" 7 | "testing" 8 | ) 9 | 10 | func TestBytePeeker_ReadByte(t *testing.T) { 11 | tt := []struct { 12 | peeker bytePeeker 13 | data []byte 14 | expectedByte byte 15 | }{ 16 | { 17 | peeker: bytePeeker{ 18 | cursor: 0, 19 | }, 20 | data: []byte{0x00, 0x01, 0x02, 0x03}, 21 | expectedByte: 0x00, 22 | }, 23 | { 24 | peeker: bytePeeker{ 25 | cursor: 1, 26 | }, 27 | data: []byte{0x00, 0x01, 0x02, 0x03}, 28 | expectedByte: 0x01, 29 | }, 30 | { 31 | peeker: bytePeeker{ 32 | cursor: 3, 33 | }, 34 | data: []byte{0x00, 0x01, 0x02, 0x03}, 35 | expectedByte: 0x03, 36 | }, 37 | } 38 | 39 | for _, tc := range tt { 40 | // Arrange 41 | clonedData := make([]byte, len(tc.data)) 42 | copy(clonedData, tc.data) 43 | tc.peeker.PeekReader = bufio.NewReader(bytes.NewReader(clonedData)) 44 | 45 | // Act 46 | b, err := tc.peeker.ReadByte() 47 | if err != nil && err != io.EOF { 48 | t.Error(err) 49 | } 50 | 51 | // Assert 52 | if b != tc.expectedByte { 53 | t.Errorf("got: %v; want: %v", b, tc.expectedByte) 54 | } 55 | 56 | if !bytes.Equal(clonedData, tc.data) { 57 | t.Errorf("data modified: got: %v; want: %v", clonedData, tc.data) 58 | } 59 | } 60 | } 61 | 62 | func TestBytePeeker_Read(t *testing.T) { 63 | tt := []struct { 64 | peeker bytePeeker 65 | data []byte 66 | expectedData []byte 67 | expectedN int 68 | }{ 69 | { 70 | peeker: bytePeeker{ 71 | cursor: 0, 72 | }, 73 | data: []byte{0x00, 0x01, 0x02, 0x03}, 74 | expectedData: []byte{0x00, 0x01, 0x02, 0x03}, 75 | expectedN: 4, 76 | }, 77 | { 78 | peeker: bytePeeker{ 79 | cursor: 1, 80 | }, 81 | data: []byte{0x00, 0x01, 0x02, 0x03}, 82 | expectedData: []byte{0x01, 0x02, 0x03}, 83 | expectedN: 3, 84 | }, 85 | { 86 | peeker: bytePeeker{ 87 | cursor: 3, 88 | }, 89 | data: []byte{0x00, 0x01, 0x02, 0x03}, 90 | expectedData: []byte{0x03}, 91 | expectedN: 1, 92 | }, 93 | } 94 | 95 | for _, tc := range tt { 96 | // Arrange 97 | clonedData := make([]byte, len(tc.data)) 98 | copy(clonedData, tc.data) 99 | tc.peeker.PeekReader = bufio.NewReader(bytes.NewReader(clonedData)) 100 | resultData := make([]byte, len(tc.expectedData)) 101 | 102 | // Act 103 | n, err := tc.peeker.Read(resultData) 104 | if err != nil && err != io.EOF { 105 | t.Error(err) 106 | } 107 | 108 | // Assert 109 | if n != tc.expectedN { 110 | t.Errorf("got: %v; want: %v", n, tc.expectedN) 111 | } 112 | 113 | if !bytes.Equal(resultData, tc.expectedData) { 114 | t.Errorf("got: %v; want: %v", resultData, tc.expectedData) 115 | } 116 | 117 | if !bytes.Equal(clonedData, tc.data) { 118 | t.Errorf("data modified: got: %v; want: %v", clonedData, tc.data) 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /protocol/play/clientbound_disconnect.go: -------------------------------------------------------------------------------- 1 | package play 2 | 3 | import "github.com/haveachin/infrared/protocol" 4 | 5 | const ClientBoundDisconnectPacketID byte = 0x1A 6 | 7 | type ClientBoundDisconnect struct { 8 | Reason protocol.Chat 9 | } 10 | 11 | func (pk ClientBoundDisconnect) Marshal() protocol.Packet { 12 | return protocol.MarshalPacket( 13 | ClientBoundDisconnectPacketID, 14 | pk.Reason, 15 | ) 16 | } 17 | -------------------------------------------------------------------------------- /protocol/status/clientbound_pong.go: -------------------------------------------------------------------------------- 1 | package status 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ClientBoundPongPacketID byte = 0x01 8 | 9 | type ClientBoundPong struct { 10 | Payload protocol.Long 11 | } 12 | 13 | func (pk ClientBoundPong) Marshal() protocol.Packet { 14 | return protocol.MarshalPacket( 15 | ClientBoundPongPacketID, 16 | pk.Payload, 17 | ) 18 | } 19 | 20 | func UnmarshalClientBoundPong(packet protocol.Packet) (ClientBoundPong, error) { 21 | var pk ClientBoundPong 22 | 23 | if packet.ID != ClientBoundPongPacketID { 24 | return pk, protocol.ErrInvalidPacketID 25 | } 26 | 27 | if err := packet.Scan( 28 | &pk.Payload, 29 | ); err != nil { 30 | return pk, err 31 | } 32 | 33 | return pk, nil 34 | } 35 | -------------------------------------------------------------------------------- /protocol/status/clientbound_response.go: -------------------------------------------------------------------------------- 1 | package status 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/haveachin/infrared/protocol" 6 | ) 7 | 8 | const ClientBoundResponsePacketID byte = 0x00 9 | 10 | type ClientBoundResponse struct { 11 | JSONResponse protocol.String 12 | } 13 | 14 | func (pk ClientBoundResponse) Marshal() protocol.Packet { 15 | return protocol.MarshalPacket( 16 | ClientBoundResponsePacketID, 17 | pk.JSONResponse, 18 | ) 19 | } 20 | 21 | func UnmarshalClientBoundResponse(packet protocol.Packet) (ClientBoundResponse, error) { 22 | var pk ClientBoundResponse 23 | 24 | if packet.ID != ClientBoundResponsePacketID { 25 | return pk, protocol.ErrInvalidPacketID 26 | } 27 | 28 | if err := packet.Scan( 29 | &pk.JSONResponse, 30 | ); err != nil { 31 | return pk, err 32 | } 33 | 34 | return pk, nil 35 | } 36 | 37 | type ResponseJSON struct { 38 | Version VersionJSON `json:"version"` 39 | Players PlayersJSON `json:"players"` 40 | Description json.RawMessage `json:"description"` 41 | Favicon string `json:"favicon"` 42 | } 43 | 44 | type VersionJSON struct { 45 | Name string `json:"name"` 46 | Protocol int `json:"protocol"` 47 | } 48 | 49 | type PlayersJSON struct { 50 | Max int `json:"max"` 51 | Online int `json:"online"` 52 | Sample []PlayerSampleJSON `json:"sample"` 53 | } 54 | 55 | type PlayerSampleJSON struct { 56 | Name string `json:"name"` 57 | ID string `json:"id"` 58 | } 59 | 60 | type DescriptionJSON struct { 61 | Text string `json:"text"` 62 | } 63 | -------------------------------------------------------------------------------- /protocol/status/clientbound_response_test.go: -------------------------------------------------------------------------------- 1 | package status 2 | 3 | import ( 4 | "bytes" 5 | "github.com/haveachin/infrared/protocol" 6 | "testing" 7 | ) 8 | 9 | func TestClientBoundResponse_Marshal(t *testing.T) { 10 | tt := []struct { 11 | packet ClientBoundResponse 12 | marshaledPacket protocol.Packet 13 | }{ 14 | { 15 | packet: ClientBoundResponse{ 16 | JSONResponse: protocol.String(""), 17 | }, 18 | marshaledPacket: protocol.Packet{ 19 | ID: 0x00, 20 | Data: []byte{0x00}, 21 | }, 22 | }, 23 | { 24 | packet: ClientBoundResponse{ 25 | JSONResponse: protocol.String("Hello, World!"), 26 | }, 27 | marshaledPacket: protocol.Packet{ 28 | ID: 0x00, 29 | Data: []byte{0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21}, 30 | }, 31 | }, 32 | } 33 | 34 | for _, tc := range tt { 35 | pk := tc.packet.Marshal() 36 | 37 | if pk.ID != ClientBoundResponsePacketID { 38 | t.Error("invalid packet id") 39 | } 40 | 41 | if !bytes.Equal(pk.Data, tc.marshaledPacket.Data) { 42 | t.Errorf("got: %v, want: %v", pk.Data, tc.marshaledPacket.Data) 43 | } 44 | } 45 | } 46 | 47 | func TestUnmarshalClientBoundResponse(t *testing.T) { 48 | tt := []struct { 49 | packet protocol.Packet 50 | unmarshalledPacket ClientBoundResponse 51 | }{ 52 | { 53 | packet: protocol.Packet{ 54 | ID: 0x00, 55 | Data: []byte{0x00}, 56 | }, 57 | unmarshalledPacket: ClientBoundResponse{ 58 | JSONResponse: "", 59 | }, 60 | }, 61 | { 62 | packet: protocol.Packet{ 63 | ID: 0x00, 64 | Data: []byte{0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21}, 65 | }, 66 | unmarshalledPacket: ClientBoundResponse{ 67 | JSONResponse: protocol.String("Hello, World!"), 68 | }, 69 | }, 70 | } 71 | 72 | for _, tc := range tt { 73 | actual, err := UnmarshalClientBoundResponse(tc.packet) 74 | if err != nil { 75 | t.Error(err) 76 | } 77 | 78 | expected := tc.unmarshalledPacket 79 | 80 | if actual.JSONResponse != expected.JSONResponse { 81 | t.Errorf("got: %v, want: %v", actual, expected) 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /protocol/status/serverbound_ping.go: -------------------------------------------------------------------------------- 1 | package status 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ServerBoundPingPacketID byte = 0x01 8 | 9 | type ServerBoundPing struct { 10 | Payload protocol.Long 11 | } 12 | 13 | func (pk ServerBoundPing) Marshal() protocol.Packet { 14 | return protocol.MarshalPacket( 15 | ServerBoundPingPacketID, 16 | pk.Payload, 17 | ) 18 | } 19 | 20 | func UnmarshalServerBoundPing(packet protocol.Packet) (ServerBoundPing, error) { 21 | var pk ServerBoundPing 22 | 23 | if packet.ID != ServerBoundPingPacketID { 24 | return pk, protocol.ErrInvalidPacketID 25 | } 26 | 27 | if err := packet.Scan( 28 | &pk.Payload, 29 | ); err != nil { 30 | return pk, err 31 | } 32 | 33 | return pk, nil 34 | } 35 | -------------------------------------------------------------------------------- /protocol/status/serverbound_request.go: -------------------------------------------------------------------------------- 1 | package status 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | ) 6 | 7 | const ServerBoundRequestPacketID byte = 0x00 8 | 9 | type ServerBoundRequest struct{} 10 | 11 | func (pk ServerBoundRequest) Marshal() protocol.Packet { 12 | return protocol.MarshalPacket( 13 | ServerBoundRequestPacketID, 14 | ) 15 | } 16 | 17 | func UnmarshalServerBoundRequest(packet protocol.Packet) (ServerBoundRequest, error) { 18 | var pk ServerBoundRequest 19 | 20 | if packet.ID != ServerBoundRequestPacketID { 21 | return pk, protocol.ErrInvalidPacketID 22 | } 23 | 24 | return pk, nil 25 | } 26 | -------------------------------------------------------------------------------- /protocol/status/serverbound_request_test.go: -------------------------------------------------------------------------------- 1 | package status 2 | 3 | import ( 4 | "github.com/haveachin/infrared/protocol" 5 | "testing" 6 | ) 7 | 8 | func TestServerBoundRequest_Marshal(t *testing.T) { 9 | tt := []struct { 10 | packet ServerBoundRequest 11 | marshaledPacket protocol.Packet 12 | }{ 13 | { 14 | packet: ServerBoundRequest{}, 15 | marshaledPacket: protocol.Packet{ 16 | ID: 0x00, 17 | Data: []byte{}, 18 | }, 19 | }, 20 | } 21 | 22 | for _, tc := range tt { 23 | pk := tc.packet.Marshal() 24 | 25 | if pk.ID != ServerBoundRequestPacketID { 26 | t.Error("invalid packet id") 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /protocol/types.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "github.com/gofrs/uuid" 7 | "io" 8 | ) 9 | 10 | // A Field is both FieldEncoder and FieldDecoder 11 | type Field interface { 12 | FieldEncoder 13 | FieldDecoder 14 | } 15 | 16 | // A FieldEncoder can be encode as minecraft protocol used. 17 | type FieldEncoder interface { 18 | Encode() []byte 19 | } 20 | 21 | // A FieldDecoder can Decode from minecraft protocol 22 | type FieldDecoder interface { 23 | Decode(r DecodeReader) error 24 | } 25 | 26 | //DecodeReader is both io.Reader and io.ByteReader 27 | type DecodeReader interface { 28 | io.ByteReader 29 | io.Reader 30 | } 31 | 32 | type ( 33 | // Boolean of True is encoded as 0x01, false as 0x00. 34 | Boolean bool 35 | // Byte is signed 8-bit integer, two's complement 36 | Byte int8 37 | // UnsignedShort is unsigned 16-bit integer 38 | UnsignedShort uint16 39 | // Long is signed 64-bit integer, two's complement 40 | Long int64 41 | // String is sequence of Unicode scalar values 42 | String string 43 | 44 | // Chat is encoded as a String with max length of 32767. 45 | Chat = String 46 | // Identifier is encoded as a String with max length of 32767. 47 | Identifier = String 48 | 49 | // VarInt is variable-length data encoding a two's complement signed 32-bit integer 50 | VarInt int32 51 | 52 | // UUID encoded as an unsigned 128-bit integer 53 | UUID uuid.UUID 54 | 55 | // ByteArray is []byte with prefix VarInt as length 56 | ByteArray []byte 57 | 58 | // OptionalByteArray is []byte without prefix VarInt as length 59 | OptionalByteArray []byte 60 | ) 61 | 62 | // ReadNBytes read N bytes from bytes.Reader 63 | func ReadNBytes(r DecodeReader, n int) ([]byte, error) { 64 | bb := make([]byte, n) 65 | var err error 66 | for i := 0; i < n; i++ { 67 | bb[i], err = r.ReadByte() 68 | if err != nil { 69 | return nil, err 70 | } 71 | } 72 | return bb, nil 73 | } 74 | 75 | // Encode a Boolean 76 | func (b Boolean) Encode() []byte { 77 | if b { 78 | return []byte{0x01} 79 | } 80 | return []byte{0x00} 81 | } 82 | 83 | // Decode a Boolean 84 | func (b *Boolean) Decode(r DecodeReader) error { 85 | v, err := r.ReadByte() 86 | if err != nil { 87 | return err 88 | } 89 | 90 | *b = v != 0 91 | return nil 92 | } 93 | 94 | // Encode a String 95 | func (s String) Encode() []byte { 96 | byteString := []byte(s) 97 | var bb []byte 98 | bb = append(bb, VarInt(len(byteString)).Encode()...) // len 99 | bb = append(bb, byteString...) // data 100 | return bb 101 | } 102 | 103 | // Decode a String 104 | func (s *String) Decode(r DecodeReader) error { 105 | var l VarInt // String length 106 | if err := l.Decode(r); err != nil { 107 | return err 108 | } 109 | 110 | bb, err := ReadNBytes(r, int(l)) 111 | if err != nil { 112 | return err 113 | } 114 | 115 | *s = String(bb) 116 | return nil 117 | } 118 | 119 | // Encode a Byte 120 | func (b Byte) Encode() []byte { 121 | return []byte{byte(b)} 122 | } 123 | 124 | // Decode a Byte 125 | func (b *Byte) Decode(r DecodeReader) error { 126 | v, err := r.ReadByte() 127 | if err != nil { 128 | return err 129 | } 130 | *b = Byte(v) 131 | return nil 132 | } 133 | 134 | // Encode a Unsigned Short 135 | func (us UnsignedShort) Encode() []byte { 136 | n := uint16(us) 137 | return []byte{ 138 | byte(n >> 8), 139 | byte(n), 140 | } 141 | } 142 | 143 | // Decode a UnsignedShort 144 | func (us *UnsignedShort) Decode(r DecodeReader) error { 145 | bb, err := ReadNBytes(r, 2) 146 | if err != nil { 147 | return err 148 | } 149 | 150 | *us = UnsignedShort(int16(bb[0])<<8 | int16(bb[1])) 151 | return nil 152 | } 153 | 154 | // Encode a Long 155 | func (l Long) Encode() []byte { 156 | n := uint64(l) 157 | return []byte{ 158 | byte(n >> 56), byte(n >> 48), byte(n >> 40), byte(n >> 32), 159 | byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n), 160 | } 161 | } 162 | 163 | // Decode a Long 164 | func (l *Long) Decode(r DecodeReader) error { 165 | bb, err := ReadNBytes(r, 8) 166 | if err != nil { 167 | return err 168 | } 169 | 170 | *l = Long(int64(bb[0])<<56 | int64(bb[1])<<48 | int64(bb[2])<<40 | int64(bb[3])<<32 | 171 | int64(bb[4])<<24 | int64(bb[5])<<16 | int64(bb[6])<<8 | int64(bb[7])) 172 | return nil 173 | } 174 | 175 | // Encode a VarInt 176 | func (v VarInt) Encode() []byte { 177 | num := uint32(v) 178 | var bb []byte 179 | for { 180 | b := num & 0x7F 181 | num >>= 7 182 | if num != 0 { 183 | b |= 0x80 184 | } 185 | bb = append(bb, byte(b)) 186 | if num == 0 { 187 | break 188 | } 189 | } 190 | return bb 191 | } 192 | 193 | // Decode a VarInt 194 | func (v *VarInt) Decode(r DecodeReader) error { 195 | var n uint32 196 | for i := 0; ; i++ { 197 | sec, err := r.ReadByte() 198 | if err != nil { 199 | return err 200 | } 201 | 202 | n |= uint32(sec&0x7F) << uint32(7*i) 203 | 204 | if i >= 5 { 205 | return errors.New("VarInt is too big") 206 | } else if sec&0x80 == 0 { 207 | break 208 | } 209 | } 210 | 211 | *v = VarInt(n) 212 | return nil 213 | } 214 | 215 | // Encode a ByteArray 216 | func (b ByteArray) Encode() []byte { 217 | return append(VarInt(len(b)).Encode(), b...) 218 | } 219 | 220 | // Decode a ByteArray 221 | func (b *ByteArray) Decode(r DecodeReader) error { 222 | var length VarInt 223 | if err := length.Decode(r); err != nil { 224 | return err 225 | } 226 | *b = make([]byte, length) 227 | _, err := r.Read(*b) 228 | return err 229 | } 230 | 231 | // Encode a UUID 232 | func (u UUID) Encode() []byte { 233 | return u[:] 234 | } 235 | 236 | // Decode a UUID 237 | func (u *UUID) Decode(r DecodeReader) error { 238 | _, err := io.ReadFull(r, (*u)[:]) 239 | return err 240 | } 241 | 242 | // Encode a OptionalByteArray 243 | func (b OptionalByteArray) Encode() []byte { 244 | return b 245 | } 246 | 247 | // Decode a OptionalByteArray 248 | func (b *OptionalByteArray) Decode(r DecodeReader) error { 249 | buf := bytes.NewBuffer([]byte{}) 250 | _, err := buf.ReadFrom(r) 251 | if err != nil { 252 | return err 253 | } 254 | *b = buf.Bytes() 255 | return nil 256 | } 257 | -------------------------------------------------------------------------------- /protocol/types_test.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "bytes" 5 | "github.com/gofrs/uuid" 6 | "io" 7 | "testing" 8 | ) 9 | 10 | func TestReadNBytes(t *testing.T) { 11 | tt := [][]byte{ 12 | {0x00, 0x01, 0x02, 0x03}, 13 | {0x03, 0x01, 0x02, 0x02}, 14 | } 15 | 16 | for _, tc := range tt { 17 | bb, err := ReadNBytes(bytes.NewBuffer(tc), len(tc)) 18 | if err != nil { 19 | t.Errorf("reading bytes: %s", err) 20 | } 21 | 22 | if !bytes.Equal(bb, tc) { 23 | t.Errorf("got %v; want: %v", bb, tc) 24 | } 25 | } 26 | } 27 | 28 | var booleanTestTable = []struct { 29 | decoded Boolean 30 | encoded []byte 31 | }{ 32 | { 33 | decoded: Boolean(false), 34 | encoded: []byte{0x00}, 35 | }, 36 | { 37 | decoded: Boolean(true), 38 | encoded: []byte{0x01}, 39 | }, 40 | } 41 | 42 | func TestBoolean_Encode(t *testing.T) { 43 | for _, tc := range booleanTestTable { 44 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 45 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 46 | } 47 | } 48 | } 49 | 50 | func TestBoolean_Decode(t *testing.T) { 51 | for _, tc := range booleanTestTable { 52 | var actualDecoded Boolean 53 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 54 | t.Errorf("decoding: %s", err) 55 | } 56 | 57 | if actualDecoded != tc.decoded { 58 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 59 | } 60 | } 61 | } 62 | 63 | var varIntTestTable = []struct { 64 | decoded VarInt 65 | encoded []byte 66 | }{ 67 | { 68 | decoded: VarInt(0), 69 | encoded: []byte{0x00}, 70 | }, 71 | { 72 | decoded: VarInt(1), 73 | encoded: []byte{0x01}, 74 | }, 75 | { 76 | decoded: VarInt(2), 77 | encoded: []byte{0x02}, 78 | }, 79 | { 80 | decoded: VarInt(127), 81 | encoded: []byte{0x7f}, 82 | }, 83 | { 84 | decoded: VarInt(128), 85 | encoded: []byte{0x80, 0x01}, 86 | }, 87 | { 88 | decoded: VarInt(255), 89 | encoded: []byte{0xff, 0x01}, 90 | }, 91 | { 92 | decoded: VarInt(2097151), 93 | encoded: []byte{0xff, 0xff, 0x7f}, 94 | }, 95 | { 96 | decoded: VarInt(2147483647), 97 | encoded: []byte{0xff, 0xff, 0xff, 0xff, 0x07}, 98 | }, 99 | { 100 | decoded: VarInt(-1), 101 | encoded: []byte{0xff, 0xff, 0xff, 0xff, 0x0f}, 102 | }, 103 | { 104 | decoded: VarInt(-2147483648), 105 | encoded: []byte{0x80, 0x80, 0x80, 0x80, 0x08}, 106 | }, 107 | } 108 | 109 | func TestVarInt_Encode(t *testing.T) { 110 | for _, tc := range varIntTestTable { 111 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 112 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 113 | } 114 | } 115 | } 116 | 117 | func TestVarInt_Decode(t *testing.T) { 118 | for _, tc := range varIntTestTable { 119 | var actualDecoded VarInt 120 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 121 | t.Errorf("decoding: %s", err) 122 | } 123 | 124 | if actualDecoded != tc.decoded { 125 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 126 | } 127 | } 128 | } 129 | 130 | var stringTestTable = []struct { 131 | decoded String 132 | encoded []byte 133 | }{ 134 | { 135 | decoded: String(""), 136 | encoded: []byte{0x00}, 137 | }, 138 | { 139 | decoded: String("Hello, World!"), 140 | encoded: []byte{0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21}, 141 | }, 142 | { 143 | decoded: String("Minecraft"), 144 | encoded: []byte{0x09, 0x4d, 0x69, 0x6e, 0x65, 0x63, 0x72, 0x61, 0x66, 0x74}, 145 | }, 146 | { 147 | decoded: String("♥"), 148 | encoded: []byte{0x03, 0xe2, 0x99, 0xa5}, 149 | }, 150 | } 151 | 152 | func TestString_Encode(t *testing.T) { 153 | for _, tc := range stringTestTable { 154 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 155 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 156 | } 157 | } 158 | } 159 | 160 | func TestString_Decode(t *testing.T) { 161 | for _, tc := range stringTestTable { 162 | var actualDecoded String 163 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 164 | t.Errorf("decoding: %s", err) 165 | } 166 | 167 | if actualDecoded != tc.decoded { 168 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 169 | } 170 | } 171 | } 172 | 173 | var byteTestTable = []struct { 174 | decoded Byte 175 | encoded []byte 176 | }{ 177 | { 178 | decoded: Byte(0x00), 179 | encoded: []byte{0x00}, 180 | }, 181 | { 182 | decoded: Byte(0x0f), 183 | encoded: []byte{0x0f}, 184 | }, 185 | } 186 | 187 | func TestByte_Encode(t *testing.T) { 188 | for _, tc := range byteTestTable { 189 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 190 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 191 | } 192 | } 193 | } 194 | 195 | func TestByte_Decode(t *testing.T) { 196 | for _, tc := range byteTestTable { 197 | var actualDecoded Byte 198 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 199 | t.Errorf("decoding: %s", err) 200 | } 201 | 202 | if actualDecoded != tc.decoded { 203 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 204 | } 205 | } 206 | } 207 | 208 | var unsignedShortTestTable = []struct { 209 | decoded UnsignedShort 210 | encoded []byte 211 | }{ 212 | { 213 | decoded: UnsignedShort(0), 214 | encoded: []byte{0x00, 0x00}, 215 | }, 216 | { 217 | decoded: UnsignedShort(15), 218 | encoded: []byte{0x00, 0x0f}, 219 | }, 220 | { 221 | decoded: UnsignedShort(16), 222 | encoded: []byte{0x00, 0x10}, 223 | }, 224 | { 225 | decoded: UnsignedShort(255), 226 | encoded: []byte{0x00, 0xff}, 227 | }, 228 | { 229 | decoded: UnsignedShort(256), 230 | encoded: []byte{0x01, 0x00}, 231 | }, 232 | { 233 | decoded: UnsignedShort(65535), 234 | encoded: []byte{0xff, 0xff}, 235 | }, 236 | } 237 | 238 | func TestUnsignedShort_Encode(t *testing.T) { 239 | for _, tc := range unsignedShortTestTable { 240 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 241 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 242 | } 243 | } 244 | } 245 | 246 | func TestUnsignedShort_Decode(t *testing.T) { 247 | for _, tc := range unsignedShortTestTable { 248 | var actualDecoded UnsignedShort 249 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 250 | t.Errorf("decoding: %s", err) 251 | } 252 | 253 | if actualDecoded != tc.decoded { 254 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 255 | } 256 | } 257 | } 258 | 259 | var longTestTable = []struct { 260 | decoded Long 261 | encoded []byte 262 | }{ 263 | { 264 | decoded: Long(-9223372036854775808), 265 | encoded: []byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 266 | }, 267 | { 268 | decoded: Long(0), 269 | encoded: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 270 | }, 271 | { 272 | decoded: Long(15), 273 | encoded: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f}, 274 | }, 275 | { 276 | decoded: Long(16), 277 | encoded: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10}, 278 | }, 279 | { 280 | decoded: Long(9223372036854775807), 281 | encoded: []byte{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, 282 | }, 283 | } 284 | 285 | func TestLong_Encode(t *testing.T) { 286 | for _, tc := range longTestTable { 287 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 288 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 289 | } 290 | } 291 | } 292 | 293 | func TestLong_Decode(t *testing.T) { 294 | for _, tc := range longTestTable { 295 | var actualDecoded Long 296 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 297 | t.Errorf("decoding: %s", err) 298 | } 299 | 300 | if actualDecoded != tc.decoded { 301 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 302 | } 303 | } 304 | } 305 | 306 | var byteArrayTestTable = []struct { 307 | decoded ByteArray 308 | encoded []byte 309 | }{ 310 | { 311 | decoded: ByteArray([]byte{}), 312 | encoded: []byte{0x00}, 313 | }, 314 | { 315 | decoded: ByteArray([]byte{0x00}), 316 | encoded: []byte{0x01, 0x00}, 317 | }, 318 | } 319 | 320 | func TestByteArray_Encode(t *testing.T) { 321 | for _, tc := range byteArrayTestTable { 322 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 323 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 324 | } 325 | } 326 | } 327 | 328 | func TestByteArray_Decode(t *testing.T) { 329 | for _, tc := range byteArrayTestTable { 330 | actualDecoded := ByteArray([]byte{}) 331 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 332 | if err != io.EOF { 333 | t.Errorf("decoding: %s", err) 334 | } 335 | } 336 | 337 | if !bytes.Equal(actualDecoded, tc.decoded) { 338 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 339 | } 340 | } 341 | } 342 | 343 | var optionalByteArrayTestTable = []struct { 344 | decoded OptionalByteArray 345 | encoded []byte 346 | }{ 347 | { 348 | decoded: OptionalByteArray([]byte{}), 349 | encoded: []byte{}, 350 | }, 351 | { 352 | decoded: OptionalByteArray([]byte{0x00}), 353 | encoded: []byte{0x00}, 354 | }, 355 | } 356 | 357 | func TestOptionalByteArray_Encode(t *testing.T) { 358 | for _, tc := range optionalByteArrayTestTable { 359 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 360 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 361 | } 362 | } 363 | } 364 | 365 | func TestOptionalByteArray_Decode(t *testing.T) { 366 | for _, tc := range optionalByteArrayTestTable { 367 | actualDecoded := OptionalByteArray([]byte{}) 368 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 369 | if err != io.EOF { 370 | t.Errorf("decoding: %s", err) 371 | } 372 | } 373 | 374 | if !bytes.Equal(actualDecoded, tc.decoded) { 375 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 376 | } 377 | } 378 | } 379 | 380 | var uuidTestTable = []struct { 381 | decoded UUID 382 | encoded []byte 383 | }{ 384 | { 385 | decoded: UUID(uuid.UUID{}), 386 | encoded: []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 387 | }, 388 | { 389 | decoded: UUID(uuid.UUID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}), 390 | encoded: []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, 391 | }, 392 | } 393 | 394 | func TestUUID_Encode(t *testing.T) { 395 | for _, tc := range uuidTestTable { 396 | if !bytes.Equal(tc.decoded.Encode(), tc.encoded) { 397 | t.Errorf("encoding: got: %v; want: %v", tc.decoded.Encode(), tc.encoded) 398 | } 399 | } 400 | } 401 | 402 | func TestUUID_Decode(t *testing.T) { 403 | for _, tc := range uuidTestTable { 404 | var actualDecoded UUID 405 | if err := actualDecoded.Decode(bytes.NewReader(tc.encoded)); err != nil { 406 | if err != io.EOF { 407 | t.Errorf("decoding: %s", err) 408 | } 409 | } 410 | 411 | if actualDecoded != tc.decoded { 412 | t.Errorf("decoding: got %v; want: %v", actualDecoded, tc.decoded) 413 | } 414 | } 415 | } 416 | -------------------------------------------------------------------------------- /proxy.go: -------------------------------------------------------------------------------- 1 | package infrared 2 | 3 | import ( 4 | "fmt" 5 | "github.com/haveachin/infrared/protocol" 6 | "github.com/haveachin/infrared/protocol/handshaking" 7 | "github.com/haveachin/infrared/protocol/login" 8 | "github.com/haveachin/infrared/protocol/status" 9 | "github.com/pires/go-proxyproto" 10 | "github.com/prometheus/client_golang/prometheus" 11 | "github.com/prometheus/client_golang/prometheus/promauto" 12 | "log" 13 | "net" 14 | "strconv" 15 | "strings" 16 | "sync" 17 | "time" 18 | ) 19 | 20 | var ( 21 | playersConnected = promauto.NewGaugeVec(prometheus.GaugeOpts{ 22 | Name: "infrared_connected", 23 | Help: "The total number of connected players", 24 | }, []string{"host"}) 25 | ) 26 | 27 | func proxyUID(domain, addr string) string { 28 | return fmt.Sprintf("%s@%s", strings.ToLower(domain), addr) 29 | } 30 | 31 | type Proxy struct { 32 | Config *ProxyConfig 33 | 34 | cancelTimeoutFunc func() 35 | mu sync.Mutex 36 | 37 | cacheOnlineTime time.Time 38 | cacheStatusTime sync.Map 39 | cacheStatusRes sync.Map 40 | cacheOnlineStatus bool 41 | 42 | usedBandwith int 43 | } 44 | 45 | func (proxy *Proxy) DomainNames() []string { 46 | proxy.Config.RLock() 47 | defer proxy.Config.RUnlock() 48 | return proxy.Config.DomainNames 49 | } 50 | 51 | func (proxy *Proxy) DomainName() string { 52 | proxy.Config.RLock() 53 | defer proxy.Config.RUnlock() 54 | return proxy.Config.DomainNames[0] 55 | } 56 | 57 | func (proxy *Proxy) ListenTo() string { 58 | proxy.Config.RLock() 59 | defer proxy.Config.RUnlock() 60 | return proxy.Config.ListenTo 61 | } 62 | 63 | func (proxy *Proxy) ProxyTo() string { 64 | proxy.Config.RLock() 65 | defer proxy.Config.RUnlock() 66 | return proxy.Config.ProxyTo 67 | } 68 | 69 | func (proxy *Proxy) Dialer() (*Dialer, error) { 70 | proxy.Config.RLock() 71 | defer proxy.Config.RUnlock() 72 | return proxy.Config.Dialer() 73 | } 74 | 75 | func (proxy *Proxy) DisconnectMessage() string { 76 | proxy.Config.RLock() 77 | defer proxy.Config.RUnlock() 78 | return proxy.Config.DisconnectMessage 79 | } 80 | 81 | func (proxy *Proxy) IsOnlineStatusConfigured() bool { 82 | proxy.Config.Lock() 83 | defer proxy.Config.Unlock() 84 | return proxy.Config.OnlineStatus.ProtocolNumber != 0 85 | } 86 | 87 | func (proxy *Proxy) OnlineStatusPacket() (protocol.Packet, error) { 88 | proxy.Config.Lock() 89 | defer proxy.Config.Unlock() 90 | return proxy.Config.OnlineStatus.StatusResponsePacket() 91 | } 92 | 93 | func (proxy *Proxy) OfflineStatusPacket() (protocol.Packet, error) { 94 | proxy.Config.Lock() 95 | defer proxy.Config.Unlock() 96 | return proxy.Config.OfflineStatus.StatusResponsePacket() 97 | } 98 | 99 | func (proxy *Proxy) Timeout() time.Duration { 100 | proxy.Config.RLock() 101 | defer proxy.Config.RUnlock() 102 | return time.Millisecond * time.Duration(proxy.Config.Timeout) 103 | } 104 | 105 | func (proxy *Proxy) ProxyProtocol() bool { 106 | proxy.Config.RLock() 107 | defer proxy.Config.RUnlock() 108 | return proxy.Config.ProxyProtocol 109 | } 110 | 111 | func (proxy *Proxy) RealIP() bool { 112 | proxy.Config.RLock() 113 | defer proxy.Config.RUnlock() 114 | return proxy.Config.RealIP 115 | } 116 | 117 | func (proxy *Proxy) UID() string { 118 | return proxyUID(proxy.DomainName(), proxy.ListenTo()) 119 | } 120 | 121 | func (proxy *Proxy) UIDs() []string { 122 | uids := []string{} 123 | for _, domain := range proxy.DomainNames() { 124 | uid := proxyUID(domain, proxy.ListenTo()) 125 | uids = append(uids, uid) 126 | } 127 | return uids 128 | } 129 | 130 | func (proxy *Proxy) handleLoginConnection(conn Conn, session Session) error { 131 | hs, err := handshaking.UnmarshalServerBoundHandshake(session.handshakePacket) 132 | if err != nil { 133 | return err 134 | } 135 | 136 | proxyDomain := proxy.DomainName() 137 | proxyTo := proxy.ProxyTo() 138 | 139 | dialer, err := proxy.Dialer() 140 | if err != nil { 141 | return err 142 | } 143 | 144 | if !proxy.cacheOnlineStatus && time.Now().Sub(proxy.cacheOnlineTime) < 10*time.Second { 145 | return proxy.handleLoginRequest(conn, session) 146 | } 147 | 148 | rconn, err := dialer.Dial(proxyTo) 149 | if err != nil { 150 | log.Printf("[i] %s did not respond to ping; is the target offline?", proxyTo) 151 | proxy.cacheOnlineStatus = false 152 | proxy.cacheOnlineTime = time.Now() 153 | return proxy.handleLoginRequest(conn, session) 154 | } 155 | proxy.cacheOnlineStatus = true 156 | proxy.cacheOnlineTime = time.Now() 157 | defer rconn.Close() 158 | 159 | if proxy.ProxyProtocol() { 160 | header := &proxyproto.Header{ 161 | Version: 2, 162 | Command: proxyproto.PROXY, 163 | TransportProtocol: proxyproto.TCPv4, 164 | SourceAddr: session.connRemoteAddr, 165 | DestinationAddr: rconn.RemoteAddr(), 166 | } 167 | 168 | if net.ParseIP(session.connRemoteAddr.String()).To4() == nil { 169 | header.TransportProtocol = proxyproto.TCPv6 170 | } 171 | 172 | if _, err = header.WriteTo(rconn); err != nil { 173 | return err 174 | } 175 | } 176 | 177 | if proxy.RealIP() { 178 | hs.UpgradeToRealIP(session.connRemoteAddr, time.Now()) 179 | session.handshakePacket = hs.Marshal() 180 | } 181 | 182 | if err := rconn.WritePacket(session.handshakePacket); err != nil { 183 | return err 184 | } 185 | 186 | err = rconn.WritePacket(session.loginPacket) 187 | if err != nil { 188 | return err 189 | } 190 | log.Printf("[i] %s with username %s connects through %s", session.connRemoteAddr, session.username, proxy.UID()) 191 | playersConnected.With(prometheus.Labels{"host": proxyDomain}).Inc() 192 | defer playersConnected.With(prometheus.Labels{"host": proxyDomain}).Dec() 193 | 194 | go pipe(rconn, conn, proxy) 195 | pipe(conn, rconn, proxy) 196 | return nil 197 | } 198 | 199 | func (proxy *Proxy) handleStatusConnection(conn Conn, session Session) error { 200 | proxyTo := proxy.ProxyTo() 201 | proxyUID := proxy.UID() 202 | 203 | hs, err := handshaking.UnmarshalServerBoundHandshake(session.handshakePacket) 204 | if err != nil { 205 | return err 206 | } 207 | 208 | statusRequest, err := conn.ReadPacket(true) 209 | if err != nil { 210 | return err 211 | } 212 | 213 | _, err = status.UnmarshalServerBoundRequest(statusRequest) 214 | if err != nil { 215 | return err 216 | } 217 | 218 | _ = conn.SetDeadline(time.Time{}) 219 | 220 | if proxy.IsOnlineStatusConfigured() { 221 | return proxy.handleStatusRequest(conn, true) 222 | } 223 | 224 | proto := int32(hs.ProtocolVersion) 225 | 226 | var cachetime time.Time 227 | entry, ok := proxy.cacheStatusTime.Load(proto) 228 | if !ok { 229 | cachetime = time.Time{} 230 | } else { 231 | cachetime = entry.(time.Time) 232 | } 233 | if !ok || cachetime.IsZero() || time.Now().Sub(cachetime) > 10*time.Second { 234 | proxy.mu.Lock() 235 | defer proxy.mu.Unlock() 236 | 237 | proxy.cacheStatusTime.Store(proto, time.Now()) 238 | 239 | dialer, err := proxy.Dialer() 240 | if err != nil { 241 | return err 242 | } 243 | 244 | rconn, err := dialer.Dial(proxyTo) 245 | if err != nil { 246 | log.Printf("[i] Failed to update cache for %s, %s did not respond: %s", proxyUID, proxyTo, err) 247 | proxy.cacheOnlineStatus = false 248 | proxy.cacheStatusTime.Store(proto, time.Now()) 249 | proxy.cacheStatusRes.Store(proto, status.ClientBoundResponse{}) 250 | 251 | return proxy.handleStatusRequest(conn, false) 252 | } 253 | 254 | if proxy.RealIP() { 255 | hs.UpgradeToRealIP(session.connRemoteAddr, time.Now()) 256 | session.handshakePacket = hs.Marshal() 257 | } 258 | 259 | if proxy.ProxyProtocol() { 260 | header := &proxyproto.Header{ 261 | Version: 2, 262 | Command: proxyproto.PROXY, 263 | TransportProtocol: proxyproto.TCPv4, 264 | SourceAddr: session.connRemoteAddr, 265 | DestinationAddr: rconn.RemoteAddr(), 266 | } 267 | 268 | if net.ParseIP(session.connRemoteAddr.String()).To4() == nil { 269 | header.TransportProtocol = proxyproto.TCPv6 270 | } 271 | 272 | if _, err = header.WriteTo(rconn); err != nil { 273 | return err 274 | } 275 | } 276 | 277 | _, portString, _ := net.SplitHostPort(proxyTo) 278 | port, err := strconv.ParseInt(portString, 10, 16) 279 | 280 | err = rconn.WritePacket(handshaking.ServerBoundHandshake{ 281 | ProtocolVersion: hs.ProtocolVersion, 282 | ServerAddress: protocol.String(proxy.DomainName()), 283 | ServerPort: protocol.UnsignedShort(port), 284 | NextState: 1, 285 | }.Marshal()) 286 | if err != nil { 287 | return err 288 | } 289 | 290 | err = rconn.WritePacket(statusRequest) 291 | if err != nil { 292 | return err 293 | } 294 | 295 | clientboundResponsePacket, err := rconn.ReadPacket(false) 296 | if err != nil { 297 | return fmt.Errorf("failed to read status response: %s", err) 298 | } 299 | clientboundResponse, err := status.UnmarshalClientBoundResponse(clientboundResponsePacket) 300 | if err != nil { 301 | return fmt.Errorf("failed to unmarshal status response: %s", err) 302 | } 303 | 304 | proxy.cacheOnlineStatus = true 305 | proxy.cacheStatusTime.Store(proto, time.Now()) 306 | proxy.cacheStatusRes.Store(proto, clientboundResponse) 307 | 308 | rconn.Close() 309 | } 310 | 311 | if !proxy.cacheOnlineStatus { 312 | if Config.Debug { 313 | log.Printf("[i] Sent %s cached offline response for %s", session.connRemoteAddr, proxyUID) 314 | } 315 | return proxy.handleStatusRequest(conn, false) 316 | } 317 | 318 | entry, ok = proxy.cacheStatusRes.Load(proto) 319 | if !ok { 320 | return fmt.Errorf("failed to get cache status response") 321 | } 322 | res := entry.(status.ClientBoundResponse) 323 | 324 | err = conn.WritePacket(status.ClientBoundResponse{ 325 | JSONResponse: res.JSONResponse, 326 | }.Marshal()) 327 | if err != nil { 328 | return err 329 | } 330 | 331 | pingPacket, err := conn.ReadPacket(true) 332 | if err != nil { 333 | return err 334 | } 335 | 336 | ping, err := status.UnmarshalServerBoundPing(pingPacket) 337 | if err != nil { 338 | return err 339 | } 340 | 341 | err = conn.WritePacket(status.ClientBoundPong{ 342 | Payload: ping.Payload, 343 | }.Marshal()) 344 | if err != nil { 345 | return err 346 | } 347 | 348 | if Config.Debug { 349 | log.Printf("[i] Sent %s cached response for %s, proto version %d", session.connRemoteAddr, proxyUID, proto) 350 | } 351 | return nil 352 | } 353 | 354 | func pipe(src, dst Conn, proxy *Proxy) { 355 | buffer := make([]byte, 0xffff) 356 | 357 | for { 358 | n, err := src.Read(buffer) 359 | if err != nil { 360 | return 361 | } 362 | 363 | data := buffer[:n] 364 | 365 | _, err = dst.Write(data) 366 | if err != nil { 367 | return 368 | } 369 | 370 | if Config.TrackBandwidth { 371 | proxy.usedBandwith = proxy.usedBandwith + len(data) 372 | } 373 | } 374 | } 375 | 376 | func (proxy *Proxy) handleLoginRequest(conn Conn, session Session) error { 377 | message := proxy.DisconnectMessage() 378 | templates := map[string]string{ 379 | "username": session.username, 380 | "now": time.Now().Format(time.RFC822), 381 | "remoteAddress": conn.LocalAddr().String(), 382 | "localAddress": conn.LocalAddr().String(), 383 | "domain": proxy.DomainName(), 384 | "proxyTo": proxy.ProxyTo(), 385 | "listenTo": proxy.ListenTo(), 386 | } 387 | 388 | for key, value := range templates { 389 | message = strings.Replace(message, fmt.Sprintf("{{%s}}", key), value, -1) 390 | } 391 | 392 | return conn.WritePacket(login.ClientBoundDisconnect{ 393 | Reason: protocol.Chat(fmt.Sprintf("{\"text\":\"%s\"}", message)), 394 | }.Marshal()) 395 | } 396 | 397 | func (proxy *Proxy) handleStatusRequest(conn Conn, online bool) error { 398 | var err error 399 | var responsePk protocol.Packet 400 | if online { 401 | responsePk, err = proxy.OnlineStatusPacket() 402 | if err != nil { 403 | return err 404 | } 405 | } else { 406 | responsePk, err = proxy.OfflineStatusPacket() 407 | if err != nil { 408 | return err 409 | } 410 | } 411 | 412 | if err := conn.WritePacket(responsePk); err != nil { 413 | return err 414 | } 415 | 416 | pingPk, err := conn.ReadPacket(true) 417 | if err != nil { 418 | return err 419 | } 420 | 421 | return conn.WritePacket(pingPk) 422 | } 423 | -------------------------------------------------------------------------------- /sha1.go: -------------------------------------------------------------------------------- 1 | package infrared 2 | 3 | import ( 4 | "crypto/sha1" 5 | "fmt" 6 | "hash" 7 | "strings" 8 | ) 9 | 10 | type Sha1Hash struct { 11 | hash.Hash 12 | } 13 | 14 | func NewSha1Hash() Sha1Hash { 15 | return Sha1Hash{ 16 | Hash: sha1.New(), 17 | } 18 | } 19 | 20 | func (h Sha1Hash) Update(b []byte) { 21 | // This will never return an error like documented in hash.Hash 22 | // so ignoring this error is ok 23 | _, _ = h.Write(b) 24 | } 25 | 26 | func (h Sha1Hash) HexDigest() string { 27 | hashBytes := h.Sum(nil) 28 | 29 | negative := (hashBytes[0] & 0x80) == 0x80 30 | if negative { 31 | // two's compliment, big endian 32 | carry := true 33 | for i := len(hashBytes) - 1; i >= 0; i-- { 34 | hashBytes[i] = ^hashBytes[i] 35 | if carry { 36 | carry = hashBytes[i] == 0xff 37 | hashBytes[i]++ 38 | } 39 | } 40 | } 41 | 42 | hashString := strings.TrimLeft(fmt.Sprintf("%x", hashBytes), "0") 43 | if negative { 44 | hashString = "-" + hashString 45 | } 46 | 47 | return hashString 48 | } 49 | --------------------------------------------------------------------------------