├── .github
└── workflows
│ ├── goreleaser_release.yml
│ └── run_simulation_tests.yml
├── .gitignore
├── .goreleaser.yaml
├── Dockerfile
├── LICENSE
├── README.md
├── cmd
└── mmar
│ └── main.go
├── constants
└── main.go
├── dev.Dockerfile
├── docs
└── assets
│ └── img
│ ├── mmar-demo.gif
│ └── mmar-gopher-logo.png
├── go.mod
├── install.sh
├── internal
├── client
│ └── main.go
├── logger
│ └── main.go
├── protocol
│ └── main.go
├── server
│ ├── main.go
│ └── utils.go
└── utils
│ └── main.go
└── simulations
├── devserver
└── main.go
├── dnsserver
└── main.go
├── simulation_test.go
└── simulation_utils.go
/.github/workflows/goreleaser_release.yml:
--------------------------------------------------------------------------------
1 |
2 | name: Release mmar
3 |
4 | on:
5 | push:
6 | tags:
7 | - '*'
8 |
9 | permissions:
10 | contents: write
11 | packages: write
12 |
13 | jobs:
14 | goreleaser:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout
18 | uses: actions/checkout@v4
19 | with:
20 | fetch-depth: 0
21 |
22 | - name: Set up Go
23 | uses: actions/setup-go@v5
24 |
25 | - name: Login to GitHub Container Registry
26 | uses: docker/login-action@v3
27 | with:
28 | registry: ghcr.io
29 | username: ${{ github.actor }}
30 | password: ${{ secrets.GITHUB_TOKEN }}
31 |
32 | - name: Run GoReleaser
33 | uses: goreleaser/goreleaser-action@v6.1.0
34 | with:
35 | distribution: goreleaser
36 | version: '~> v2'
37 | args: release --clean
38 | env:
39 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
40 | TAP_GITHUB_TOKEN: ${{ secrets.TAP_GITHUB_TOKEN }}
41 |
--------------------------------------------------------------------------------
/.github/workflows/run_simulation_tests.yml:
--------------------------------------------------------------------------------
1 |
2 | name: Run Simulation Tests
3 |
4 | on:
5 | workflow_dispatch:
6 | pull_request:
7 | branches: [ "master" ]
8 |
9 | jobs:
10 |
11 | build:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v4
15 |
16 | - name: Set up Go
17 | uses: actions/setup-go@v4
18 | with:
19 | go-version: '1.23'
20 |
21 | - name: Build
22 | run: go build -o ./simulations/mmar ./cmd/mmar/main.go
23 |
24 | - name: Test
25 | run: go test -v ./...
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # If you prefer the allow list template instead of the deny list, see community template:
2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
3 | #
4 | # Binaries for programs and plugins
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, built with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
17 | # Dependency directories (remove the comment below to include it)
18 | # vendor/
19 |
20 | # Go workspace file
21 | go.work
22 | go.work.sum
23 |
24 | # env file
25 | .env
26 |
27 | # MacOS DS_Store file
28 | *.DS_Store
29 | # Added by goreleaser init:
30 | dist/
31 |
--------------------------------------------------------------------------------
/.goreleaser.yaml:
--------------------------------------------------------------------------------
1 | version: 2
2 |
3 | project_name: mmar
4 |
5 | builds:
6 | - main: ./cmd/mmar
7 | binary: mmar
8 | env:
9 | - CGO_ENABLED=0
10 | goos:
11 | - linux
12 | - windows
13 | - darwin
14 | goarch:
15 | - amd64
16 | - arm64
17 | - 386 # Add support for Windows 32-bit (x86)
18 |
19 | archives:
20 | - formats: [ 'tar.gz' ]
21 | # this name template makes the OS and Arch compatible with the results of `uname`.
22 | name_template: >-
23 | {{ .ProjectName }}_
24 | {{- title .Os }}_
25 | {{- if eq .Arch "amd64" }}x86_64
26 | {{- else if eq .Arch "386" }}i386
27 | {{- else }}{{ .Arch }}{{ end }}
28 | {{- if .Arm }}v{{ .Arm }}{{ end }}
29 | # use zip for windows archives
30 | format_overrides:
31 | - goos: windows
32 | formats: [ 'zip' ]
33 |
34 | changelog:
35 | sort: asc
36 | filters:
37 | exclude:
38 | - "^docs:"
39 | - "^test:"
40 | - "^chore:"
41 |
42 | release:
43 | github:
44 | owner: yusuf-musleh
45 | name: mmar
46 | footer: >-
47 |
48 | ---
49 |
50 | Released by [GoReleaser](https://github.com/goreleaser/goreleaser).
51 |
52 | dockers:
53 | - image_templates:
54 | - "ghcr.io/yusuf-musleh/mmar:{{ .Tag }}-amd64"
55 | use: buildx
56 | dockerfile: Dockerfile
57 | build_flag_templates:
58 | - "--platform=linux/amd64"
59 | - image_templates:
60 | - "ghcr.io/yusuf-musleh/mmar:{{ .Tag }}-arm64"
61 | use: buildx
62 | goarch: arm64
63 | dockerfile: Dockerfile
64 | build_flag_templates:
65 | - "--platform=linux/arm64/v8"
66 |
67 | docker_manifests:
68 | - name_template: "ghcr.io/yusuf-musleh/mmar:{{ .Tag }}"
69 | image_templates:
70 | - "ghcr.io/yusuf-musleh/mmar:{{ .Tag }}-amd64"
71 | - "ghcr.io/yusuf-musleh/mmar:{{ .Tag }}-arm64"
72 |
73 | brews:
74 | - repository:
75 | owner: yusuf-musleh
76 | name: homebrew-mmar-tap
77 | token: "{{ .Env.TAP_GITHUB_TOKEN }}"
78 | directory: Formula
79 | homepage: "https://mmar.dev"
80 | description: mmar is a zero-dependancy, self-hostable, cross-platform HTTP tunnel that exposes your localhost to the world on a public URL.
81 | license: AGPLv3
82 | test: |
83 | system "#{bin}/mmar version"
84 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM scratch
2 |
3 | ENTRYPOINT ["/mmar"]
4 |
5 | COPY mmar /
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | # mmar
8 |
9 | mmar (pronounced "ma-mar") is a zero-dependency, self-hostable, cross-platform HTTP tunnel that exposes your localhost to the world on a public URL.
10 |
11 | It allows you to quickly share what you are working on locally with others without the hassle of a full deployment, especially if it is not ready to be shipped.
12 |
13 | ### Demo
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | ### Key Features
22 |
23 | - Super simple to use
24 | - Provides "mmar.dev" to tunnel for free on a generated subdomain
25 | - Expose multiple ports on different subdomains
26 | - Live logs of requests coming into your localhost server
27 | - Zero dependencies
28 | - Self-host your own mmar server to have full control
29 |
30 | ### Limitations
31 |
32 | - Currently only supports the HTTP protocol, other protocols such as websockets were not tested and will likely not work
33 | - Requests through mmar are limited to 10mb in size, however this could be made configurable in the future
34 | - There is a limit of 5 mmar tunnels per IP to avoid abuse, this could also be made configurable in the future
35 |
36 | ### Learn More
37 |
38 | The development, implementation and technical details of mmar has all been documented in a [devlog series](https://ymusleh.com/tags/mmar.html). You can read more about it there.
39 |
40 | _p.s. mmar means “corridor” or “pass-through” in Arabic._
41 |
42 | ## Installation
43 |
44 | ### Linux/MacOS
45 |
46 | Install mmar
47 |
48 | ```sh
49 | sudo curl -sSL https://raw.githubusercontent.com/yusuf-musleh/mmar/refs/heads/master/install.sh | sh
50 | ```
51 |
52 | ### MacOS (Homebrew)
53 |
54 | Use [Homebrew](https://brew.sh/) to install `mmar` on MacOS:
55 |
56 | ```
57 | brew install yusuf-musleh/mmar-tap/mmar
58 | ```
59 |
60 | If you already have it installed and want to update it to the latest release:
61 |
62 | ```
63 | brew upgrade yusuf-musleh/mmar-tap/mmar
64 | ```
65 |
66 | ### Docker
67 |
68 | The fastest way to create a tunnel what is running on your `localhost:8080` using [Docker](https://www.docker.com/) is by running this command:
69 |
70 | ```
71 | docker run --rm --network host ghcr.io/yusuf-musleh/mmar:v0.2.6 client --local-port 8080
72 | ```
73 |
74 | ### Windows
75 |
76 | See Docker or Manual installation instructions
77 |
78 | ### Manually
79 |
80 | Download a [Release](https://github.com/yusuf-musleh/mmar/releases/) from Github that is compatible with your OS, extract/locate the `mmar` binary and add it somewhere in your PATH.
81 |
82 | ## Quick Start
83 |
84 | 1. Check that you have `mmar` installed
85 |
86 | ```
87 | $ mmar version
88 | mmar version 0.2.1
89 | ```
90 | 1. Make sure you have your localhost server running on some port (eg: 8080)
91 | 1. Run the `mmar` client, pointing it to your localhost port
92 | ```
93 | $ mmar client --local-port 8080
94 |
95 | 2025/02/02 16:26:54 Starting mmar client...
96 | Creating tunnel:
97 | Tunnel Host: mmar.dev
98 | Local Port: 8080
99 |
100 | 2025/02/02 16:26:54 Tunnel created successfully!
101 |
102 | A mmar tunnel is now open on:
103 |
104 | >>> https://7v0aye.mmar.dev -> http://localhost:8080
105 | ```
106 | 1. That's it! Now you have an HTTP tunnel open through `mmar.dev` on a randomly generated unique subdomain
107 | 1. Access this link from anywhere and you should be able to access your localhost server
108 | 1. You can see all the options `mmar` by running the help command:
109 | ```
110 | $ mmar --help
111 | mmar is an HTTP tunnel that exposes your localhost to the world on a public URL.
112 |
113 | Usage:
114 | mmar [command flags]
115 |
116 | Commands:
117 | server
118 | Runs a mmar server. Run this on your publicly reachable server if you're self-hosting mmar.
119 | client
120 | Runs a mmar client. Run this on your machine to expose your localhost on a public URL.
121 | version
122 | Prints the installed version of mmar.
123 |
124 |
125 | Run `mmar -h` to get help for a specific command
126 | ```
127 |
128 | ### Configuring through Environment Variables
129 |
130 | You can define the various mmar command flags in environment variables rather than passing them in with the command. Here are the available environment variables along with the corresponding flags:
131 |
132 | ```
133 | MMAR__SERVER_HTTP_PORT -> mmar server --http-port
134 | MMAR__SERVER_TCP_PORT -> mmar server --tcp-port
135 | MMAR__LOCAL_PORT -> mmar client --local-port
136 | MMAR__TUNNEL_HTTP_PORT -> mmar client --tunnel-http-port
137 | MMAR__TUNNEL_TCP_PORT -> mmar client --tunnel-tcp-port
138 | MMAR__TUNNEL_HOST -> mmar client --tunnel-host
139 | ```
140 |
141 | ## Self-Host
142 |
143 | Since everything is open-source, you can easily self-host mmar on your own infrastructure under your own domain.
144 |
145 | To deploy mmar on your own VPS using docker, you can do the following:
146 |
147 | 1. Make sure you have your VPS already provisioned and have ssh access to it.
148 | 1. Make sure you already own a domain and have the apex domain as well as wildcard subdomains pointing towards your VPS's public IP. It should look something like this:
149 |
150 |
151 | | Type | Host | Value | TTL |
152 | | -------- | ------- | --------------- | ------ |
153 | | A Record | * | 123.123.123.123 | Auto |
154 | | A Record | @ | 123.123.123.123 | Auto |
155 |
156 | This would direct all your tunnel subdomains to your VPS for mmar to handle.
157 |
158 | 1. Next, make sure you have docker installed on your VPS, and create a `compose.yaml` file and add the mmar server as a service:
159 |
160 | ```yaml
161 | services:
162 | mmar-server:
163 | image: "ghcr.io/yusuf-musleh/mmar:v0.2.3" # <----- make sure to use the mmar's latest version
164 | restart: unless-stopped
165 | command: server
166 | environment:
167 | - USERNAME_HASH=[YOUR_SHA256_USERNAME_HASH]
168 | - PASSWORD_HASH=[YOUR_SHA256_PASSWORD_HASH]
169 | ports:
170 | - "3376:3376"
171 | - "6673:6673"
172 | ```
173 |
174 | The `USERNAME_HASH` and `PASSWORD_HASH` env variables are the hashes of the credentials needed to access the stats page, which can be viewed at `stats.yourdomain.com`. The stats pages returns a json with very basic information about the number of clients connected (i.e. tunnels open) along with a list of the subdomains and when they were created:
175 |
176 | ```json
177 | {
178 | "connectedClients": [
179 | {
180 | "createdOn": "2025-03-01T08:01:46Z",
181 | "id": "owrwf0"
182 | }
183 | ],
184 | "connectedClientsCount": 1
185 | }
186 | ```
187 |
188 | 1. Next, we need to also add a reverse proxy, such as [Nginx](https://nginx.org/) or [Caddy](https://caddyserver.com/), so that requests and TCP connections to your domain are routed accordingly. Since the mmar client communicates with the server using TCP, you need to make sure that the reverse proxy supports routing on TCP, and not just HTTP.
189 |
190 | I highly recommend [Caddy](https://caddyserver.com/) as it also handles obtaining SSL certificates for your wildcard subdomains automatically for you, in addition to having a Layer4 reverse proxy to route TCP connections. To get this functionality we need to include a few additional Caddy modules, the [layer4 module](github.com/mholt/caddy-l4) as well as the [caddy-dns](https://github.com/caddy-dns) module that matches your domain registrar, in my case I am using the [namecheap module](https://github.com/caddy-dns/namecheap) in order to automatically issue SSL certificates for wildcard subdomains.
191 |
192 | To add those modules you can build a new docker image for Caddy including these modules:
193 |
194 | ```
195 | FROM caddy:2.9.1-builder AS builder
196 |
197 | RUN xcaddy build \
198 | --with github.com/mholt/caddy-l4 \
199 | --with github.com/caddy-dns/namecheap
200 |
201 | FROM caddy:2.9.1
202 |
203 | COPY --from=builder /usr/bin/caddy /usr/bin/caddy
204 | ```
205 |
206 | Next we need to configure Caddy for our setup, let's define a `Caddyfile`:
207 |
208 | ```
209 | # Layer4 reverse proxy TCP connection to TCP port
210 | {
211 | layer4 {
212 | example.com:6673 {
213 | route {
214 | tls
215 | proxy {
216 | upstream mmar-server:6673
217 | }
218 | }
219 | }
220 | }
221 | }
222 |
223 | # Redirect to repo page on Github
224 | example.com {
225 | redir https://github.com/yusuf-musleh/mmar
226 | }
227 |
228 | # Reverse proxy HTTP requests to HTTP port
229 | *.example.com {
230 | reverse_proxy mmar-server:3376
231 | tls {
232 | resolvers 1.1.1.1
233 | dns namecheap {
234 | api_key API_KEY_HERE
235 | user USERNAME_HERE
236 | api_endpoint https://api.namecheap.com/xml.response
237 | client_ip IP_HERE
238 | }
239 | }
240 | }
241 | ```
242 |
243 | Now that we have the new Caddy image and we defined out Caddyfile, we just need to update out `compose.yaml` file to start Caddy:
244 |
245 | ```yaml
246 | services:
247 | caddy:
248 | image: custom-caddy:2.9.1
249 | restart: unless-stopped
250 | ports:
251 | - "80:80"
252 | - "443:443"
253 | - "443:443/udp"
254 | volumes:
255 | - ./Caddyfile:/etc/caddy/Caddyfile
256 | - caddy_data:/data
257 | - caddy_config:/config
258 | mmar-server:
259 | image: "ghcr.io/yusuf-musleh/mmar:v0.2.3" # <----- make sure to use the mmar's latest version
260 | restart: unless-stopped
261 | command: server
262 | environment:
263 | - USERNAME_HASH=[YOUR_SHA256_USERNAME_HASH]
264 | - PASSWORD_HASH=[YOUR_SHA256_PASSWORD_HASH]
265 | ports:
266 | - "3376:3376"
267 | - "6673:6673"
268 |
269 | volumes:
270 | caddy_data:
271 | caddy_config:
272 |
273 | ```
274 |
275 | That's it! All you need to do is run `docker compose up -d` and then check the logs to make sure everything is running as expected, `docker compose logs --follow`.
276 |
277 | 1. To create a tunnel using your self-hosted mmar tunnel run the following command on your local machine:
278 |
279 | ```
280 | $ mmar client --tunnel-host example.com --local-port 8080
281 | ```
282 |
283 | That should open a mmar tunnel through your self-hosted mmar server pointing towards your `localhost:8080`.
284 |
285 |
286 | ## License
287 |
288 | [AGPL-3.0](https://github.com/yusuf-musleh/mmar#AGPL-3.0-1-ov-file)
289 |
290 | ## Attributions
291 |
292 | Attributions for the mmar gopher logo:
293 |
294 | - [gopherize.me](https://gopherize.me/)
295 | - Icons Vectors by Vecteezy
296 |
--------------------------------------------------------------------------------
/cmd/mmar/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "os"
7 |
8 | "github.com/yusuf-musleh/mmar/constants"
9 | "github.com/yusuf-musleh/mmar/internal/client"
10 | "github.com/yusuf-musleh/mmar/internal/server"
11 | "github.com/yusuf-musleh/mmar/internal/utils"
12 | )
13 |
14 | func main() {
15 | serverCmd := flag.NewFlagSet(constants.SERVER_CMD, flag.ExitOnError)
16 | serverHttpPort := serverCmd.String(
17 | "http-port",
18 | utils.EnvVarOrDefault(constants.MMAR_ENV_VAR_SERVER_HTTP_PORT, constants.SERVER_HTTP_PORT),
19 | constants.SERVER_HTTP_PORT_HELP,
20 | )
21 | serverTcpPort := serverCmd.String(
22 | "tcp-port",
23 | utils.EnvVarOrDefault(constants.MMAR_ENV_VAR_SERVER_TCP_PORT, constants.SERVER_TCP_PORT),
24 | constants.SERVER_TCP_PORT_HELP,
25 | )
26 |
27 | clientCmd := flag.NewFlagSet(constants.CLIENT_CMD, flag.ExitOnError)
28 | clientLocalPort := clientCmd.String(
29 | "local-port",
30 | utils.EnvVarOrDefault(constants.MMAR_ENV_VAR_LOCAL_PORT, constants.CLIENT_LOCAL_PORT),
31 | constants.CLIENT_LOCAL_PORT_HELP,
32 | )
33 | clientTunnelHttpPort := clientCmd.String(
34 | "tunnel-http-port",
35 | utils.EnvVarOrDefault(constants.MMAR_ENV_VAR_TUNNEL_HTTP_PORT, constants.TUNNEL_HTTP_PORT),
36 | constants.CLIENT_HTTP_PORT_HELP,
37 | )
38 | clientTunnelTcpPort := clientCmd.String(
39 | "tunnel-tcp-port",
40 | utils.EnvVarOrDefault(constants.MMAR_ENV_VAR_TUNNEL_TCP_PORT, constants.SERVER_TCP_PORT),
41 | constants.CLIENT_TCP_PORT_HELP,
42 | )
43 | clientTunnelHost := clientCmd.String(
44 | "tunnel-host",
45 | utils.EnvVarOrDefault(constants.MMAR_ENV_VAR_TUNNEL_HOST, constants.TUNNEL_HOST),
46 | constants.TUNNEL_HOST_HELP,
47 | )
48 |
49 | versionCmd := flag.NewFlagSet(constants.VERSION_CMD, flag.ExitOnError)
50 | versionCmd.Usage = utils.MmarVersionUsage
51 |
52 | flag.Usage = utils.MmarUsage
53 |
54 | if len(os.Args) < 2 {
55 | utils.MmarUsage()
56 | os.Exit(0)
57 | }
58 |
59 | switch os.Args[1] {
60 | case constants.SERVER_CMD:
61 | serverCmd.Parse(os.Args[2:])
62 | mmarServerConfig := server.ConfigOptions{
63 | HttpPort: *serverHttpPort,
64 | TcpPort: *serverTcpPort,
65 | }
66 | server.Run(mmarServerConfig)
67 | case constants.CLIENT_CMD:
68 | clientCmd.Parse(os.Args[2:])
69 | mmarClientConfig := client.ConfigOptions{
70 | LocalPort: *clientLocalPort,
71 | TunnelHttpPort: *clientTunnelHttpPort,
72 | TunnelTcpPort: *clientTunnelTcpPort,
73 | TunnelHost: *clientTunnelHost,
74 | }
75 | client.Run(mmarClientConfig)
76 | case constants.VERSION_CMD:
77 | versionCmd.Parse(os.Args[2:])
78 | fmt.Println("mmar version", constants.MMAR_VERSION)
79 | default:
80 | utils.MmarUsage()
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/constants/main.go:
--------------------------------------------------------------------------------
1 | package constants
2 |
3 | const (
4 | MMAR_VERSION = "0.2.6"
5 |
6 | VERSION_CMD = "version"
7 | SERVER_CMD = "server"
8 | CLIENT_CMD = "client"
9 | CLIENT_LOCAL_PORT = "8000"
10 | SERVER_HTTP_PORT = "3376"
11 | SERVER_TCP_PORT = "6673"
12 | TUNNEL_HOST = "mmar.dev"
13 | TUNNEL_HTTP_PORT = "443"
14 |
15 | MMAR_ENV_VAR_SERVER_HTTP_PORT = "MMAR__SERVER_HTTP_PORT"
16 | MMAR_ENV_VAR_SERVER_TCP_PORT = "MMAR__SERVER_TCP_PORT"
17 | MMAR_ENV_VAR_LOCAL_PORT = "MMAR__LOCAL_PORT"
18 | MMAR_ENV_VAR_TUNNEL_HTTP_PORT = "MMAR__TUNNEL_HTTP_PORT"
19 | MMAR_ENV_VAR_TUNNEL_TCP_PORT = "MMAR__TUNNEL_TCP_PORT"
20 | MMAR_ENV_VAR_TUNNEL_HOST = "MMAR__TUNNEL_HOST"
21 |
22 | SERVER_STATS_DEFAULT_USERNAME = "admin"
23 | SERVER_STATS_DEFAULT_PASSWORD = "admin"
24 |
25 | SERVER_HTTP_PORT_HELP = "Define port where mmar will bind to and run on server for HTTP requests."
26 | SERVER_TCP_PORT_HELP = "Define port where mmar will bind to and run on server for TCP connections."
27 |
28 | CLIENT_LOCAL_PORT_HELP = "Define the port where your local dev server is running to expose through mmar."
29 | CLIENT_HTTP_PORT_HELP = "Define port of mmar HTTP server to make requests through the tunnel."
30 | CLIENT_TCP_PORT_HELP = "Define port of mmar TCP server for client to connect to, creating a tunnel."
31 | TUNNEL_HOST_HELP = "Define host domain of mmar server for client to connect to."
32 |
33 | TUNNEL_MESSAGE_PROTOCOL_VERSION = 3
34 | TUNNEL_MESSAGE_DATA_DELIMITER = '\n'
35 | ID_CHARSET = "abcdefghijklmnopqrstuvwxyz0123456789"
36 | ID_LENGTH = 6
37 |
38 | MAX_TUNNELS_PER_IP = 5
39 | TUNNEL_RECONNECT_TIMEOUT = 3
40 | GRACEFUL_SHUTDOWN_TIMEOUT = 3
41 | TUNNEL_CREATE_TIMEOUT = 3
42 | REQ_BODY_READ_CHUNK_TIMEOUT = 3
43 | DEST_REQUEST_TIMEOUT = 30
44 | HEARTBEAT_FROM_SERVER_TIMEOUT = 5
45 | HEARTBEAT_FROM_CLIENT_TIMEOUT = 2
46 | READ_DEADLINE = 3
47 | MAX_REQ_BODY_SIZE = 10000000 // 10mb
48 |
49 | CLIENT_DISCONNECT_ERR_TEXT = "Tunnel is closed, cannot connect to mmar client."
50 | LOCALHOST_NOT_RUNNING_ERR_TEXT = "Tunneled successfully, but nothing is running on localhost."
51 | DEST_REQUEST_TIMEDOUT_ERR_TEXT = "Destination server took too long to respond"
52 | READ_BODY_CHUNK_ERR_TEXT = "Error reading request body"
53 | READ_BODY_CHUNK_TIMEOUT_ERR_TEXT = "Timeout reading request body"
54 | READ_RESP_BODY_ERR_TEXT = "Could not read response from destination server, check your server's logs for any errors."
55 | MAX_REQ_BODY_SIZE_ERR_TEXT = "Request too large"
56 | FAILED_TO_FORWARD_TO_MMAR_CLIENT_ERR_TEXT = "Failed to forward request to mmar client"
57 | FAILED_TO_READ_RESP_FROM_MMAR_CLIENT_ERR_TEXT = "Fail to read response from mmad client"
58 |
59 | // TERMINAL ANSI ESCAPED COLORS
60 | DEFAULT_COLOR = ""
61 | RED = "\033[31m"
62 | GREEN = "\033[32m"
63 | YELLOW = "\033[33m"
64 | BLUE = "\033[34m"
65 | RESET = "\033[0m"
66 | )
67 |
68 | var (
69 | MMAR_SUBCOMMANDS = [][]string{
70 | {"server", "Runs a mmar server. Run this on your publicly reachable server if you're self-hosting mmar."},
71 | {"client", "Runs a mmar client. Run this on your machine to expose your localhost on a public URL."},
72 | {"version", "Prints the installed version of mmar."},
73 | }
74 | )
75 |
--------------------------------------------------------------------------------
/dev.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:1.23
2 |
3 | # Install gopls for golang LSP
4 | RUN go install golang.org/x/tools/gopls@latest
5 |
6 | # Install delve for debugging
7 | RUN go install github.com/go-delve/delve/cmd/dlv@latest
8 |
9 | WORKDIR /app
10 |
--------------------------------------------------------------------------------
/docs/assets/img/mmar-demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yusuf-musleh/mmar/26b9439dc5c75e90f25893eb228e9d5d78ca2e52/docs/assets/img/mmar-demo.gif
--------------------------------------------------------------------------------
/docs/assets/img/mmar-gopher-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yusuf-musleh/mmar/26b9439dc5c75e90f25893eb228e9d5d78ca2e52/docs/assets/img/mmar-gopher-logo.png
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/yusuf-musleh/mmar
2 |
3 | go 1.23.0
4 |
--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | set -e
4 |
5 | REPO="yusuf-musleh/mmar"
6 | BINARY="mmar"
7 |
8 | echo "Installing $BINARY..."
9 |
10 | # Detect OS
11 | OS="$(uname -s)"
12 | case "$OS" in
13 | Linux) OS_TITLE="Linux";;
14 | Darwin) OS_TITLE="Darwin";;
15 | *) echo "Unsupported OS: $OS"; exit 1;;
16 | esac
17 |
18 | # Detect ARCH
19 | ARCH="$(uname -m)"
20 | case "$ARCH" in
21 | x86_64) ARCH_ID="x86_64";;
22 | i386) ARCH_ID="i386";;
23 | aarch64|arm64) ARCH_ID="arm64";;
24 | *) echo "Unsupported architecture: $ARCH"; exit 1;;
25 | esac
26 |
27 | ASSET="${BINARY}_${OS_TITLE}_${ARCH_ID}.tar.gz"
28 | URL="https://github.com/$REPO/releases/latest/download/$ASSET"
29 |
30 | # Temp dir
31 | TMP_DIR=$(mktemp -d)
32 | cd "$TMP_DIR"
33 |
34 | echo "Downloading $ASSET..."
35 | curl -sSL "$URL" -o "$ASSET"
36 |
37 | echo "Extracting..."
38 | tar -xzf "$ASSET"
39 |
40 | # Install location
41 | INSTALL_DIR="/usr/local/bin"
42 |
43 | # Ensure /usr/local/lib exists
44 | if [ ! -d "$INSTALL_DIR" ]; then
45 | sudo mkdir -p "$INSTALL_DIR"
46 | fi
47 |
48 | echo "Installing to $INSTALL_DIR"
49 | sudo install -m 755 "$BINARY" "$INSTALL_DIR/$BINARY"
50 |
51 | echo "$BINARY installed successfully to $INSTALL_DIR/$BINARY"
52 | "$BINARY" version || true
53 |
--------------------------------------------------------------------------------
/internal/client/main.go:
--------------------------------------------------------------------------------
1 | package client
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "context"
7 | "errors"
8 | "fmt"
9 | "io"
10 | "log"
11 | "net"
12 | "net/http"
13 | "net/url"
14 | "os"
15 | "os/signal"
16 | "syscall"
17 | "time"
18 |
19 | "github.com/yusuf-musleh/mmar/constants"
20 | "github.com/yusuf-musleh/mmar/internal/logger"
21 | "github.com/yusuf-musleh/mmar/internal/protocol"
22 | )
23 |
24 | type ConfigOptions struct {
25 | LocalPort string
26 | TunnelHttpPort string
27 | TunnelTcpPort string
28 | TunnelHost string
29 | }
30 |
31 | type MmarClient struct {
32 | // Tunnel to Server
33 | protocol.Tunnel
34 | ConfigOptions
35 | subdomain string
36 | }
37 |
38 | func (mc *MmarClient) localizeRequest(request *http.Request) {
39 | localhost := fmt.Sprintf("http://localhost:%v%v", mc.LocalPort, request.RequestURI)
40 | localURL, urlErr := url.Parse(localhost)
41 | if urlErr != nil {
42 | log.Fatalf("Failed to parse URL: %v", urlErr)
43 | }
44 |
45 | // Set URL to send request to local server
46 | request.URL = localURL
47 | // Clear requestURI since it is now a client request
48 | request.RequestURI = ""
49 | }
50 |
51 | // Process requests coming from mmar server and forward them to localhost
52 | func (mc *MmarClient) handleRequestMessage(tunnelMsg protocol.TunnelMessage) {
53 | fwdClient := &http.Client{
54 | Timeout: constants.DEST_REQUEST_TIMEOUT * time.Second,
55 | // Do not follow redirects, let the end-user's client handle it
56 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
57 | return http.ErrUseLastResponse
58 | },
59 | }
60 |
61 | reqReader := bufio.NewReader(bytes.NewReader(tunnelMsg.MsgData))
62 | req, reqErr := http.ReadRequest(reqReader)
63 |
64 | if reqErr != nil {
65 | if errors.Is(reqErr, io.EOF) {
66 | logger.Log(constants.DEFAULT_COLOR, "Connection to mmar server closed or disconnected. Exiting...")
67 | os.Exit(0)
68 | }
69 |
70 | if errors.Is(reqErr, net.ErrClosed) {
71 | logger.Log(constants.DEFAULT_COLOR, "Connection closed.")
72 | os.Exit(0)
73 | }
74 | log.Fatalf("Failed to read data from TCP conn: %v", reqErr)
75 | }
76 |
77 | // Convert request to target localhost
78 | mc.localizeRequest(req)
79 |
80 | resp, fwdErr := fwdClient.Do(req)
81 | if fwdErr != nil {
82 | if errors.Is(fwdErr, syscall.ECONNREFUSED) || errors.Is(fwdErr, io.ErrUnexpectedEOF) || errors.Is(fwdErr, io.EOF) {
83 | localhostNotRunningMsg := protocol.TunnelMessage{MsgType: protocol.LOCALHOST_NOT_RUNNING}
84 | if err := mc.SendMessage(localhostNotRunningMsg); err != nil {
85 | log.Fatal(err)
86 | }
87 | return
88 | } else if errors.Is(fwdErr, context.DeadlineExceeded) {
89 | destServerTimedoutMsg := protocol.TunnelMessage{MsgType: protocol.DEST_REQUEST_TIMEDOUT}
90 | if err := mc.SendMessage(destServerTimedoutMsg); err != nil {
91 | log.Fatal(err)
92 | }
93 | return
94 | }
95 |
96 | invalidRespFromDestMsg := protocol.TunnelMessage{MsgType: protocol.INVALID_RESP_FROM_DEST}
97 | if err := mc.SendMessage(invalidRespFromDestMsg); err != nil {
98 | log.Fatal(err)
99 | }
100 | return
101 | }
102 |
103 | logger.LogHTTP(req, resp.StatusCode, resp.ContentLength, false, true)
104 |
105 | // Writing response to buffer to tunnel it back
106 | var responseBuff bytes.Buffer
107 | resp.Write(&responseBuff)
108 |
109 | respMessage := protocol.TunnelMessage{MsgType: protocol.RESPONSE, MsgData: responseBuff.Bytes()}
110 | if err := mc.SendMessage(respMessage); err != nil {
111 | log.Fatal(err)
112 | }
113 | }
114 |
115 | // Keep attempting to reconnect the existing tunnel until successful
116 | func (mc *MmarClient) reconnectTunnel(ctx context.Context) {
117 | for {
118 | // If context is cancelled, do not reconnect
119 | if errors.Is(ctx.Err(), context.Canceled) {
120 | return
121 | }
122 | logger.Log(constants.DEFAULT_COLOR, "Attempting to reconnect...")
123 | conn, err := net.DialTimeout(
124 | "tcp",
125 | net.JoinHostPort(mc.ConfigOptions.TunnelHost, mc.ConfigOptions.TunnelTcpPort),
126 | constants.TUNNEL_CREATE_TIMEOUT*time.Second,
127 | )
128 | if err != nil {
129 | time.Sleep(constants.TUNNEL_RECONNECT_TIMEOUT * time.Second)
130 | continue
131 | }
132 | mc.Tunnel.Conn = conn
133 | break
134 | }
135 | }
136 |
137 | func (mc *MmarClient) ProcessTunnelMessages(ctx context.Context) {
138 | for {
139 | select {
140 | case <-ctx.Done(): // Client gracefully shutdown
141 | return
142 | default:
143 | // Send heartbeat if nothing has been read for a while
144 | receiveMessageTimeout := time.AfterFunc(
145 | constants.HEARTBEAT_FROM_CLIENT_TIMEOUT*time.Second,
146 | func() {
147 | heartbeatMsg := protocol.TunnelMessage{MsgType: protocol.HEARTBEAT_FROM_CLIENT}
148 | if err := mc.SendMessage(heartbeatMsg); err != nil {
149 | logger.Log(constants.DEFAULT_COLOR, "Failed to send heartbeat. Exiting...")
150 | os.Exit(0)
151 | }
152 | // Set a read timeout, if no response to heartbeat is recieved within that period,
153 | // attempt to reconnect to the server
154 | readDeadline := time.Now().Add((constants.READ_DEADLINE * time.Second))
155 | mc.Tunnel.Conn.SetReadDeadline(readDeadline)
156 | },
157 | )
158 |
159 | tunnelMsg, err := mc.ReceiveMessage()
160 | // If a message is received, stop the receiveMessageTimeout and remove the ReadTimeout
161 | // as we do not need to send heartbeat or check connection health in this iteration
162 | receiveMessageTimeout.Stop()
163 | mc.Tunnel.Conn.SetReadDeadline(time.Time{})
164 |
165 | if err != nil {
166 | // If the context was cancelled just return
167 | if errors.Is(ctx.Err(), context.Canceled) {
168 | return
169 | } else if errors.Is(err, protocol.INVALID_MESSAGE_PROTOCOL_VERSION) {
170 | logger.Log(constants.YELLOW, "The mmar message protocol has been updated, please update mmar.")
171 | os.Exit(0)
172 | }
173 |
174 | logger.Log(constants.DEFAULT_COLOR, "Tunnel connection disconnected.")
175 |
176 | // Keep trying to reconnect
177 | mc.reconnectTunnel(ctx)
178 |
179 | continue
180 | }
181 |
182 | switch tunnelMsg.MsgType {
183 | case protocol.CLIENT_CONNECT:
184 | tunnelSubdomain := string(tunnelMsg.MsgData)
185 | // If there is an existing subdomain, that means we are reconnecting with an
186 | // existing mmar client, try to reclaim the same subdomain
187 | if mc.subdomain != "" {
188 | reconnectMsg := protocol.TunnelMessage{MsgType: protocol.CLIENT_RECLAIM_SUBDOMAIN, MsgData: []byte(tunnelSubdomain + ":" + mc.subdomain)}
189 | mc.subdomain = ""
190 | if err := mc.SendMessage(reconnectMsg); err != nil {
191 | logger.Log(constants.DEFAULT_COLOR, "Tunnel failed to reconnect. Exiting...")
192 | os.Exit(0)
193 | }
194 | continue
195 | } else {
196 | mc.subdomain = tunnelSubdomain
197 | }
198 | logger.LogTunnelCreated(tunnelSubdomain, mc.TunnelHost, mc.TunnelHttpPort, mc.LocalPort)
199 | case protocol.CLIENT_TUNNEL_LIMIT:
200 | limit := logger.ColorLogStr(
201 | constants.RED,
202 | fmt.Sprintf("(%v/%v)", constants.MAX_TUNNELS_PER_IP, constants.MAX_TUNNELS_PER_IP),
203 | )
204 | logger.Log(
205 | constants.DEFAULT_COLOR,
206 | fmt.Sprintf(
207 | "Maximum limit of Tunnels created reached %v. Please shutdown existing tunnels to create new ones.",
208 | limit,
209 | ))
210 | os.Exit(0)
211 | case protocol.REQUEST:
212 | go mc.handleRequestMessage(tunnelMsg)
213 | case protocol.HEARTBEAT_ACK:
214 | // Got a heartbeat ack, that means the connection is healthy,
215 | // we do not need to perform any action
216 | case protocol.HEARTBEAT_FROM_SERVER:
217 | heartbeatAckMsg := protocol.TunnelMessage{MsgType: protocol.HEARTBEAT_ACK}
218 | if err := mc.SendMessage(heartbeatAckMsg); err != nil {
219 | logger.Log(constants.DEFAULT_COLOR, "Failed to send Heartbeat Ack. Exiting...")
220 | os.Exit(0)
221 | }
222 | }
223 | }
224 | }
225 | }
226 |
227 | func Run(config ConfigOptions) {
228 | logger.LogStartMmarClient(config.TunnelHost, config.TunnelTcpPort, config.TunnelHttpPort, config.LocalPort)
229 |
230 | // Channel handler for interrupt signal
231 | sigInt := make(chan os.Signal, 1)
232 | signal.Notify(sigInt, os.Interrupt)
233 |
234 | conn, err := net.DialTimeout(
235 | "tcp",
236 | net.JoinHostPort(config.TunnelHost, config.TunnelTcpPort),
237 | constants.TUNNEL_CREATE_TIMEOUT*time.Second,
238 | )
239 | if err != nil {
240 | logger.Log(
241 | constants.DEFAULT_COLOR,
242 | fmt.Sprintf(
243 | "Could not reach mmar server on %s:%s\n %v \nExiting...",
244 | logger.ColorLogStr(constants.RED, config.TunnelHost),
245 | logger.ColorLogStr(constants.RED, config.TunnelTcpPort),
246 | err,
247 | ),
248 | )
249 | os.Exit(0)
250 | }
251 | defer conn.Close()
252 | mmarClient := MmarClient{
253 | protocol.Tunnel{Conn: conn},
254 | config,
255 | "",
256 | }
257 |
258 | // Create context to cancel running gouroutines when shutting down
259 | ctx, cancel := context.WithCancel(context.Background())
260 |
261 | // Process Tunnel Messages coming from mmar server
262 | go mmarClient.ProcessTunnelMessages(ctx)
263 |
264 | // Wait for an interrupt signal, if received, terminate gracefully
265 | <-sigInt
266 |
267 | logger.Log(constants.YELLOW, "Gracefully shutting down client...")
268 | disconnectMsg := protocol.TunnelMessage{MsgType: protocol.CLIENT_DISCONNECT}
269 | mmarClient.SendMessage(disconnectMsg)
270 | cancel()
271 | gracefulShutdownTimer := time.NewTimer(constants.GRACEFUL_SHUTDOWN_TIMEOUT * time.Second)
272 | <-gracefulShutdownTimer.C
273 | }
274 |
--------------------------------------------------------------------------------
/internal/logger/main.go:
--------------------------------------------------------------------------------
1 | package logger
2 |
3 | import (
4 | "fmt"
5 | "html"
6 | "log"
7 | "net/http"
8 | "strconv"
9 |
10 | "github.com/yusuf-musleh/mmar/constants"
11 | "github.com/yusuf-musleh/mmar/internal/utils"
12 | )
13 |
14 | // Wrapping ResponseWriter to capture response status code and content length
15 | type WrappedResponseWriter struct {
16 | http.ResponseWriter
17 | statusCode int
18 | contentLength int64
19 | }
20 |
21 | // Capture the response status code then call the actual ResponseWriter's WriteHeader
22 | func (wrw *WrappedResponseWriter) WriteHeader(statusCode int) {
23 | wrw.statusCode = statusCode
24 | wrw.ResponseWriter.WriteHeader(statusCode)
25 | }
26 |
27 | // Capture the response content length then call the actual ResponseWriter's Write
28 | func (wrw *WrappedResponseWriter) Write(data []byte) (int, error) {
29 | wrw.contentLength = int64(len(data))
30 | return wrw.ResponseWriter.Write(data)
31 | }
32 |
33 | func ColorLogStr(color string, logstr string) string {
34 | return color + logstr + constants.RESET
35 | }
36 |
37 | func Log(color string, logstr string) {
38 | if color == constants.DEFAULT_COLOR {
39 | log.Println(logstr)
40 | return
41 | }
42 | log.Println(ColorLogStr(color, logstr))
43 | }
44 |
45 | // Log HTTP requests including their response's status code and response data length
46 | func LogHTTP(req *http.Request, statusCode int, contentLength int64, includeSubdomain bool, colored bool) {
47 | hasQueryParams := ""
48 | if req.URL.RawQuery != "" {
49 | hasQueryParams = "?"
50 | }
51 |
52 | subdomainInfo := ""
53 | if includeSubdomain {
54 | subdomainInfo = "[" + utils.ExtractSubdomain(req.Host) + "] "
55 | }
56 |
57 | if !colored {
58 | log.Printf(
59 | "%s\"%s %s%s%s %s\" %d %d",
60 | subdomainInfo,
61 | req.Method,
62 | html.EscapeString(req.URL.Path),
63 | hasQueryParams,
64 | req.URL.RawQuery,
65 | req.Proto,
66 | statusCode,
67 | contentLength,
68 | )
69 | return
70 | }
71 |
72 | // Color HTTP status code
73 | var strStatusCode string
74 | switch statusCode / 100 {
75 | case 2:
76 | strStatusCode = ColorLogStr(constants.GREEN, strconv.Itoa(statusCode))
77 | case 3:
78 | strStatusCode = ColorLogStr(constants.YELLOW, strconv.Itoa(statusCode))
79 | case 4:
80 | strStatusCode = ColorLogStr(constants.RED, strconv.Itoa(statusCode))
81 | case 5:
82 | strStatusCode = ColorLogStr(constants.RED, strconv.Itoa(statusCode))
83 | default:
84 | strStatusCode = strconv.Itoa(statusCode)
85 | }
86 |
87 | // Color HTTP method
88 | var coloredMethod string
89 | switch req.Method {
90 | case "GET":
91 | coloredMethod = ColorLogStr(constants.YELLOW, req.Method)
92 | case "POST", "PATCH", "PUT":
93 | coloredMethod = ColorLogStr(constants.BLUE, req.Method)
94 | case "DELETE":
95 | coloredMethod = ColorLogStr(constants.RED, req.Method)
96 | default:
97 | coloredMethod = req.Method
98 | }
99 |
100 | log.Printf(
101 | "%s\"%s %s%s%s %s\" %s %d",
102 | subdomainInfo,
103 | coloredMethod,
104 | html.EscapeString(req.URL.Path),
105 | hasQueryParams,
106 | req.URL.RawQuery,
107 | req.Proto,
108 | strStatusCode,
109 | contentLength,
110 | )
111 |
112 | }
113 |
114 | // Logger middle to log all HTTP requests handled
115 | func LoggerMiddleware(h http.Handler) http.Handler {
116 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
117 | // Initializing WrappedResponseWrapper with default values
118 | wrw := WrappedResponseWriter{ResponseWriter: w, statusCode: http.StatusOK, contentLength: 0}
119 | h.ServeHTTP(&wrw, r)
120 | LogHTTP(r, wrw.statusCode, wrw.contentLength, true, false)
121 | })
122 | }
123 |
124 | func LogStartMmarServer(tcpPort string, httpPort string) {
125 | logStr := `Starting mmar server...
126 | Starting HTTP Server on port: %s
127 | Starting TCP Sever on port: %s
128 |
129 | `
130 | log.Printf(
131 | logStr,
132 | httpPort,
133 | tcpPort,
134 | )
135 |
136 | }
137 |
138 | func LogStartMmarClient(tunnelHost string, tunnelTcpPort string, tunnelHttpPort string, localPort string) {
139 | logStr := `Starting %s...
140 | Creating tunnel:
141 | Tunnel Host: %s%s%s
142 | Local Port: %s
143 |
144 | `
145 |
146 | tunnelTcpPortStr := ""
147 | if tunnelTcpPort != constants.SERVER_TCP_PORT {
148 | tunnelTcpPortStr = fmt.Sprintf("\n Tunnel TCP Port: %s", ColorLogStr(constants.BLUE, tunnelTcpPort))
149 | }
150 |
151 | tunnelHttpPortStr := ""
152 | if tunnelHttpPort != constants.TUNNEL_HTTP_PORT {
153 | tunnelHttpPortStr = fmt.Sprintf("\n Tunnel HTTP Port: %s", ColorLogStr(constants.BLUE, tunnelHttpPort))
154 | }
155 |
156 | log.Printf(
157 | logStr,
158 | ColorLogStr(constants.BLUE, "mmar client"),
159 | ColorLogStr(constants.BLUE, tunnelHost),
160 | tunnelTcpPortStr,
161 | tunnelHttpPortStr,
162 | ColorLogStr(constants.BLUE, localPort),
163 | )
164 | }
165 |
166 | func LogTunnelCreated(subdomain string, tunnelHost string, tunnelHttpPort string, localPort string) {
167 | logStr := `%s
168 |
169 | A mmar tunnel is now open on:
170 |
171 | >>> %s://%s.%s%s %s http://localhost:%s
172 |
173 | `
174 | httpProtocol := "https"
175 | tunnelHttpPortStr := ""
176 | if tunnelHost == "localhost" {
177 | httpProtocol = "http"
178 | if tunnelHttpPort == constants.TUNNEL_HTTP_PORT {
179 | tunnelHttpPort = constants.SERVER_HTTP_PORT
180 | }
181 | }
182 |
183 | if tunnelHttpPort != constants.TUNNEL_HTTP_PORT {
184 | tunnelHttpPortStr = ":" + tunnelHttpPort
185 | }
186 |
187 | log.Printf(
188 | logStr,
189 | ColorLogStr(constants.GREEN, "Tunnel created successfully!"),
190 | httpProtocol,
191 | subdomain,
192 | tunnelHost,
193 | tunnelHttpPortStr,
194 | ColorLogStr(constants.GREEN, "->"),
195 | localPort,
196 | )
197 | }
198 |
--------------------------------------------------------------------------------
/internal/protocol/main.go:
--------------------------------------------------------------------------------
1 | package protocol
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "context"
7 | "errors"
8 | "fmt"
9 | "io"
10 | "net"
11 | "net/http"
12 | "strconv"
13 | "time"
14 |
15 | "github.com/yusuf-musleh/mmar/constants"
16 | "github.com/yusuf-musleh/mmar/internal/logger"
17 | )
18 |
19 | const (
20 | REQUEST = uint8(iota + 1)
21 | RESPONSE
22 | CLIENT_CONNECT
23 | CLIENT_RECLAIM_SUBDOMAIN
24 | CLIENT_DISCONNECT
25 | CLIENT_TUNNEL_LIMIT
26 | LOCALHOST_NOT_RUNNING
27 | DEST_REQUEST_TIMEDOUT
28 | HEARTBEAT_FROM_CLIENT
29 | HEARTBEAT_FROM_SERVER
30 | HEARTBEAT_ACK
31 | INVALID_RESP_FROM_DEST
32 | )
33 |
34 | var INVALID_MESSAGE_PROTOCOL_VERSION = errors.New("Invalid Message Protocol Version")
35 | var INVALID_MESSAGE_TYPE = errors.New("Invalid Tunnel Message Type")
36 |
37 | func isValidTunnelMessageType(mt uint8) (uint8, error) {
38 | // Iterate through all the message type, from first to last, checking
39 | // if the provided message type matches one of them
40 | for msgType := REQUEST; msgType <= INVALID_RESP_FROM_DEST; msgType++ {
41 | if mt == msgType {
42 | return msgType, nil
43 | }
44 | }
45 |
46 | return 0, INVALID_MESSAGE_TYPE
47 | }
48 |
49 | func TunnelErrState(errState uint8) string {
50 | // TODO: Have nicer/more elaborative error messages/pages
51 | errStates := map[uint8]string{
52 | CLIENT_DISCONNECT: constants.CLIENT_DISCONNECT_ERR_TEXT,
53 | LOCALHOST_NOT_RUNNING: constants.LOCALHOST_NOT_RUNNING_ERR_TEXT,
54 | DEST_REQUEST_TIMEDOUT: constants.DEST_REQUEST_TIMEDOUT_ERR_TEXT,
55 | INVALID_RESP_FROM_DEST: constants.READ_RESP_BODY_ERR_TEXT,
56 | }
57 | fallbackErr := "An error occured while attempting to tunnel."
58 |
59 | tunnelErr, ok := errStates[errState]
60 | if !ok {
61 | tunnelErr = fallbackErr
62 | }
63 | return tunnelErr
64 | }
65 |
66 | func RespondTunnelErr(errState uint8, w http.ResponseWriter) {
67 | errBody := TunnelErrState(errState)
68 |
69 | w.Header().Set("Content-Length", strconv.Itoa(len(errBody)))
70 | w.Header().Set("Connection", "close")
71 | w.WriteHeader(http.StatusOK)
72 | w.Write([]byte(errBody))
73 | }
74 |
75 | type Tunnel struct {
76 | Id string
77 | Conn net.Conn
78 | CreatedOn time.Time
79 | }
80 |
81 | type TunnelInterface interface {
82 | ProcessTunnelMessages(ctx context.Context)
83 | }
84 |
85 | type TunnelMessage struct {
86 | MsgType uint8
87 | MsgData []byte
88 | }
89 |
90 | // A TunnelMessage is serialized in the following format:
91 | //
92 | // +---------+------------+---------------------+------------+-------------------------+
93 | // | Version | Msg Type | Length of Msg Data | Delimiter | Message Data |
94 | // | (1 byte)| (1 byte) | (1 or more bytes) | (1 byte) | (Variable Length) |
95 | // +---------+------------+---------------------+------------+-------------------------+
96 | func (tm *TunnelMessage) serializeMessage() ([]byte, error) {
97 | serializedMsg := [][]byte{}
98 |
99 | // Determine and validate message type to add prefix
100 | msgType, err := isValidTunnelMessageType(tm.MsgType)
101 | if err != nil {
102 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Invalid TunnelMessage type: %v:", tm.MsgType))
103 | return []byte{}, err
104 | }
105 |
106 | // Add version of TunnelMessage protocol and TunnelMessage type
107 | serializedMsg = append(
108 | serializedMsg,
109 | []byte{byte(constants.TUNNEL_MESSAGE_PROTOCOL_VERSION), byte(msgType)},
110 | )
111 |
112 | // Add message data bytes length
113 | serializedMsg = append(serializedMsg, []byte(strconv.Itoa(len(tm.MsgData))))
114 |
115 | // Add delimiter to know where the data content starts in the message
116 | serializedMsg = append(serializedMsg, []byte{byte(constants.TUNNEL_MESSAGE_DATA_DELIMITER)})
117 |
118 | // Add the message data
119 | serializedMsg = append(serializedMsg, tm.MsgData)
120 |
121 | // Combine all the data with no separators
122 | return bytes.Join(serializedMsg, nil), nil
123 | }
124 |
125 | func (tm *TunnelMessage) readMessageData(length int, reader *bufio.Reader) ([]byte, error) {
126 | msgData := make([]byte, length)
127 |
128 | if _, err := io.ReadFull(reader, msgData); err != nil {
129 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to read all Msg Data: %v", err))
130 | return []byte{}, err
131 | }
132 |
133 | return msgData, nil
134 | }
135 |
136 | func (tm *TunnelMessage) deserializeMessage(reader *bufio.Reader) error {
137 | msgProtocolVersion, err := reader.ReadByte()
138 | if err != nil {
139 | return err
140 | }
141 |
142 | // Check if the message protocol version is correct
143 | if uint8(msgProtocolVersion) != constants.TUNNEL_MESSAGE_PROTOCOL_VERSION {
144 | return INVALID_MESSAGE_PROTOCOL_VERSION
145 | }
146 |
147 | msgPrefix, err := reader.ReadByte()
148 | if err != nil {
149 | return err
150 | }
151 |
152 | msgType, err := isValidTunnelMessageType(msgPrefix)
153 | if err != nil {
154 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Invalid TunnelMessage prefix: %v", msgPrefix))
155 | return err
156 | }
157 |
158 | msgLengthStr, err := reader.ReadString('\n')
159 | if err != nil {
160 | return err
161 | }
162 |
163 | // Determine the length of the data by stripping out the '\n' and convert to int
164 | msgLength, err := strconv.Atoi(msgLengthStr[:len(msgLengthStr)-1])
165 | if err != nil {
166 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Could not parse message length: %v", msgLengthStr))
167 | return err
168 | }
169 |
170 | msgData, readErr := tm.readMessageData(msgLength, reader)
171 | if readErr != nil {
172 | return readErr
173 | }
174 |
175 | tm.MsgType = msgType
176 | tm.MsgData = msgData
177 |
178 | return nil
179 | }
180 |
181 | func (t *Tunnel) SendMessage(tunnelMsg TunnelMessage) error {
182 | // Serialize tunnel message data
183 | serializedMsg, serializeErr := tunnelMsg.serializeMessage()
184 | if serializeErr != nil {
185 | return serializeErr
186 | }
187 | _, err := t.Conn.Write(serializedMsg)
188 | return err
189 | }
190 |
191 | func (t *Tunnel) ReceiveMessage() (TunnelMessage, error) {
192 | msgReader := bufio.NewReader(t.Conn)
193 |
194 | // Read and deserialize tunnel message data
195 | tunnelMessage := TunnelMessage{}
196 | deserializeErr := tunnelMessage.deserializeMessage(msgReader)
197 |
198 | return tunnelMessage, deserializeErr
199 | }
200 |
--------------------------------------------------------------------------------
/internal/server/main.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "context"
7 | "encoding/json"
8 | "errors"
9 | "fmt"
10 | "html"
11 | "io"
12 | "log"
13 | "math/rand"
14 | "net"
15 | "net/http"
16 | "os"
17 | "os/signal"
18 | "slices"
19 | "strings"
20 | "sync"
21 | "time"
22 |
23 | "github.com/yusuf-musleh/mmar/constants"
24 | "github.com/yusuf-musleh/mmar/internal/logger"
25 | "github.com/yusuf-musleh/mmar/internal/protocol"
26 | "github.com/yusuf-musleh/mmar/internal/utils"
27 | )
28 |
29 | var CLIENT_MAX_TUNNELS_REACHED = errors.New("Client reached max tunnels limit")
30 |
31 | type ConfigOptions struct {
32 | HttpPort string
33 | TcpPort string
34 | }
35 |
36 | type MmarServer struct {
37 | mu sync.Mutex
38 | clients map[string]ClientTunnel
39 | tunnelsPerIP map[string][]string
40 | }
41 |
42 | type IncomingRequest struct {
43 | responseChannel chan OutgoingResponse
44 | responseWriter http.ResponseWriter
45 | request *http.Request
46 | cancel context.CancelCauseFunc
47 | serializedReq []byte
48 | ctx context.Context
49 | }
50 |
51 | type OutgoingResponse struct {
52 | statusCode int
53 | body []byte
54 | }
55 |
56 | // Tunnel to Client
57 | type ClientTunnel struct {
58 | protocol.Tunnel
59 | incomingChannel chan IncomingRequest
60 | outgoingChannel chan protocol.TunnelMessage
61 | }
62 |
63 | func (ct *ClientTunnel) drainChannels() {
64 | // Drain all incoming requests to tunnel and cancel them
65 | incomingDrainerLoop:
66 | for {
67 | select {
68 | case incoming, _ := <-ct.incomingChannel:
69 | // Cancel incoming requests
70 | incoming.cancel(CLIENT_DISCONNECTED_ERR)
71 | default:
72 | // Close the TunneledRequests channel
73 | close(ct.incomingChannel)
74 | break incomingDrainerLoop
75 | }
76 | }
77 |
78 | // Draining all outgoing requests from tunnel
79 | OutgoingDrainerLoop:
80 | for {
81 | select {
82 | case <-ct.outgoingChannel:
83 | // Just draining, do nothing
84 | default:
85 | // Close the TunneledResponses channel
86 | close(ct.outgoingChannel)
87 | break OutgoingDrainerLoop
88 | }
89 | }
90 | }
91 |
92 | func (ct *ClientTunnel) close(graceful bool) {
93 | logger.Log(
94 | constants.DEFAULT_COLOR,
95 | fmt.Sprintf(
96 | "[%s] Client disconnected: %v, closing tunnel...",
97 | ct.Tunnel.Id,
98 | ct.Conn.RemoteAddr().String(),
99 | ),
100 | )
101 |
102 | // Drain channels before closing them to prevent panics if there are blocked writes
103 | ct.drainChannels()
104 |
105 | if graceful {
106 | // Wait a little for final response to complete, then close the connection
107 | gracefulCloseTimer := time.NewTimer(constants.GRACEFUL_SHUTDOWN_TIMEOUT * time.Second)
108 | <-gracefulCloseTimer.C
109 | }
110 |
111 | ct.Conn.Close()
112 | logger.Log(
113 | constants.DEFAULT_COLOR,
114 | fmt.Sprintf(
115 | "[%s] Tunnel connection closed: %v",
116 | ct.Tunnel.Id,
117 | ct.Conn.RemoteAddr().String(),
118 | ),
119 | )
120 | }
121 |
122 | // Serves simple stats for mmar server behind Basic Authentication
123 | func (ms *MmarServer) handleServerStats(w http.ResponseWriter, r *http.Request) {
124 | // Check Basic Authentication
125 | username, password, ok := r.BasicAuth()
126 | if !ok || !utils.ValidCredentials(username, password) {
127 | w.Header().Add("WWW-Authenticate", "Basic realm=\"stats\"")
128 | w.WriteHeader(http.StatusUnauthorized)
129 | return
130 | }
131 |
132 | stats := map[string]any{}
133 |
134 | // Add total connected clients count
135 | stats["connectedClientsCount"] = len(ms.clients)
136 |
137 | // Add list of connected clients, including only relevant fields
138 | clientStats := []map[string]string{}
139 | for _, val := range ms.clients {
140 | client := map[string]string{
141 | "id": val.Id,
142 | "createdOn": val.CreatedOn.Format(time.RFC3339),
143 | }
144 | clientStats = append(clientStats, client)
145 | }
146 | stats["connectedClients"] = clientStats
147 |
148 | // Marshal the result
149 | marshalledStats, err := json.Marshal(stats)
150 |
151 | if err != nil {
152 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to marshal server stats: %v", err))
153 | w.WriteHeader(http.StatusInternalServerError)
154 | return
155 | }
156 | w.WriteHeader(http.StatusOK)
157 | w.Write(marshalledStats)
158 | }
159 |
160 | func (ms *MmarServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
161 | // Extract subdomain to retrieve related client tunnel
162 | subdomain := utils.ExtractSubdomain(r.Host)
163 |
164 | // Handle stats subdomain
165 | if subdomain == "stats" {
166 | ms.handleServerStats(w, r)
167 | return
168 | }
169 |
170 | clientTunnel, clientExists := ms.clients[subdomain]
171 |
172 | if !clientExists {
173 | protocol.RespondTunnelErr(protocol.CLIENT_DISCONNECT, w)
174 | return
175 | }
176 |
177 | // Create channel to receive serialized request
178 | serializedReqChannel := make(chan []byte)
179 |
180 | ctx, cancel := context.WithCancelCause(r.Context())
181 |
182 | // Writing request to buffer to forward it
183 | go serializeRequest(ctx, r, cancel, serializedReqChannel)
184 |
185 | select {
186 | case <-ctx.Done():
187 | // We could not serialize request, so we cancelled it
188 | handleCancel(context.Cause(ctx), w)
189 | return
190 | case serializedRequest, _ := <-serializedReqChannel:
191 | // Request serialized, we can proceed to tunnel it
192 |
193 | // Create response channel to receive response for tunneled request
194 | respChannel := make(chan OutgoingResponse)
195 |
196 | // Tunnel the request
197 | clientTunnel.incomingChannel <- IncomingRequest{
198 | responseChannel: respChannel,
199 | responseWriter: w,
200 | request: r,
201 | cancel: cancel,
202 | serializedReq: serializedRequest,
203 | ctx: ctx,
204 | }
205 |
206 | select {
207 | case <-ctx.Done(): // Request is canceled or Tunnel is closed if context is canceled
208 | handleCancel(context.Cause(ctx), w)
209 | return
210 | case resp, _ := <-respChannel: // Await response for tunneled request
211 | // Add header to close the connection
212 | w.Header().Set("Connection", "close")
213 |
214 | // Write response headers with response status code to original client
215 | w.WriteHeader(resp.statusCode)
216 |
217 | // Write the response body to original client
218 | w.Write(resp.body)
219 | }
220 | }
221 | }
222 |
223 | func (ms *MmarServer) GenerateUniqueId() string {
224 | reservedIDs := []string{"", "admin", "stats"}
225 |
226 | generatedId := ""
227 | for _, exists := ms.clients[generatedId]; exists || slices.Contains(reservedIDs, generatedId); {
228 | var randSeed *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
229 | b := make([]byte, constants.ID_LENGTH)
230 | for i := range b {
231 | b[i] = constants.ID_CHARSET[randSeed.Intn(len(constants.ID_CHARSET))]
232 | }
233 | generatedId = string(b)
234 | }
235 |
236 | return generatedId
237 | }
238 |
239 | func (ms *MmarServer) TunnelLimitedIP(ip string) bool {
240 | tunnels, tunnelsExist := ms.tunnelsPerIP[ip]
241 |
242 | // Initialize tunnels list for IP
243 | if !tunnelsExist {
244 | ms.tunnelsPerIP[ip] = []string{}
245 | }
246 |
247 | return len(tunnels) >= constants.MAX_TUNNELS_PER_IP
248 | }
249 |
250 | func (ms *MmarServer) newClientTunnel(conn net.Conn) (*ClientTunnel, error) {
251 | // Acquire lock to create new client tunnel data
252 | ms.mu.Lock()
253 |
254 | // Generate unique ID for client
255 | uniqueId := ms.GenerateUniqueId()
256 | tunnel := protocol.Tunnel{
257 | Id: uniqueId,
258 | Conn: conn,
259 | CreatedOn: time.Now(),
260 | }
261 |
262 | // Create channels to tunnel requests to and recieve responses from
263 | incomingChannel := make(chan IncomingRequest)
264 | outgoingChannel := make(chan protocol.TunnelMessage)
265 |
266 | // Create client tunnel
267 | clientTunnel := ClientTunnel{
268 | tunnel,
269 | incomingChannel,
270 | outgoingChannel,
271 | }
272 |
273 | // Check if IP reached max tunnel limit
274 | clientIP := utils.ExtractIP(conn.RemoteAddr().String())
275 | limitedIP := ms.TunnelLimitedIP(clientIP)
276 | // If so, send limit message to client and close client tunnel
277 | if limitedIP {
278 | limitMessage := protocol.TunnelMessage{MsgType: protocol.CLIENT_TUNNEL_LIMIT}
279 | if err := clientTunnel.SendMessage(limitMessage); err != nil {
280 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to send Tunnel Limit msg to client: %v", err))
281 | }
282 | clientTunnel.close(false)
283 | // Release lock once errored
284 | ms.mu.Unlock()
285 | return nil, CLIENT_MAX_TUNNELS_REACHED
286 | }
287 |
288 | // Add client tunnel to clients
289 | ms.clients[uniqueId] = clientTunnel
290 |
291 | // Associate tunnel with client IP
292 | ms.tunnelsPerIP[clientIP] = append(ms.tunnelsPerIP[clientIP], uniqueId)
293 |
294 | // Release lock once created
295 | ms.mu.Unlock()
296 |
297 | // Send unique ID to client
298 | connMessage := protocol.TunnelMessage{MsgType: protocol.CLIENT_CONNECT, MsgData: []byte(uniqueId)}
299 | if err := clientTunnel.SendMessage(connMessage); err != nil {
300 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to send unique ID msg to client: %v", err))
301 | return nil, err
302 | }
303 |
304 | return &clientTunnel, nil
305 | }
306 |
307 | func (ms *MmarServer) handleTcpConnection(conn net.Conn) {
308 |
309 | clientTunnel, err := ms.newClientTunnel(conn)
310 |
311 | if err != nil {
312 | if errors.Is(err, CLIENT_MAX_TUNNELS_REACHED) {
313 | // Close the connection when client max tunnels limit reached
314 | conn.Close()
315 | return
316 | }
317 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to create ClientTunnel: %v", err))
318 | return
319 | }
320 |
321 | logger.Log(
322 | constants.DEFAULT_COLOR,
323 | fmt.Sprintf(
324 | "[%s] Tunnel created: %s",
325 | clientTunnel.Tunnel.Id,
326 | conn.RemoteAddr().String(),
327 | ),
328 | )
329 |
330 | // Process Tunnel Messages coming from mmar client
331 | go ms.processTunnelMessages(clientTunnel)
332 |
333 | // Start goroutine to process tunneled requests
334 | go ms.processTunneledRequestsForClient(clientTunnel)
335 | }
336 |
337 | func (ms *MmarServer) closeClientTunnel(ct *ClientTunnel) {
338 | // Remove Client Tunnel from clients
339 | delete(ms.clients, ct.Id)
340 |
341 | // Remove Client Tunnel from client IP
342 | clientIP := utils.ExtractIP(ct.Conn.RemoteAddr().String())
343 | tunnels := ms.tunnelsPerIP[clientIP]
344 | index := slices.Index(tunnels, ct.Id)
345 | if index != -1 {
346 | tunnels = slices.Delete(tunnels, index, index+1)
347 | ms.tunnelsPerIP[clientIP] = tunnels
348 | }
349 |
350 | // Gracefully close the Client Tunnel
351 | ct.close(true)
352 | }
353 |
354 | func (ms *MmarServer) processTunneledRequestsForClient(ct *ClientTunnel) {
355 | for {
356 | // Read requests coming in tunnel channel
357 | incomingReq, ok := <-ct.incomingChannel
358 | if !ok {
359 | // Channel closed, client disconencted, shutdown goroutine
360 | return
361 | }
362 |
363 | // Forward the request to mmar client
364 | reqMessage := protocol.TunnelMessage{MsgType: protocol.REQUEST, MsgData: incomingReq.serializedReq}
365 | if err := ct.SendMessage(reqMessage); err != nil {
366 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to send Request msg to client: %v", err))
367 | incomingReq.cancel(FAILED_TO_FORWARD_TO_MMAR_CLIENT_ERR)
368 | continue
369 | }
370 |
371 | // Wait for response for this request to come back from outgoing channel
372 | respTunnelMsg, ok := <-ct.outgoingChannel
373 | if !ok {
374 | // Channel closed, client disconencted, shutdown goroutine
375 | return
376 | }
377 |
378 | // Read response for forwarded request
379 | respReader := bufio.NewReader(bytes.NewReader(respTunnelMsg.MsgData))
380 | resp, respErr := http.ReadResponse(respReader, incomingReq.request)
381 |
382 | if respErr != nil {
383 | if errors.Is(respErr, io.ErrUnexpectedEOF) || errors.Is(respErr, net.ErrClosed) {
384 | incomingReq.cancel(CLIENT_DISCONNECTED_ERR)
385 | ms.closeClientTunnel(ct)
386 | return
387 | }
388 | failedReq := fmt.Sprintf("%s - %s%s", incomingReq.request.Method, html.EscapeString(incomingReq.request.URL.Path), incomingReq.request.URL.RawQuery)
389 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to return response: %v\n\n for req: %v", respErr, failedReq))
390 | incomingReq.cancel(FAILED_TO_READ_RESP_FROM_MMAR_CLIENT_ERR)
391 | continue
392 | }
393 |
394 | respBody, respBodyErr := io.ReadAll(resp.Body)
395 | if respBodyErr != nil {
396 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to parse response body: %v\n\n", respBodyErr))
397 | incomingReq.cancel(READ_RESP_BODY_ERR)
398 | continue
399 | }
400 |
401 | // Set headers for response
402 | for hKey, hVal := range resp.Header {
403 | incomingReq.responseWriter.Header().Set(hKey, hVal[0])
404 | // Add remaining values for header if more than than one exists
405 | for i := 1; i < len(hVal); i++ {
406 | incomingReq.responseWriter.Header().Add(hKey, hVal[i])
407 | }
408 | }
409 |
410 | // Close response body
411 | resp.Body.Close()
412 |
413 | select {
414 | case <-incomingReq.ctx.Done():
415 | // Request is canceled, on to the next request
416 | continue
417 | case incomingReq.responseChannel <- OutgoingResponse{statusCode: resp.StatusCode, body: respBody}:
418 | // Send response data back
419 | }
420 | }
421 | }
422 |
423 | func (ms *MmarServer) processTunnelMessages(ct *ClientTunnel) {
424 | for {
425 | // Send heartbeat if nothing has been read for a while
426 | receiveMessageTimeout := time.AfterFunc(
427 | constants.HEARTBEAT_FROM_SERVER_TIMEOUT*time.Second,
428 | func() {
429 | heartbeatMsg := protocol.TunnelMessage{MsgType: protocol.HEARTBEAT_FROM_SERVER}
430 | if err := ct.SendMessage(heartbeatMsg); err != nil {
431 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to send heartbeat: %v", err))
432 | ms.closeClientTunnel(ct)
433 | return
434 | }
435 | // Set a read timeout, if no response to heartbeat is recieved within that period,
436 | // that means the client has disconnected
437 | readDeadline := time.Now().Add((constants.READ_DEADLINE * time.Second))
438 | ct.Tunnel.Conn.SetReadDeadline(readDeadline)
439 | },
440 | )
441 |
442 | tunnelMsg, err := ct.ReceiveMessage()
443 | // If a message is received, stop the receiveMessageTimeout and remove the ReadTimeout
444 | // as we do not need to send heartbeat or check connection health in this iteration
445 | receiveMessageTimeout.Stop()
446 | ct.Tunnel.Conn.SetReadDeadline(time.Time{})
447 |
448 | if err != nil {
449 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Receive Message from client tunnel errored: %v", err))
450 | if utils.NetworkError(err) {
451 | // If error with connection, stop processing messages
452 | ms.closeClientTunnel(ct)
453 | return
454 | }
455 | continue
456 | }
457 |
458 | switch tunnelMsg.MsgType {
459 | case protocol.RESPONSE:
460 | ct.outgoingChannel <- tunnelMsg
461 | case protocol.LOCALHOST_NOT_RUNNING:
462 | // Create a response for Tunnel connected but localhost not running
463 | errState := protocol.TunnelErrState(protocol.LOCALHOST_NOT_RUNNING)
464 | responseBuff := createSerializedServerResp("200 OK", http.StatusOK, errState)
465 | notRunningMsg := protocol.TunnelMessage{MsgType: protocol.RESPONSE, MsgData: responseBuff.Bytes()}
466 | ct.outgoingChannel <- notRunningMsg
467 | case protocol.DEST_REQUEST_TIMEDOUT:
468 | // Create a response for Tunnel connected but localhost took too long to respond
469 | errState := protocol.TunnelErrState(protocol.DEST_REQUEST_TIMEDOUT)
470 | responseBuff := createSerializedServerResp("200 OK", http.StatusOK, errState)
471 | destTimedoutMsg := protocol.TunnelMessage{MsgType: protocol.RESPONSE, MsgData: responseBuff.Bytes()}
472 | ct.outgoingChannel <- destTimedoutMsg
473 | case protocol.CLIENT_DISCONNECT:
474 | ms.closeClientTunnel(ct)
475 | return
476 | case protocol.HEARTBEAT_FROM_CLIENT:
477 | heartbeatAckMsg := protocol.TunnelMessage{MsgType: protocol.HEARTBEAT_ACK}
478 | if err := ct.SendMessage(heartbeatAckMsg); err != nil {
479 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to heartbeat ack to client: %v", err))
480 | ms.closeClientTunnel(ct)
481 | return
482 | }
483 | case protocol.HEARTBEAT_ACK:
484 | // Got a heartbeat ack, that means the connection is healthy,
485 | // we do not need to perform any action
486 | case protocol.CLIENT_RECLAIM_SUBDOMAIN:
487 | newAndExistingIDs := strings.Split(string(tunnelMsg.MsgData), ":")
488 | newId := newAndExistingIDs[0]
489 | existingId := newAndExistingIDs[1]
490 |
491 | // Check if the subdomain has already been taken
492 | _, ok := ms.clients[existingId]
493 | if ok {
494 | // if so, close the tunnel, so the user can create a new one
495 | ms.closeClientTunnel(ct)
496 | return
497 | }
498 |
499 | ct.Tunnel.Id = existingId
500 |
501 | // Add existing client tunnel to clients
502 | ms.clients[existingId] = *ct
503 |
504 | // Remove newId tunnel from clients
505 | delete(ms.clients, newId)
506 |
507 | // Update the tunnels for the IP
508 | clientIP := utils.ExtractIP(ct.Conn.RemoteAddr().String())
509 | newIdIndex := slices.Index(ms.tunnelsPerIP[clientIP], newId)
510 | if newIdIndex == -1 {
511 | ms.tunnelsPerIP[clientIP] = append(ms.tunnelsPerIP[clientIP], existingId)
512 | } else {
513 | ms.tunnelsPerIP[clientIP][newIdIndex] = existingId
514 | }
515 |
516 | connMessage := protocol.TunnelMessage{MsgType: protocol.CLIENT_CONNECT, MsgData: []byte(existingId)}
517 | if err := ct.SendMessage(connMessage); err != nil {
518 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to send unique ID msg to client: %v", err))
519 | ms.closeClientTunnel(ct)
520 | return
521 | }
522 |
523 | logger.Log(
524 | constants.DEFAULT_COLOR,
525 | fmt.Sprintf(
526 | "[%s] Tunnel reclaimed: %s -> %s",
527 | newId,
528 | ct.Conn.RemoteAddr().String(),
529 | existingId,
530 | ),
531 | )
532 | case protocol.INVALID_RESP_FROM_DEST:
533 | // Create a response for receiving invalid response from destination server
534 | errState := protocol.TunnelErrState(protocol.INVALID_RESP_FROM_DEST)
535 | responseBuff := createSerializedServerResp("500 Internal Server Error", http.StatusInternalServerError, errState)
536 | invalidRespFromDestMsg := protocol.TunnelMessage{MsgType: protocol.RESPONSE, MsgData: responseBuff.Bytes()}
537 | ct.outgoingChannel <- invalidRespFromDestMsg
538 | }
539 | }
540 | }
541 |
542 | func Run(config ConfigOptions) {
543 | logger.LogStartMmarServer(config.TcpPort, config.HttpPort)
544 |
545 | // Channel handler for interrupt signal
546 | sigInt := make(chan os.Signal, 1)
547 | signal.Notify(sigInt, os.Interrupt)
548 |
549 | mux := http.NewServeMux()
550 |
551 | // Initialize Mmar Server
552 | mmarServer := MmarServer{
553 | clients: map[string]ClientTunnel{},
554 | tunnelsPerIP: map[string][]string{},
555 | }
556 | mux.Handle("/", logger.LoggerMiddleware(&mmarServer))
557 |
558 | go func() {
559 | ln, err := net.Listen("tcp", fmt.Sprintf(":%s", config.TcpPort))
560 | if err != nil {
561 | log.Fatalf("Failed to start TCP server: %v", err)
562 | return
563 | }
564 | logger.Log(
565 | constants.DEFAULT_COLOR,
566 | fmt.Sprintf(
567 | "TCP Server started successfully!\nListening for TCP Connections on port %s...",
568 | config.TcpPort,
569 | ),
570 | )
571 |
572 | for {
573 | conn, err := ln.Accept()
574 | if err != nil {
575 | logger.Log(constants.DEFAULT_COLOR, fmt.Sprintf("Failed to accept TCP connection: %v", err))
576 | } else {
577 | go mmarServer.handleTcpConnection(conn)
578 | }
579 | }
580 | }()
581 |
582 | go func() {
583 | logger.Log(
584 | constants.DEFAULT_COLOR,
585 | fmt.Sprintf(
586 | "HTTP Server started successfully!\nListening for HTTP Requests on %s...",
587 | config.HttpPort,
588 | ),
589 | )
590 | if err := http.ListenAndServe(fmt.Sprintf(":%s", config.HttpPort), mux); err != nil && err != http.ErrServerClosed {
591 | fmt.Fprintf(os.Stderr, "Error listening and serving: %s\n", err)
592 | }
593 | }()
594 |
595 | // Wait for an interrupt signal, if received, terminate gracefully
596 | <-sigInt
597 | log.Printf("Gracefully shutting down server...")
598 | }
599 |
--------------------------------------------------------------------------------
/internal/server/utils.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "bytes"
5 | "context"
6 | "errors"
7 | "fmt"
8 | "io"
9 | "net/http"
10 | "strconv"
11 | "time"
12 |
13 | "github.com/yusuf-musleh/mmar/constants"
14 | )
15 |
16 | var READ_BODY_CHUNK_ERR error = errors.New(constants.READ_BODY_CHUNK_ERR_TEXT)
17 | var READ_BODY_CHUNK_TIMEOUT_ERR error = errors.New(constants.READ_BODY_CHUNK_TIMEOUT_ERR_TEXT)
18 | var CLIENT_DISCONNECTED_ERR error = errors.New(constants.CLIENT_DISCONNECT_ERR_TEXT)
19 | var READ_RESP_BODY_ERR error = errors.New(constants.READ_RESP_BODY_ERR_TEXT)
20 | var MAX_REQ_BODY_SIZE_ERR error = errors.New(constants.MAX_REQ_BODY_SIZE_ERR_TEXT)
21 | var FAILED_TO_FORWARD_TO_MMAR_CLIENT_ERR error = errors.New(constants.FAILED_TO_FORWARD_TO_MMAR_CLIENT_ERR_TEXT)
22 | var FAILED_TO_READ_RESP_FROM_MMAR_CLIENT_ERR error = errors.New(constants.FAILED_TO_READ_RESP_FROM_MMAR_CLIENT_ERR_TEXT)
23 |
24 | func respondWith(respText string, w http.ResponseWriter, statusCode int) {
25 | w.Header().Set("Content-Length", strconv.Itoa(len(respText)))
26 | w.Header().Set("Connection", "close")
27 | w.WriteHeader(statusCode)
28 | w.Write([]byte(respText))
29 | }
30 |
31 | func handleCancel(cause error, w http.ResponseWriter) {
32 | switch cause {
33 | case context.Canceled:
34 | // Cancelled, do nothing
35 | return
36 | case READ_BODY_CHUNK_TIMEOUT_ERR:
37 | respondWith(cause.Error(), w, http.StatusRequestTimeout)
38 | case READ_BODY_CHUNK_ERR, CLIENT_DISCONNECTED_ERR:
39 | respondWith(cause.Error(), w, http.StatusBadRequest)
40 | case READ_RESP_BODY_ERR:
41 | respondWith(cause.Error(), w, http.StatusInternalServerError)
42 | case MAX_REQ_BODY_SIZE_ERR:
43 | respondWith(cause.Error(), w, http.StatusRequestEntityTooLarge)
44 | case FAILED_TO_FORWARD_TO_MMAR_CLIENT_ERR, FAILED_TO_READ_RESP_FROM_MMAR_CLIENT_ERR:
45 | respondWith(cause.Error(), w, http.StatusServiceUnavailable)
46 | }
47 | }
48 |
49 | func cancelRead(ctx context.Context, cancel context.CancelCauseFunc) {
50 | if errors.Is(ctx.Err(), context.Canceled) {
51 | // If context is Already cancelled, do nothing
52 | return
53 | }
54 |
55 | // Cancel request
56 | cancel(READ_BODY_CHUNK_TIMEOUT_ERR)
57 | }
58 |
59 | // Serialize HTTP request inorder to tunnel it to mmar client
60 | func serializeRequest(ctx context.Context, r *http.Request, cancel context.CancelCauseFunc, serializedRequestChannel chan []byte) {
61 | var requestBuff bytes.Buffer
62 |
63 | // Writing & serializing the HTTP Request Line
64 | requestBuff.WriteString(
65 | fmt.Sprintf(
66 | "%v %v %v\nHost: %v\n",
67 | r.Method,
68 | r.RequestURI,
69 | r.Proto,
70 | r.Host,
71 | ),
72 | )
73 |
74 | // Initialize read buffer/counter
75 | bufferSize := 2048
76 | contentLength := 0
77 | buf := make([]byte, bufferSize)
78 | reqBodyBytes := []byte{}
79 |
80 | // Keep reading response until completely read
81 | for {
82 | // Cancel request if read buffer times out
83 | readBufferTimeout := time.AfterFunc(
84 | constants.REQ_BODY_READ_CHUNK_TIMEOUT*time.Second,
85 | func() { cancelRead(ctx, cancel) },
86 | )
87 | r, readErr := r.Body.Read(buf)
88 | readBufferTimeout.Stop()
89 | contentLength += r
90 | if contentLength > constants.MAX_REQ_BODY_SIZE {
91 | cancel(MAX_REQ_BODY_SIZE_ERR)
92 | return
93 | }
94 | if readErr != nil {
95 | if errors.Is(readErr, io.EOF) {
96 | reqBodyBytes = append(reqBodyBytes, buf[:r]...)
97 | break
98 | }
99 | // Cancel request if there was an error reading
100 | cancel(READ_BODY_CHUNK_ERR)
101 | return
102 | }
103 | reqBodyBytes = append(reqBodyBytes, buf[:r]...)
104 | }
105 |
106 | // Set actual Content-Length header
107 | r.Header.Set("Content-Length", strconv.Itoa(contentLength))
108 |
109 | // Serialize headers
110 | r.Header.Clone().Write(&requestBuff)
111 |
112 | // Add new line
113 | requestBuff.WriteByte('\n')
114 |
115 | // Write body to buffer
116 | requestBuff.Write(reqBodyBytes)
117 | requestBuff.WriteByte('\n')
118 |
119 | // Send serialized request through channel
120 | serializedRequestChannel <- requestBuff.Bytes()
121 | }
122 |
123 | // Create HTTP response sent from mmar server to the end-user client
124 | func createSerializedServerResp(status string, statusCode int, body string) bytes.Buffer {
125 | resp := http.Response{
126 | Status: status,
127 | StatusCode: statusCode,
128 | Body: io.NopCloser(bytes.NewBufferString(body)),
129 | }
130 |
131 | // Writing response to buffer to tunnel it back
132 | var responseBuff bytes.Buffer
133 | resp.Write(&responseBuff)
134 |
135 | return responseBuff
136 | }
137 |
--------------------------------------------------------------------------------
/internal/utils/main.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "crypto/sha256"
5 | "crypto/subtle"
6 | "encoding/hex"
7 | "errors"
8 | "fmt"
9 | "io"
10 | "net"
11 | "os"
12 | "strings"
13 | "syscall"
14 |
15 | "github.com/yusuf-musleh/mmar/constants"
16 | )
17 |
18 | func ExtractSubdomain(host string) string {
19 | splitDomain := strings.Split(host, ".")
20 | subdomains := splitDomain[:1]
21 | return strings.ToLower(strings.Join(subdomains, "."))
22 | }
23 |
24 | func ExtractIP(remoteAddr string) string {
25 | ip, _, err := net.SplitHostPort(remoteAddr)
26 |
27 | // Return an empty string if we could not extract IP
28 | if err != nil {
29 | return ""
30 | }
31 | return ip
32 | }
33 |
34 | func MmarVersionUsage() {
35 | fmt.Fprintf(os.Stdout, "Prints the installed version of mmar.")
36 | }
37 |
38 | func MmarUsage() {
39 | intro := `mmar is an HTTP tunnel that exposes your localhost to the world on a public URL.
40 |
41 | Usage:
42 | mmar [command flags]`
43 | fmt.Fprintln(os.Stdout, intro)
44 |
45 | fmt.Fprint(os.Stdout, "\nCommands:\n")
46 |
47 | commands := ""
48 | for _, subcommand := range constants.MMAR_SUBCOMMANDS {
49 | command := strings.Join(subcommand, "\n ")
50 | commands = commands + " " + command + "\n"
51 | }
52 |
53 | fmt.Fprintln(os.Stdout, commands)
54 |
55 | fmt.Fprintln(os.Stdout)
56 | fmt.Fprintf(os.Stdout, "Run `mmar -h` to get help for a specific command\n\n")
57 | }
58 |
59 | // Decode hash string to bytes so it can be compared
60 | func decodeHash(hashStr string) ([]byte, error) {
61 | dst := make([]byte, hex.DecodedLen(len([]byte(hashStr))))
62 | n, err := hex.Decode(dst, []byte(hashStr))
63 | if err != nil {
64 | return []byte{}, err
65 | }
66 | return dst[:n], nil
67 | }
68 |
69 | // Check if provided Basic Auth credentials are valid
70 | func ValidCredentials(username string, password string) bool {
71 | // Compute Hash for provided username and password
72 | usernameHash := sha256.Sum256([]byte(username))
73 | passwordHash := sha256.Sum256([]byte(password))
74 |
75 | // Receive expected Hash for username
76 | envUsernameHash, foundUsernameHash := os.LookupEnv("USERNAME_HASH")
77 | var usernameDecodedHash []byte
78 | if foundUsernameHash {
79 | var decodeErr error
80 | usernameDecodedHash, decodeErr = decodeHash(envUsernameHash)
81 | if decodeErr != nil {
82 | return false
83 | }
84 | } else {
85 | // Fallback to default if not set
86 | defaultUsernameHash := sha256.Sum256([]byte(constants.SERVER_STATS_DEFAULT_USERNAME))
87 | usernameDecodedHash = defaultUsernameHash[:]
88 | }
89 |
90 | // Receive expected Hash for password
91 | envPasswordHash, foundPasswordHash := os.LookupEnv("PASSWORD_HASH")
92 | var passwordDecodedHash []byte
93 | if foundPasswordHash {
94 | var decodeErr error
95 | passwordDecodedHash, decodeErr = decodeHash(envPasswordHash)
96 | if decodeErr != nil {
97 | return false
98 | }
99 | } else {
100 | // Fallback to default if not set
101 | defaultPasswordHash := sha256.Sum256([]byte(constants.SERVER_STATS_DEFAULT_PASSWORD))
102 | passwordDecodedHash = defaultPasswordHash[:]
103 | }
104 |
105 | // Compare them to check if they match and are valid
106 | validUsername := subtle.ConstantTimeCompare(usernameHash[:], usernameDecodedHash) == 1
107 | validPassword := subtle.ConstantTimeCompare(passwordHash[:], passwordDecodedHash) == 1
108 | return validUsername && validPassword
109 | }
110 |
111 | func NetworkError(err error) bool {
112 | return errors.Is(err, io.EOF) ||
113 | errors.Is(err, io.ErrUnexpectedEOF) ||
114 | errors.Is(err, net.ErrClosed) ||
115 | errors.Is(err, syscall.ECONNRESET) ||
116 | errors.Is(err, os.ErrDeadlineExceeded)
117 | }
118 |
119 | func EnvVarOrDefault(envVar string, defaultVal string) string {
120 | envValue, ok := os.LookupEnv(envVar)
121 | if !ok {
122 | return defaultVal
123 | }
124 | return envValue
125 | }
126 |
--------------------------------------------------------------------------------
/simulations/devserver/main.go:
--------------------------------------------------------------------------------
1 | package devserver
2 |
3 | import (
4 | "encoding/json"
5 | "log"
6 | "net/http"
7 | "net/http/httptest"
8 | "strconv"
9 | "strings"
10 | "time"
11 | )
12 |
13 | const (
14 | GET_SUCCESS_URL = "/get"
15 | GET_FAILURE_URL = "/get-fail"
16 | POST_SUCCESS_URL = "/post"
17 | POST_FAILURE_URL = "/post-fail"
18 | REDIRECT_URL = "/redirect"
19 | BAD_RESPONSE_URL = "/bad-resp"
20 | LONG_RUNNING_URL = "/long-running"
21 | CRASH_URL = "/crash"
22 | )
23 |
24 | type DevServer struct {
25 | *httptest.Server
26 | }
27 |
28 | func NewDevServer() *DevServer {
29 | mux := setupMux()
30 |
31 | return &DevServer{
32 | httptest.NewServer(mux),
33 | }
34 | }
35 |
36 | func (ds *DevServer) Port() string {
37 | urlSplit := strings.Split(ds.URL, ":")
38 | devServerPort := urlSplit[len(urlSplit)-1]
39 | return devServerPort
40 | }
41 |
42 | func setupMux() *http.ServeMux {
43 | mux := http.NewServeMux()
44 |
45 | mux.Handle(GET_SUCCESS_URL, http.HandlerFunc(handleGet))
46 | mux.Handle(GET_FAILURE_URL, http.HandlerFunc(handleGetFail))
47 | mux.Handle(POST_SUCCESS_URL, http.HandlerFunc(handlePost))
48 | mux.Handle(POST_FAILURE_URL, http.HandlerFunc(handlePostFail))
49 | mux.Handle(REDIRECT_URL, http.HandlerFunc(handleRedirect))
50 | mux.Handle(BAD_RESPONSE_URL, http.HandlerFunc(handleBadResp))
51 | mux.Handle(LONG_RUNNING_URL, http.HandlerFunc(handleLongRunningReq))
52 | mux.Handle(CRASH_URL, http.HandlerFunc(handleCrashingReq))
53 |
54 | return mux
55 | }
56 |
57 | func handleGet(w http.ResponseWriter, r *http.Request) {
58 | // Include echo of request headers and query params in response to
59 | // confirm they were received
60 | respBody, err := json.Marshal(map[string]interface{}{
61 | "success": true,
62 | "data": "some data",
63 | "echo": map[string]interface{}{
64 | "reqHeaders": r.Header,
65 | "reqQueryParams": r.URL.Query(),
66 | },
67 | })
68 |
69 | if err != nil {
70 | log.Fatalf("Failed to marshal response for GET: %v", err)
71 | }
72 |
73 | w.Header().Set("Content-Type", "application/json")
74 | // Add custom header to response to confirm to confirm that they
75 | // propograte when going through mmar
76 | w.Header().Set("Simulation-Header", "devserver-handle-get")
77 | w.WriteHeader(http.StatusOK)
78 | w.Write(respBody)
79 | }
80 |
81 | func handleGetFail(w http.ResponseWriter, r *http.Request) {
82 | // Include echo of request headers in response to confirm they were received
83 | respBody, err := json.Marshal(map[string]interface{}{
84 | "success": false,
85 | "error": "Sent bad GET request",
86 | "echo": map[string]interface{}{
87 | "reqHeaders": r.Header,
88 | },
89 | })
90 |
91 | if err != nil {
92 | log.Fatalf("Failed to marshal response for GET: %v", err)
93 | }
94 |
95 | w.Header().Set("Content-Type", "application/json")
96 | // Add custom header to response to confirm to confirm that they
97 | // propograte when going through mmar
98 | w.Header().Set("Simulation-Header", "devserver-handle-get-fail")
99 | w.WriteHeader(http.StatusBadRequest)
100 | w.Write(respBody)
101 | }
102 |
103 | func handlePost(w http.ResponseWriter, r *http.Request) {
104 | // Include echo of request headers/body in response to confirm they were received
105 | var reqBody interface{}
106 | jsonDecoder := json.NewDecoder(r.Body)
107 | err := jsonDecoder.Decode(&reqBody)
108 | if err != nil {
109 | log.Fatal("Failed to decode request body to json", err)
110 | }
111 |
112 | respBody, err := json.Marshal(map[string]interface{}{
113 | "success": true,
114 | "data": map[string]interface{}{
115 | "posted": "data",
116 | },
117 | "echo": map[string]interface{}{
118 | "reqHeaders": r.Header,
119 | "reqBody": reqBody,
120 | },
121 | })
122 |
123 | if err != nil {
124 | log.Fatalf("Failed to marshal response for POST: %v", err)
125 | }
126 |
127 | w.Header().Set("Content-Type", "application/json")
128 | w.Header().Set("Content-Length", strconv.Itoa(len(respBody)))
129 | // Add custom header to response to confirm to confirm that they
130 | // propograte when going through mmar
131 | w.Header().Set("Simulation-Header", "devserver-handle-post-success")
132 | w.WriteHeader(http.StatusOK)
133 | w.Write(respBody)
134 | }
135 |
136 | func handlePostFail(w http.ResponseWriter, r *http.Request) {
137 | // Include echo of request headers/body in response to confirm they were received
138 | var reqBody interface{}
139 | jsonDecoder := json.NewDecoder(r.Body)
140 | err := jsonDecoder.Decode(&reqBody)
141 | if err != nil {
142 | log.Fatal("Failed to decode request body to json", err)
143 | }
144 |
145 | respBody, err := json.Marshal(map[string]interface{}{
146 | "success": false,
147 | "error": "Sent bad POST request",
148 | "echo": map[string]interface{}{
149 | "reqHeaders": r.Header,
150 | "reqBody": reqBody,
151 | },
152 | })
153 |
154 | if err != nil {
155 | log.Fatalf("Failed to marshal response for GET: %v", err)
156 | }
157 |
158 | w.Header().Set("Content-Type", "application/json")
159 | // Add custom header to response to confirm to confirm that they
160 | // propograte when going through mmar
161 | w.Header().Set("Simulation-Header", "devserver-handle-post-fail")
162 | w.WriteHeader(http.StatusBadRequest)
163 | w.Write(respBody)
164 | }
165 |
166 | // Request handler that returns a redirect
167 | func handleRedirect(w http.ResponseWriter, r *http.Request) {
168 | http.Redirect(w, r, GET_SUCCESS_URL, http.StatusFound)
169 | }
170 |
171 | // Request handler that returns an invalid HTTP response
172 | func handleBadResp(w http.ResponseWriter, r *http.Request) {
173 | // Get the underlying connection object
174 | // Assert that w supports Hijacking
175 | hijacker, ok := w.(http.Hijacker)
176 | if !ok {
177 | http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
178 | return
179 | }
180 |
181 | // Hijack the connection
182 | conn, buf, err := hijacker.Hijack()
183 | if err != nil {
184 | http.Error(w, "Hijacking failed", http.StatusInternalServerError)
185 | return
186 | }
187 | defer conn.Close()
188 |
189 | // Send back an invalid HTTP response
190 | buf.WriteString("some random string\r\n" +
191 | "\r\n" +
192 | "that is not a valid http resp")
193 | buf.Flush()
194 | }
195 |
196 | // Request handler that takes a long time before returning response
197 | func handleLongRunningReq(w http.ResponseWriter, r *http.Request) {
198 | // Include echo of request headers in response to confirm they were received
199 | respBody, err := json.Marshal(map[string]interface{}{
200 | "success": true,
201 | "data": "some data",
202 | "echo": map[string]interface{}{
203 | "reqHeaders": r.Header,
204 | },
205 | })
206 |
207 | if err != nil {
208 | log.Fatalf("Failed to marshal response for GET: %v", err)
209 | }
210 |
211 | // Sleep longer than the dest server request timeout (30s)
212 | time.Sleep(40 * time.Second)
213 |
214 | w.Header().Set("Content-Type", "application/json")
215 | // Add custom header to response to confirm to confirm that they
216 | // propograte when going through mmar
217 | w.Header().Set("Simulation-Header", "devserver-handle-long-running")
218 | w.WriteHeader(http.StatusOK)
219 | w.Write(respBody)
220 | }
221 |
222 | // Request handler that crashes the dev server
223 | func handleCrashingReq(w http.ResponseWriter, _ *http.Request) {
224 | panic("crashing devserver")
225 | }
226 |
--------------------------------------------------------------------------------
/simulations/dnsserver/main.go:
--------------------------------------------------------------------------------
1 | package dnsserver
2 |
3 | import (
4 | "encoding/binary"
5 | "encoding/hex"
6 | "log"
7 | "net"
8 | )
9 |
10 | const (
11 | LOCALHOST_DNS_SERVER = "127.0.0.1:3535"
12 | )
13 |
14 | // The purpose of this DNS server is resolve requests to localhost
15 | // addresses with subdomains. By default Go does not resolve localhost
16 | // addresses containing subdomains, so this basic DNS server always resolves
17 | // to the IPv6 loopback address "::1"
18 | func StartDnsServer() {
19 | addr, err := net.ResolveUDPAddr("udp", LOCALHOST_DNS_SERVER)
20 | if err != nil {
21 | log.Fatal("Failed to resolve UDP Address", err)
22 | }
23 |
24 | udpConn, err := net.ListenUDP("udp", addr)
25 |
26 | if err != nil {
27 | log.Fatal("Failed to start Dummy DNS server", err)
28 | }
29 |
30 | for {
31 | buffer := make([]byte, 512)
32 | n, udpWriteAddr, err := udpConn.ReadFromUDP(buffer)
33 | if err != nil {
34 | log.Fatal("Failed to read from UDP connection", err)
35 | }
36 |
37 | go handleDnsConn(udpConn, buffer, n, udpWriteAddr)
38 | }
39 | }
40 |
41 | // Handles building and returning the response for the DNS request, that resolves to ::1
42 | // For more details on the message format: https://datatracker.ietf.org/doc/html/rfc1035#autoid-39
43 | func handleDnsConn(udpConn *net.UDPConn, buffer []byte, n int, udpWriteAddr *net.UDPAddr) {
44 | // Extracting information from DNS request
45 | transactionID := buffer[:2]
46 | questionsCount := buffer[4:6]
47 | authorityRRs := buffer[8:10]
48 | msgQuestion := buffer[12:n]
49 |
50 | // Building DNS response
51 | respBuffer := []byte{}
52 | respBuffer = append(respBuffer, transactionID...)
53 |
54 | // Adding Response flag
55 | respFlag, _ := hex.DecodeString("8000") // Bits: 1000 0000 0000 0000
56 | respBuffer = append(respBuffer, respFlag...)
57 |
58 | // Adding QuestionsCount
59 | respBuffer = append(respBuffer, questionsCount...)
60 |
61 | // Adding Answers
62 | answer, _ := hex.DecodeString("0001")
63 | respBuffer = append(respBuffer, answer...)
64 |
65 | // Adding Authorities
66 | respBuffer = append(respBuffer, authorityRRs...)
67 |
68 | // Adding Additionals (there are none)
69 | respBuffer = append(respBuffer, byte(0))
70 | respBuffer = append(respBuffer, byte(0))
71 |
72 | // Adding the Name (eg: ikyx31.localhost)
73 | i := 0
74 | for i < n && hex.EncodeToString(msgQuestion[i:i+1]) != "00" {
75 | label := int(msgQuestion[i])
76 | for labelI := i; labelI < (i + label + 1); labelI++ {
77 | respBuffer = append(respBuffer, msgQuestion[labelI])
78 | }
79 | i = i + label + 1
80 | }
81 |
82 | // Adding the domain terminator "0x00"
83 | respBuffer = append(respBuffer, msgQuestion[i])
84 | i++
85 |
86 | // Adding Type
87 | respBuffer = append(respBuffer, msgQuestion[i:i+2]...)
88 |
89 | // Adding Class
90 | respBuffer = append(respBuffer, msgQuestion[i+2:i+4]...)
91 |
92 | // Adding pointer label and index
93 | // See: https://datatracker.ietf.org/doc/html/rfc1035#section-4.1.4
94 | pointerLabel, _ := hex.DecodeString("C0")
95 | addrIndex := 12
96 | respBuffer = append(respBuffer, pointerLabel...)
97 | respBuffer = append(respBuffer, byte(addrIndex))
98 |
99 | // Adding Type for answer
100 | respBuffer = append(respBuffer, msgQuestion[i:i+2]...)
101 |
102 | // Adding Class for answer
103 | respBuffer = append(respBuffer, msgQuestion[i+2:i+4]...)
104 |
105 | // Adding TTL (in seconds)
106 | ttl := make([]byte, 4)
107 | // Setting it to 1 hour (3600s)
108 | binary.BigEndian.PutUint32(ttl, 3600)
109 | respBuffer = append(respBuffer, ttl...)
110 |
111 | // Adding length of data, since its always ::1 (IPv6) it will be 16 bytes
112 | // Represented as 0000000000000001
113 | dataLength := make([]byte, 2)
114 | binary.BigEndian.PutUint16(dataLength, 16)
115 | respBuffer = append(respBuffer, dataLength...)
116 | for j := 0; j < 15; j++ {
117 | respBuffer = append(respBuffer, byte(0))
118 | }
119 | respBuffer = append(respBuffer, byte(1))
120 |
121 | // Writing the response back to UDP connection
122 | _, err := udpConn.WriteToUDP(respBuffer, udpWriteAddr)
123 | if err != nil {
124 | log.Fatal("Failed to write UDP response", err)
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/simulations/simulation_test.go:
--------------------------------------------------------------------------------
1 | package simulations
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "context"
7 | "encoding/json"
8 | "errors"
9 | "fmt"
10 | "log"
11 | "net/http"
12 | "net/url"
13 | "os"
14 | "os/exec"
15 | "strconv"
16 | "strings"
17 | "sync"
18 | "testing"
19 | "time"
20 |
21 | "github.com/yusuf-musleh/mmar/constants"
22 | "github.com/yusuf-musleh/mmar/simulations/devserver"
23 | "github.com/yusuf-musleh/mmar/simulations/dnsserver"
24 | )
25 |
26 | func StartMmarServer(ctx context.Context) {
27 | cmd := exec.CommandContext(ctx, "./mmar", "server")
28 |
29 | cmd.Stdin = os.Stdin
30 | cmd.Stdout = os.Stdout
31 | cmd.Stderr = os.Stderr
32 |
33 | cmd.Cancel = func() error {
34 | fmt.Println("cancelled, server")
35 | wait := time.NewTimer(4 * time.Second)
36 | <-wait.C
37 | return cmd.Process.Signal(os.Interrupt)
38 | }
39 |
40 | err := cmd.Run()
41 | if err != nil && !errors.Is(err, context.Canceled) {
42 | log.Fatal(err)
43 | }
44 | }
45 |
46 | func StartMmarClient(ctx context.Context, urlCh chan string, localDevServerPort string) {
47 | cmd := exec.CommandContext(
48 | ctx,
49 | "./mmar",
50 | "client",
51 | "--tunnel-host",
52 | "localhost",
53 | "--local-port",
54 | localDevServerPort,
55 | )
56 |
57 | // Pipe Stderr To capture logs for extracting the tunnel url
58 | pipe, _ := cmd.StderrPipe()
59 |
60 | cmd.Cancel = func() error {
61 | fmt.Println("cancelled, client")
62 | return cmd.Process.Signal(os.Interrupt)
63 | }
64 |
65 | err := cmd.Start()
66 | if err != nil && !errors.Is(err, context.Canceled) {
67 | log.Fatal("Failed to start", err)
68 | }
69 |
70 | // Read through the logs (stderr), print them and extract the tunnel url
71 | // to send back through the channel
72 | go func() {
73 | stdoutReader := bufio.NewReader(pipe)
74 | line, readErr := stdoutReader.ReadString('\n')
75 | for readErr == nil {
76 | fmt.Print(line)
77 | tunnelUrl := extractTunnelURL(line)
78 | if tunnelUrl != "" {
79 | urlCh <- tunnelUrl
80 | break
81 | }
82 | line, readErr = stdoutReader.ReadString('\n')
83 | }
84 | // Print extra line at the end
85 | fmt.Println()
86 | }()
87 |
88 | waitErr := cmd.Wait()
89 | if waitErr != nil && !errors.Is(waitErr, context.Canceled) {
90 | log.Fatal("Failed to wait", waitErr)
91 | }
92 | }
93 |
94 | func StartLocalDevServer() *devserver.DevServer {
95 | ds := devserver.NewDevServer()
96 | log.Printf("Started local dev server on: http://localhost:%v", ds.Port())
97 | return ds
98 | }
99 |
100 | // Test to verify successful GET request through mmar tunnel returned expected request/response
101 | func verifyGetRequestSuccess(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
102 | defer wg.Done()
103 | req, reqErr := http.NewRequest("GET", tunnelUrl+devserver.GET_SUCCESS_URL, nil)
104 | if reqErr != nil {
105 | log.Fatalf("Failed to create new request: %v", reqErr)
106 | }
107 | // Adding custom header to confirm that they are propogated when going through mmar
108 | req.Header.Set("Simulation-Test", "verify-get-request-success")
109 |
110 | // Adding query params to confirm that they get propogated when going through mmar
111 | q := req.URL.Query()
112 | q.Add("first", "query param")
113 | q.Add("second", "param & last")
114 | req.URL.RawQuery = q.Encode()
115 |
116 | resp, respErr := client.Do(req)
117 | if respErr != nil {
118 | log.Printf("Failed to get response: %v", respErr)
119 | }
120 |
121 | expectedReqHeaders := map[string][]string{
122 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
123 | "Accept-Encoding": {"gzip"}, // Default header in golang client
124 | "Simulation-Test": {"verify-get-request-success"},
125 | }
126 |
127 | expectedBody := map[string]interface{}{
128 | "success": true,
129 | "data": "some data",
130 | "echo": map[string]interface{}{
131 | "reqHeaders": expectedReqHeaders,
132 | "reqQueryParams": q,
133 | },
134 | }
135 | marshaledBody, _ := json.Marshal(expectedBody)
136 |
137 | expectedResp := expectedResponse{
138 | statusCode: http.StatusOK,
139 | headers: map[string]string{
140 | "Content-Length": strconv.Itoa(len(marshaledBody)),
141 | "Content-Type": "application/json",
142 | "Simulation-Header": "devserver-handle-get",
143 | },
144 | jsonBody: expectedBody,
145 | }
146 |
147 | validateRequestResponse(t, expectedResp, resp, "verifyGetRequestSuccess")
148 | }
149 |
150 | // Test to verify failed GET request through mmar tunnel returned expected request/response
151 | func verifyGetRequestFail(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
152 | defer wg.Done()
153 | req, reqErr := http.NewRequest("GET", tunnelUrl+devserver.GET_FAILURE_URL, nil)
154 | if reqErr != nil {
155 | log.Fatalf("Failed to create new request: %v", reqErr)
156 | }
157 | // Adding custom header to confirm that they are propogated when going through mmar
158 | req.Header.Set("Simulation-Test", "verify-get-request-fail")
159 |
160 | resp, respErr := client.Do(req)
161 | if respErr != nil {
162 | log.Printf("Failed to get response: %v", respErr)
163 | }
164 |
165 | expectedReqHeaders := map[string][]string{
166 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
167 | "Accept-Encoding": {"gzip"}, // Default header in golang client
168 | "Simulation-Test": {"verify-get-request-fail"},
169 | }
170 |
171 | expectedBody := map[string]interface{}{
172 | "success": false,
173 | "error": "Sent bad GET request",
174 | "echo": map[string]interface{}{
175 | "reqHeaders": expectedReqHeaders,
176 | },
177 | }
178 | marshaledBody, _ := json.Marshal(expectedBody)
179 |
180 | expectedResp := expectedResponse{
181 | statusCode: http.StatusBadRequest,
182 | headers: map[string]string{
183 | "Content-Length": strconv.Itoa(len(marshaledBody)),
184 | "Content-Type": "application/json",
185 | "Simulation-Header": "devserver-handle-get-fail",
186 | },
187 | jsonBody: expectedBody,
188 | }
189 |
190 | validateRequestResponse(t, expectedResp, resp, "verifyGetRequestFail")
191 | }
192 |
193 | // Test to verify successful POST request through mmar tunnel returned expected request/response
194 | func verifyPostRequestSuccess(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
195 | defer wg.Done()
196 | reqBody := map[string]interface{}{
197 | "success": true,
198 | "payload": map[string]interface{}{
199 | "some": "data",
200 | "moreData": 123,
201 | },
202 | }
203 | serializedReqBody, _ := json.Marshal(reqBody)
204 | req, reqErr := http.NewRequest("POST", tunnelUrl+devserver.POST_SUCCESS_URL, bytes.NewBuffer(serializedReqBody))
205 | if reqErr != nil {
206 | log.Fatalf("Failed to create new request: %v", reqErr)
207 | }
208 | // Adding custom header to confirm that they are propogated when going through mmar
209 | req.Header.Set("Simulation-Test", "verify-post-request-success")
210 |
211 | resp, respErr := client.Do(req)
212 | if respErr != nil {
213 | log.Printf("Failed to get response: %v", respErr)
214 | }
215 |
216 | expectedReqHeaders := map[string][]string{
217 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
218 | "Accept-Encoding": {"gzip"}, // Default header in golang client
219 | "Simulation-Test": {"verify-post-request-success"},
220 | "Content-Length": {strconv.Itoa(len(serializedReqBody))},
221 | }
222 |
223 | expectedBody := map[string]interface{}{
224 | "success": true,
225 | "data": map[string]interface{}{
226 | "posted": "data",
227 | },
228 | "echo": map[string]interface{}{
229 | "reqHeaders": expectedReqHeaders,
230 | "reqBody": reqBody,
231 | },
232 | }
233 | marshaledBody, _ := json.Marshal(expectedBody)
234 |
235 | expectedResp := expectedResponse{
236 | statusCode: http.StatusOK,
237 | headers: map[string]string{
238 | "Content-Length": strconv.Itoa(len(marshaledBody)),
239 | "Content-Type": "application/json",
240 | "Simulation-Header": "devserver-handle-post-success",
241 | },
242 | jsonBody: expectedBody,
243 | }
244 |
245 | validateRequestResponse(t, expectedResp, resp, "verifyPostRequestSuccess")
246 | }
247 |
248 | // Test to verify failed POST request through mmar tunnel returned expected request/response
249 | func verifyPostRequestFail(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
250 | defer wg.Done()
251 | reqBody := map[string]interface{}{
252 | "success": false,
253 | "payload": map[string]interface{}{
254 | "some": "data",
255 | "moreData": 123,
256 | },
257 | }
258 | serializedReqBody, _ := json.Marshal(reqBody)
259 | req, reqErr := http.NewRequest("POST", tunnelUrl+devserver.POST_FAILURE_URL, bytes.NewBuffer(serializedReqBody))
260 | if reqErr != nil {
261 | log.Fatalf("Failed to create new request: %v", reqErr)
262 | }
263 | // Adding custom header to confirm that they are propogated when going through mmar
264 | req.Header.Set("Simulation-Test", "verify-post-request-fail")
265 |
266 | resp, respErr := client.Do(req)
267 | if respErr != nil {
268 | log.Printf("Failed to get response: %v", respErr)
269 | }
270 |
271 | expectedReqHeaders := map[string][]string{
272 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
273 | "Accept-Encoding": {"gzip"}, // Default header in golang client
274 | "Simulation-Test": {"verify-post-request-fail"},
275 | "Content-Length": {strconv.Itoa(len(serializedReqBody))},
276 | }
277 |
278 | expectedBody := map[string]interface{}{
279 | "success": false,
280 | "error": "Sent bad POST request",
281 | "echo": map[string]interface{}{
282 | "reqHeaders": expectedReqHeaders,
283 | "reqBody": reqBody,
284 | },
285 | }
286 | marshaledBody, _ := json.Marshal(expectedBody)
287 |
288 | expectedResp := expectedResponse{
289 | statusCode: http.StatusBadRequest,
290 | headers: map[string]string{
291 | "Content-Length": strconv.Itoa(len(marshaledBody)),
292 | "Content-Type": "application/json",
293 | "Simulation-Header": "devserver-handle-post-fail",
294 | },
295 | jsonBody: expectedBody,
296 | }
297 |
298 | validateRequestResponse(t, expectedResp, resp, "verifyPostRequestFail")
299 | }
300 |
301 | // Test to verify redirects works as expected
302 | func verifyRedirectsHandled(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
303 | defer wg.Done()
304 | reqBody := map[string]interface{}{
305 | "success": true,
306 | "payload": map[string]interface{}{
307 | "some": "data",
308 | "moreData": 123,
309 | },
310 | }
311 | serializedReqBody, _ := json.Marshal(reqBody)
312 | req, reqErr := http.NewRequest("POST", tunnelUrl+devserver.REDIRECT_URL, bytes.NewBuffer(serializedReqBody))
313 | if reqErr != nil {
314 | log.Fatalf("Failed to create new request: %v", reqErr)
315 | }
316 |
317 | // Adding custom header to confirm that they are propogated when going through mmar
318 | req.Header.Set("Simulation-Test", "verify-redirect-request")
319 |
320 | resp, respErr := client.Do(req)
321 | if respErr != nil {
322 | log.Printf("Failed to get response: %v", respErr)
323 | }
324 |
325 | expectedReqHeaders := map[string][]string{
326 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
327 | "Accept-Encoding": {"gzip"}, // Default header in golang client
328 | "Simulation-Test": {"verify-redirect-request"},
329 | "Referer": {tunnelUrl + "/redirect"}, // Include referer header since it redirects
330 | }
331 |
332 | expectedBody := map[string]interface{}{
333 | "success": true,
334 | "data": "some data",
335 | "echo": map[string]interface{}{
336 | "reqHeaders": expectedReqHeaders,
337 | "reqQueryParams": map[string][]string{},
338 | },
339 | }
340 | marshaledBody, _ := json.Marshal(expectedBody)
341 |
342 | expectedResp := expectedResponse{
343 | statusCode: http.StatusOK,
344 | headers: map[string]string{
345 | "Content-Length": strconv.Itoa(len(marshaledBody)),
346 | "Content-Type": "application/json",
347 | "Simulation-Header": "devserver-handle-get",
348 | },
349 | jsonBody: expectedBody,
350 | }
351 |
352 | validateRequestResponse(t, expectedResp, resp, "verifyRedirectsHandled")
353 | }
354 |
355 | // Test to verify a HTTP request with an invalid method is handled
356 | func verifyInvalidMethodRequestHandled(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
357 | defer wg.Done()
358 | url, urlErr := url.Parse(tunnelUrl + devserver.GET_SUCCESS_URL)
359 | if urlErr != nil {
360 | log.Fatal("Failed to create url", urlErr)
361 | }
362 |
363 | req := &http.Request{
364 | Method: "INVALID_METHOD",
365 | URL: url,
366 | Header: make(http.Header),
367 | }
368 | // Adding custom header to confirm that they are propogated when going through mmar
369 | req.Header.Set("Simulation-Test", "verify-invalid-method-request")
370 |
371 | resp, respErr := client.Do(req)
372 | if respErr != nil {
373 | t.Errorf("Failed to get response %v", respErr)
374 | }
375 |
376 | // Using the same validation for "verifyGetRequestSuccess" since we are
377 | // hitting the same endpoint
378 | expectedReqHeaders := map[string][]string{
379 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
380 | "Accept-Encoding": {"gzip"}, // Default header in golang client
381 | "Simulation-Test": {"verify-invalid-method-request"},
382 | }
383 |
384 | expectedBody := map[string]interface{}{
385 | "success": true,
386 | "data": "some data",
387 | "echo": map[string]interface{}{
388 | "reqHeaders": expectedReqHeaders,
389 | "reqQueryParams": map[string][]string{},
390 | },
391 | }
392 | marshaledBody, _ := json.Marshal(expectedBody)
393 |
394 | expectedResp := expectedResponse{
395 | statusCode: http.StatusOK,
396 | headers: map[string]string{
397 | "Content-Length": strconv.Itoa(len(marshaledBody)),
398 | "Content-Type": "application/json",
399 | "Simulation-Header": "devserver-handle-get",
400 | },
401 | jsonBody: expectedBody,
402 | }
403 |
404 | validateRequestResponse(t, expectedResp, resp, "verifyInvalidMethodRequestHandled")
405 | }
406 |
407 | // Test to verify a HTTP request with invalid headers is handled
408 | func verifyInvalidHeadersRequestHandled(t *testing.T, tunnelUrl string, wg *sync.WaitGroup) {
409 | defer wg.Done()
410 | dialUrl := strings.Replace(tunnelUrl, "http://", "", 1)
411 |
412 | // Write a raw HTTP request with an invalid header
413 | req := "GET / HTTP/1.1\r\n" +
414 | "Host: " + dialUrl + "\r\n" +
415 | ":Invalid-Header: :value\r\n" + // Header that starts with a colon (invalid)
416 | "\r\n"
417 |
418 | // Manually perform request and read response
419 | conn := manualHttpRequest(dialUrl, req)
420 | resp, respErr := manualReadResponse(conn)
421 |
422 | if respErr != nil {
423 | t.Errorf("%v: Failed to get response %v", "verifyInvalidHeadersRequestHandled", respErr)
424 | }
425 |
426 | if resp.StatusCode != http.StatusBadRequest {
427 | t.Errorf(
428 | "%v: resp.StatusCode = %v; want %v",
429 | "verifyInvalidHeadersRequestHandled",
430 | resp.StatusCode,
431 | http.StatusBadRequest,
432 | )
433 | }
434 | }
435 |
436 | // Test to verify a HTTP request with invalid protocol version is handled
437 | func verifyInvalidHttpVersionRequestHandled(t *testing.T, tunnelUrl string, wg *sync.WaitGroup) {
438 | defer wg.Done()
439 | dialUrl := strings.Replace(tunnelUrl, "http://", "", 1)
440 |
441 | // Write a raw HTTP request with an invalid HTTP version
442 | req := "GET / HTTP/2.0.1\r\n" + // Invalid HTTP version
443 | "Host: " + dialUrl + "\r\n" +
444 | "\r\n"
445 |
446 | // Manually perform request and read response
447 | conn := manualHttpRequest(dialUrl, req)
448 | resp, respErr := manualReadResponse(conn)
449 |
450 | if respErr != nil {
451 | t.Errorf("%v: Failed to get response %v", "verifyInvalidHttpVersionRequestHandled", respErr)
452 | }
453 |
454 | if resp.StatusCode != http.StatusBadRequest {
455 | t.Errorf(
456 | "%v: resp.StatusCode = %v; want %v",
457 | "verifyInvalidHttpVersionRequestHandled",
458 | resp.StatusCode,
459 | http.StatusBadRequest,
460 | )
461 | }
462 | }
463 |
464 | // Test to verify a HTTP request with a invalid Content-Length header
465 | func verifyInvalidContentLengthRequestHandled(t *testing.T, tunnelUrl string, wg *sync.WaitGroup) {
466 | defer wg.Done()
467 | dialUrl := strings.Replace(tunnelUrl, "http://", "", 1)
468 |
469 | // Write a raw HTTP request with an invalid Content-Length header
470 | req := "POST /post HTTP/1.1\r\n" +
471 | "Host: " + dialUrl + "\r\n" +
472 | "Content-Length: abc" + "\r\n" + // Invalid Content-Length header
473 | "\r\n"
474 |
475 | // Manually perform request and read response for invalid Content-Length
476 | conn := manualHttpRequest(dialUrl, req)
477 | resp, respErr := manualReadResponse(conn)
478 |
479 | if respErr != nil {
480 | t.Errorf("%v: Failed to get response %v", "verifyInvalidContentLengthRequestHandled", respErr)
481 | }
482 |
483 | if resp.StatusCode != http.StatusBadRequest {
484 | t.Errorf(
485 | "%v: resp.StatusCode = %v; want %v",
486 | "verifyInvalidContentLengthRequestHandled",
487 | resp.StatusCode,
488 | http.StatusBadRequest,
489 | )
490 | }
491 | }
492 |
493 | // Test to verify a HTTP request with a mismatched Content-Length header
494 | func verifyMismatchedContentLengthRequestHandled(t *testing.T, tunnelUrl string, wg *sync.WaitGroup) {
495 | defer wg.Done()
496 | dialUrl := strings.Replace(tunnelUrl, "http://", "", 1)
497 |
498 | serializedBody := "{\"message\": \"Hello\"}\r\n"
499 |
500 | // Write a raw HTTP request with an invalid Content-Length header
501 | req := "POST /post HTTP/1.1\r\n" +
502 | "Host: " + dialUrl + "\r\n" +
503 | "Content-Length: 25\r\n" + // Mismatched Content-Length header, should be 20
504 | "Simulation-Test: verify-mismatched-content-length-request-handled\r\n" +
505 | "\r\n" +
506 | serializedBody
507 |
508 | // Manually perform request and read response for mismatched content-length
509 | conn := manualHttpRequest(dialUrl, req)
510 | resp, respErr := manualReadResponse(conn)
511 |
512 | if respErr != nil {
513 | t.Errorf("%v: Failed to get response %v", "verifyMismatchedContentLengthRequestHandled", respErr)
514 | }
515 |
516 | expectedBody := constants.READ_BODY_CHUNK_TIMEOUT_ERR_TEXT
517 |
518 | expectedResp := expectedResponse{
519 | statusCode: http.StatusRequestTimeout,
520 | headers: map[string]string{
521 | "Content-Length": strconv.Itoa(len(expectedBody)),
522 | "Content-Type": "text/plain; charset=utf-8",
523 | },
524 | textBody: expectedBody,
525 | }
526 |
527 | validateRequestResponse(t, expectedResp, resp, "verifyMismatchedContentLengthRequestHandled")
528 | }
529 |
530 | // Test to verify a HTTP request with a Content-Length header but no body
531 | func verifyContentLengthWithNoBodyRequestHandled(t *testing.T, tunnelUrl string, wg *sync.WaitGroup) {
532 | defer wg.Done()
533 | dialUrl := strings.Replace(tunnelUrl, "http://", "", 1)
534 |
535 | // Write a raw HTTP request with Content-Length header but no body
536 | req := "POST /post HTTP/1.1\r\n" +
537 | "Host: " + dialUrl + "\r\n" +
538 | "Content-Length: 25\r\n" + // Content-Length header provided but no body
539 | "Simulation-Test: verify-content-length-with-no-body-request-handled\r\n" +
540 | "\r\n"
541 |
542 | // Manually perform request and read response
543 | conn := manualHttpRequest(dialUrl, req)
544 | resp, respErr := manualReadResponse(conn)
545 |
546 | if respErr != nil {
547 | t.Errorf("%v: Failed to get response %v", "verifyContentLengthWithNoBodyRequestHandled", respErr)
548 | }
549 |
550 | expectedBody := constants.READ_BODY_CHUNK_TIMEOUT_ERR_TEXT
551 |
552 | expectedResp := expectedResponse{
553 | statusCode: http.StatusRequestTimeout,
554 | headers: map[string]string{
555 | "Content-Length": strconv.Itoa(len(expectedBody)),
556 | "Content-Type": "text/plain; charset=utf-8",
557 | },
558 | textBody: expectedBody,
559 | }
560 |
561 | validateRequestResponse(t, expectedResp, resp, "verifyContentLengthWithNoBodyRequestHandled")
562 | }
563 |
564 | // Test to verify a HTTP request with a large body but still within the limit
565 | func verifyRequestWithLargeBody(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
566 | defer wg.Done()
567 | littleUnderTenMb := 999989
568 | reqBody := map[string]interface{}{
569 | "success": true,
570 | "payload": make([]byte, littleUnderTenMb),
571 | }
572 |
573 | serializedReqBody, _ := json.Marshal(reqBody)
574 | req, reqErr := http.NewRequest("POST", tunnelUrl+devserver.POST_SUCCESS_URL, bytes.NewBuffer(serializedReqBody))
575 | if reqErr != nil {
576 | log.Fatalf("Failed to create new request: %v", reqErr)
577 | }
578 | // Adding custom header to confirm that they are propogated when going through mmar
579 | req.Header.Set("Simulation-Test", "verify-large-post-request-success")
580 |
581 | resp, respErr := client.Do(req)
582 | if respErr != nil {
583 | log.Printf("Failed to get response: %v", respErr)
584 | }
585 |
586 | expectedReqHeaders := map[string][]string{
587 | "User-Agent": {"Go-http-client/1.1"}, // Default header in golang client
588 | "Accept-Encoding": {"gzip"}, // Default header in golang client
589 | "Simulation-Test": {"verify-large-post-request-success"},
590 | "Content-Length": {strconv.Itoa(len(serializedReqBody))},
591 | }
592 |
593 | expectedBody := map[string]interface{}{
594 | "success": true,
595 | "data": map[string]interface{}{
596 | "posted": "data",
597 | },
598 | "echo": map[string]interface{}{
599 | "reqHeaders": expectedReqHeaders,
600 | "reqBody": reqBody,
601 | },
602 | }
603 | marshaledBody, _ := json.Marshal(expectedBody)
604 |
605 | expectedResp := expectedResponse{
606 | statusCode: http.StatusOK,
607 | headers: map[string]string{
608 | "Content-Length": strconv.Itoa(len(marshaledBody)),
609 | "Content-Type": "application/json",
610 | "Simulation-Header": "devserver-handle-post-success",
611 | },
612 | jsonBody: expectedBody,
613 | }
614 |
615 | validateRequestResponse(t, expectedResp, resp, "verifyRequestWithLargeBody")
616 | }
617 |
618 | // Test to verify a HTTP request with a very large body, over the 10mb limit
619 | func verifyRequestWithVeryLargeBody(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
620 | defer wg.Done()
621 | hundredMb := 100000000
622 | reqBody := map[string]interface{}{
623 | "success": true,
624 | "payload": make([]byte, hundredMb),
625 | }
626 |
627 | serializedReqBody, _ := json.Marshal(reqBody)
628 | req, reqErr := http.NewRequest("POST", tunnelUrl+devserver.POST_SUCCESS_URL, bytes.NewBuffer(serializedReqBody))
629 | if reqErr != nil {
630 | log.Fatalf("Failed to create new request: %v", reqErr)
631 | }
632 | // Adding custom header to confirm that they are propogated when going through mmar
633 | req.Header.Set("Simulation-Test", "verify-very-large-post-request-success")
634 |
635 | resp, respErr := client.Do(req)
636 | if respErr != nil {
637 | log.Printf("Failed to get response: %v", respErr)
638 | }
639 |
640 | expectedBody := constants.MAX_REQ_BODY_SIZE_ERR_TEXT
641 |
642 | expectedResp := expectedResponse{
643 | statusCode: http.StatusRequestEntityTooLarge,
644 | headers: map[string]string{
645 | "Content-Length": strconv.Itoa(len(expectedBody)),
646 | "Content-Type": "text/plain; charset=utf-8",
647 | },
648 | textBody: expectedBody,
649 | }
650 |
651 | validateRequestResponse(t, expectedResp, resp, "verifyRequestWithVeryLargeBody")
652 | }
653 |
654 | // Test to verify that mmar handles invalid response from dev server gracefully
655 | func verifyDevServerReturningInvalidRespHandled(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
656 | defer wg.Done()
657 | req, reqErr := http.NewRequest("GET", tunnelUrl+devserver.BAD_RESPONSE_URL, nil)
658 | if reqErr != nil {
659 | log.Fatalf("Failed to create new request: %v", reqErr)
660 | }
661 |
662 | resp, respErr := client.Do(req)
663 | if respErr != nil {
664 | log.Printf("Failed to get response: %v", respErr)
665 | }
666 |
667 | expectedBody := constants.READ_RESP_BODY_ERR_TEXT
668 |
669 | expectedResp := expectedResponse{
670 | statusCode: http.StatusInternalServerError,
671 | headers: map[string]string{
672 | "Content-Length": strconv.Itoa(len(expectedBody)),
673 | "Content-Type": "text/plain; charset=utf-8",
674 | },
675 | textBody: expectedBody,
676 | }
677 |
678 | validateRequestResponse(t, expectedResp, resp, "verifyDevServerReturningInvalidRespHandled")
679 | }
680 |
681 | // Test to verify that mmar timesout if devserver takes too long to respond
682 | func verifyDevServerLongRunningReqHandledGradefully(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
683 | defer wg.Done()
684 | req, reqErr := http.NewRequest("GET", tunnelUrl+devserver.LONG_RUNNING_URL, nil)
685 | if reqErr != nil {
686 | log.Fatalf("Failed to create new request: %v", reqErr)
687 | }
688 |
689 | resp, respErr := client.Do(req)
690 | if respErr != nil {
691 | log.Printf("Failed to get response: %v", respErr)
692 | }
693 |
694 | expectedBody := constants.DEST_REQUEST_TIMEDOUT_ERR_TEXT
695 |
696 | expectedResp := expectedResponse{
697 | statusCode: http.StatusOK,
698 | headers: map[string]string{
699 | "Content-Length": strconv.Itoa(len(expectedBody)),
700 | "Content-Type": "text/plain; charset=utf-8",
701 | },
702 | textBody: expectedBody,
703 | }
704 |
705 | validateRequestResponse(t, expectedResp, resp, "verifyDevServerLongRunningReqHandledGradefully")
706 | }
707 |
708 | // Test to verify that mmar handles crashes in the devserver gracefully
709 | func verifyDevServerCrashHandledGracefully(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup) {
710 | defer wg.Done()
711 | req, reqErr := http.NewRequest("GET", tunnelUrl+devserver.CRASH_URL, nil)
712 | if reqErr != nil {
713 | log.Fatalf("Failed to create new request: %v", reqErr)
714 | }
715 |
716 | resp, respErr := client.Do(req)
717 | if respErr != nil {
718 | log.Printf("Failed to get response: %v", respErr)
719 | }
720 |
721 | expectedBody := constants.LOCALHOST_NOT_RUNNING_ERR_TEXT
722 |
723 | expectedResp := expectedResponse{
724 | statusCode: http.StatusOK,
725 | headers: map[string]string{
726 | "Content-Length": strconv.Itoa(len(expectedBody)),
727 | "Content-Type": "text/plain; charset=utf-8",
728 | },
729 | textBody: expectedBody,
730 | }
731 |
732 | validateRequestResponse(t, expectedResp, resp, "verifyDevServerCrashHandledGracefully")
733 | }
734 |
735 | func TestSimulation(t *testing.T) {
736 | simulationCtx, simulationCancel := context.WithCancel(context.Background())
737 |
738 | localDevServer := StartLocalDevServer()
739 | defer localDevServer.Close()
740 |
741 | go dnsserver.StartDnsServer()
742 |
743 | go StartMmarServer(simulationCtx)
744 | wait := time.NewTimer(2 * time.Second)
745 | <-wait.C
746 | clientUrlCh := make(chan string)
747 | go StartMmarClient(simulationCtx, clientUrlCh, localDevServer.Port())
748 |
749 | // Wait for tunnel url
750 | tunnelUrl := <-clientUrlCh
751 |
752 | // Initialize http client
753 | client := httpClient()
754 |
755 | var wg sync.WaitGroup
756 |
757 | simulationTests := []func(t *testing.T, client *http.Client, tunnelUrl string, wg *sync.WaitGroup){
758 | // Perform simulated usage tests
759 | verifyGetRequestSuccess,
760 | verifyGetRequestFail,
761 | verifyPostRequestSuccess,
762 | verifyPostRequestFail,
763 | verifyRedirectsHandled,
764 |
765 | // Perform Invalid HTTP requests to test durability of mmar
766 | verifyInvalidMethodRequestHandled,
767 | verifyRequestWithLargeBody,
768 |
769 | // Perform edge case usage tests
770 | verifyRequestWithVeryLargeBody,
771 | verifyDevServerReturningInvalidRespHandled,
772 | verifyDevServerLongRunningReqHandledGradefully,
773 | verifyDevServerCrashHandledGracefully,
774 | }
775 |
776 | // Tests that require more control hence don't use the built in go http.client
777 | manualClientSimulationTests := []func(t *testing.T, tunnelUrl string, wg *sync.WaitGroup){
778 | // Perform Invalid HTTP requests to test durability of mmar
779 | verifyInvalidHeadersRequestHandled,
780 | verifyInvalidHttpVersionRequestHandled,
781 | verifyInvalidContentLengthRequestHandled,
782 | verifyMismatchedContentLengthRequestHandled,
783 | verifyContentLengthWithNoBodyRequestHandled,
784 | }
785 |
786 | for _, simTest := range simulationTests {
787 | wg.Add(1)
788 | go simTest(t, client, tunnelUrl, &wg)
789 | }
790 |
791 | for _, manualClientSimTest := range manualClientSimulationTests {
792 | wg.Add(1)
793 | go manualClientSimTest(t, tunnelUrl, &wg)
794 | }
795 |
796 | wg.Wait()
797 |
798 | // Stop simulation tests
799 | simulationCancel()
800 |
801 | wait.Reset(6 * time.Second)
802 | <-wait.C
803 | }
804 |
--------------------------------------------------------------------------------
/simulations/simulation_utils.go:
--------------------------------------------------------------------------------
1 | package simulations
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "context"
7 | "encoding/json"
8 | "errors"
9 | "fmt"
10 | "io"
11 | "log"
12 | "net"
13 | "net/http"
14 | "regexp"
15 | "slices"
16 | "testing"
17 |
18 | "github.com/yusuf-musleh/mmar/simulations/dnsserver"
19 | )
20 |
21 | type receivedRequest struct {
22 | headers map[string]string
23 | body map[string]interface{}
24 | }
25 |
26 | type expectedResponse struct {
27 | statusCode int
28 | headers map[string]string
29 | jsonBody map[string]interface{}
30 | textBody string
31 | }
32 |
33 | func validateRequestResponse(t *testing.T, expectedResp expectedResponse, resp *http.Response, testName string) {
34 | // Verify expected status code returned
35 | if resp.StatusCode != expectedResp.statusCode {
36 | t.Errorf("%v: resp.statusCode = %v; want %v", testName, resp.StatusCode, expectedResp.statusCode)
37 | }
38 |
39 | // Verify contains expected headers
40 | for hKey, hVal := range expectedResp.headers {
41 | vals, ok := resp.Header[hKey]
42 | if !ok || slices.Index(vals, hVal) == -1 {
43 | t.Errorf("%v: resp.headers[%v] = %v; want %v", testName, hKey, vals, hVal)
44 | }
45 | }
46 |
47 | // Verify correct body returned
48 | var respBody interface{}
49 | jsonDecoder := json.NewDecoder(resp.Body)
50 | err := jsonDecoder.Decode(&respBody)
51 | if err != nil {
52 | jsonDecoderBuffered := jsonDecoder.Buffered()
53 | nonJsonBody, nonJsonBodyErr := io.ReadAll(jsonDecoderBuffered)
54 | if nonJsonBodyErr != nil {
55 | t.Error("Failed to read response body", err)
56 | return
57 | }
58 |
59 | // Handle case when body is not JSON
60 | if string(nonJsonBody) != string(expectedResp.textBody) {
61 | t.Errorf("%v: body = %v; want %v", testName, string(nonJsonBody), string(expectedResp.textBody))
62 | return
63 | }
64 | }
65 |
66 | // Hanlde case when body is JSON
67 | expectedJson, _ := json.Marshal(expectedResp.jsonBody)
68 | actualJson, _ := json.Marshal(respBody)
69 | if string(actualJson) != string(expectedJson) {
70 | t.Errorf("%v: body = %v; want %v", testName, string(actualJson), string(expectedJson))
71 | }
72 | }
73 |
74 | func extractTunnelURL(clientStdout string) string {
75 | re := regexp.MustCompile(`http:\/\/[a-zA-Z0-9\-]+\.localhost:\d+`)
76 | return re.FindString(clientStdout)
77 | }
78 |
79 | func initCustomDialer() *net.Dialer {
80 | // Adding custom resolver that points to our simulated DNS Server to
81 | // handle subdomain on localhost
82 | r := &net.Resolver{
83 | PreferGo: true,
84 | Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
85 | return net.Dial("udp", dnsserver.LOCALHOST_DNS_SERVER)
86 | },
87 | }
88 | dial := &net.Dialer{
89 | Resolver: r,
90 | }
91 | return dial
92 | }
93 |
94 | func httpClient() *http.Client {
95 | dialer := initCustomDialer()
96 |
97 | tp := &http.Transport{
98 | DialContext: dialer.DialContext,
99 | }
100 | client := &http.Client{Transport: tp}
101 | return client
102 | }
103 |
104 | // This is used when we want more control over creating HTTP requests
105 | // mainly allowing us to create invalid ones
106 | func manualHttpRequest(url string, rawHttpReq string) net.Conn {
107 | dialer := initCustomDialer()
108 |
109 | conn, err := dialer.Dial("tcp", url)
110 | if err != nil {
111 | log.Fatal("Failed to connect to server", err)
112 | }
113 |
114 | _, writeErr := fmt.Fprint(conn, rawHttpReq)
115 | if writeErr != nil {
116 | log.Fatal("Failed to write to connection", writeErr)
117 | }
118 |
119 | return conn
120 | }
121 |
122 | // This is used when reading responses of manually performed HTTP requests
123 | func manualReadResponse(conn net.Conn) (*http.Response, error) {
124 | defer conn.Close()
125 | bufferSize := 2048
126 | buf := make([]byte, bufferSize)
127 | respBytes := []byte{}
128 |
129 | // Keep reading response until completely read
130 | for {
131 | r, readErr := conn.Read(buf)
132 | if readErr != nil {
133 | if errors.Is(readErr, io.EOF) {
134 | respBytes = append(respBytes, buf[:r]...)
135 | break
136 | }
137 | return nil, readErr
138 | }
139 | respBytes = append(respBytes, buf[:r]...)
140 | if r < bufferSize {
141 | break
142 | }
143 | }
144 |
145 | // Convert response bytes to http.Response
146 | respBuff := bytes.NewBuffer(respBytes)
147 | reader := bufio.NewReader(respBuff)
148 | resp, respErr := http.ReadResponse(reader, nil)
149 | if respErr != nil {
150 | log.Fatal("failed to parse response", respErr)
151 | }
152 |
153 | return resp, nil
154 | }
155 |
--------------------------------------------------------------------------------