├── .gitignore
├── .goreleaser.yml
├── LICENSE
├── README.md
├── client
└── flyclient.go
├── cmd
├── client
│ └── client.go
└── server
│ └── server.go
├── fly
├── buf_pipe.go
├── cipher.go
├── cipher_test.go
├── conn.go
├── error_utils.go
├── http.go
├── logs.go
├── net_utils.go
├── pac.go
├── pac_test.go
├── portforward.go
├── relay.go
└── socks5.go
├── flynet.conf
├── go.mod
├── go.sum
└── server
└── flyserver.go
/.gitignore:
--------------------------------------------------------------------------------
1 | /.idea
2 | /dist
3 | /test.go
4 | /flynet.pac
5 | /cmd/client/client.exe
6 | /cmd/client/client
7 | /cmd/client/client_linux_amd64
8 | /cmd/client/auto-build.bat
9 | /cmd/server/server.exe
10 | /cmd/server/server
11 | /cmd/server/server_flynet
12 | /cmd/server/auto-build.bat
13 |
14 | /cmd/server/build.sh
15 |
16 | /.DS_Store
--------------------------------------------------------------------------------
/.goreleaser.yml:
--------------------------------------------------------------------------------
1 |
2 | builds:
3 | -
4 | binary: client-flynet
5 | id: client-flynet
6 | main: ./cmd/client/client.go
7 | goos:
8 | - windows
9 | - darwin
10 | - linux
11 | - freebsd
12 | goarch:
13 | - amd64
14 | - 386
15 | - arm
16 | - mipsle
17 | -
18 | binary: server-flynet
19 | id: server-flynet
20 | main: ./cmd/server/server.go
21 | goos:
22 | - windows
23 | - darwin
24 | - linux
25 | - freebsd
26 | goarch:
27 | - amd64
28 | - 386
29 | - arm
30 | - mipsle
31 |
32 | archives:
33 | -
34 | files:
35 | - flynet.conf
36 | - README.md
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # flynet
2 | [![release][1]][4] [![size][2]][5] [![License][3]][6]
3 |
4 | [1]: https://img.shields.io/github/v/release/asche910/flynet
5 | [2]: https://img.shields.io/github/repo-size/asche910/flynet
6 | [3]: https://img.shields.io/github/license/asche910/flynet
7 | [4]: https://github.com/asche910/flynet/releases
8 | [5]: https://github.com/asche910/flynet
9 | [6]: https://github.com/asche910/flynet/blob/master/LICENSE
10 |
11 |
12 |
13 | ## Features
14 | [flynet](https://github.com/asche910/flynet) Is a command-line tool written in Golang language, currently supported features include:
15 |
16 | * [Http proxy](#Http-Proxy)
17 | * [Local Socks5 proxy](#Local-Socks5-Proxy)
18 | * [C/S mode of Socks5 proxy by TCP](#CS-mode-of-Socks5-proxy-by-TCP)
19 | * [C/S mode of Socks5 proxy by UDP](#CS-mode-of-Socks5-proxy-by-UDP)
20 | * [NAT traversal](#NAT-traversal)
21 | * ...
22 |
23 | The project is currently divided into the client and the sever. The http and local socks5 proxy, both sides of flynet support. The other functions need to be used at both sides.
24 |
25 | ## Getting Started
26 | ### Installing
27 | There are two ways to install
28 |
29 | ##### Download from [Releases Page](https://github.com/asche910/flynet/releases)
30 | Go to the [Releases Page](https://github.com/asche910/flynet/releases), download the corresponding version
31 |
32 |
33 | ##### Build from source
34 |
35 | ```shell
36 | go get -u -v github.com/asche910/flynet
37 | ```
38 | In windows system,```.\client.exe ...```or ```.\server.exe ...```
39 |
40 | and linux system, ```./server ...``` or ```./client ...```
41 |
42 | will show like this ```server ...``` or ```client ...``` in the following article
43 |
44 | after run this command, it should output some messages like this:
45 | ```
46 | Usage: flynet [options]
47 | -M, --mode choose which mode to run. the mode must be one of['http', 'socks5',
48 | 'socks5-tcp', 'socks5-udp', 'forward']
49 | -L, --listen choose which port(s) to listen or forward
50 | -S, --server the server address client connect to
51 | -m, --method choose a encrypt method, which must be one of ['aes-128-cfb','aes-192-cfb',
52 | 'aes-256-cfb', 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'rc4-md5',
53 | 'rc4-md5-6', 'chacha20', 'chacha20-ietf'], default is 'aes-256-cfb'
54 | -P, --password password of server
55 | -p, --pac having this flag, pac-mode will open
56 | -C, --config read from config file
57 | -V, --verbose output detail info
58 | -l, --log output detail info to log file
59 | -H, --help show detail usage
60 |
61 | Mail bug reports and suggestions to
62 | or github: https://github.com/asche910/flynet
63 | ```
64 |
65 | ### Http Proxy
66 |
67 | The http proxy directly opens the Http proxy on this machine. Both the client and the server support it. The commands are as follows:
68 |
69 | ```
70 | server -M http -L 8848
71 | ```
72 | or
73 | ```
74 | client -M http -L 8848
75 | ```
76 | It means that the Http proxy service is enabled on the port of 8848. If there is no output, it means the startup is successful. After all, one of philosophies of linux is:
77 |
78 | > No news is good news
79 |
80 | Of course, if you still want to see some messages, you could run this command with options, like ```-V``` or ```--verbose```, which will output detail message to the terminal.
81 | and the option ```-l``` or ```--log```will write message to the file named 'flynet.log'. of course you can also indicate the file name after the option
82 |
83 | ### Local Socks5 Proxy
84 |
85 | It is very simple to start the socks5 proxy on this machine. Both the client and the server support it. The commands are as follows:
86 |
87 | ```
88 | server -M socks5 -L 1080
89 | ```
90 | or
91 | ```
92 | client -M socks5 -L 1080
93 | ```
94 | This means that the socks5 proxy is enabled on the port 1080 of the machine, and then Chrome can work well with **Switchy Omega**.
95 |
96 | ### C/S mode of Socks5 proxy by TCP
97 |
98 | The previous one is the socks5 agent on the local, this one is the socks5 proxy that the client and the server cooperate with each other, and the middle is transmitted by the **TCP** protocol.
99 | The usage is as follows:
100 |
101 | **Server**
102 | ```
103 | server -M socks5-tcp -L 8888
104 | ```
105 | **Client**
106 | ```
107 | client -M socks5-tcp -L 1080 -S example.com:8888
108 | ```
109 |
110 |
111 | The example here is to assume that my server domain name is example.com ( you can also use ip directly:`-S xxx.xxx.xxx.xxx:8888`), then the client starts the socks5 proxy on port 1080,
112 | and then the traffic is forwarded to the server's 8888 port by TCP, and the server requests the corresponding target website. Return the result of the request to the client.
113 | The intermediate traffic is encrypted (default method is "aes-256-cfb") to ensure the security of the transmission.
114 | If you want, you can add more options, like
115 | * ```-P password``` add a password as the key for encryption or decryption
116 | * ```-m method``` use different encrypt method to encrypt your traffic
117 | * ```-p``` adding this on client side will start **PAC** mode. but you should setting the url as System auto proxy url manually
118 |
119 | If you feel that it is too much trouble to enter a bunch of parameters every time,you can just use ```-C flynet.cnnf``` to load a config file in your current directory
120 |
121 | ### C/S mode of Socks5 proxy by UDP
122 |
123 | This is very similar to the above tcp. The difference is that this is sending and receiving all packets through kcp (UDP) not TCP.
124 | After all, UDP has its own advantages in some aspects, and some important protocols mainly use udp transmission, such as the DNS protocol.
125 | One of uses is that you can have free internet access **without authentication** when using **campus-wifi** or **public-wifi**.
126 | Here's a look at the specific usage:
127 |
128 | **Server**
129 | ```
130 | server -M socks5-udp -L 53
131 | ```
132 | **Client**
133 | ```
134 | client -M socks5-udp -L 8848 -S example.com:53
135 | ```
136 |
137 | Here also take the domain name example.com and port 53 as examples.The client opens the socks5 proxy on udp port 53, and then all traffic
138 | is transmitted to the server port 53 through the udp mode. After receiving the request, the server then requests all requests.
139 | Send to the target website and return the results to the client in udp mode. The same is that all traffic is encrypted.
140 |
141 | ### NAT traversal
142 |
143 | > Network address translator traversal is a computer networking technique of establishing and maintaining Internet protocol connections across gateways that implement network address translation (NAT).
144 |
145 | To put it simply, the external network can access the machines in the internal network. What the tool does here is to map a port
146 | on the intranet to a port on the server, so that by accessing a port on the server, you can indirectly access the port in the intranet.
147 | Methods as below:
148 |
149 | **Server**
150 | ```
151 | server -M forward -L 8888 8080
152 | ```
153 | **Client**
154 | ```
155 | server -M forward -L 80 -S example.com:8888
156 | ```
157 |
158 | Also assume that the server domain name is example.com. The goal is mapping the port 80 of the client to the server port 8080. the middle of the data transmission is done through the server listening 8888.
159 | Then we visit example.com:8080 could see the content on the client port 80.
160 |
161 | ## Conclusion
162 |
163 | The current function of the project is relatively limited, and more functions should be added in the future.
164 | If the project is useful to you, a **star** is best favour for me!
165 |
--------------------------------------------------------------------------------
/client/flyclient.go:
--------------------------------------------------------------------------------
1 | package client
2 |
3 | import "github.com/asche910/flynet/fly"
4 |
5 | type FlyClient struct {
6 | Mode int
7 | //localhost string
8 | Ports []string // ports[0] stands for the listening port; others are for reserve
9 | Method string
10 | Password string
11 | //protocol string // tcp or udp protocol
12 | ServerAddr string
13 | PACMode bool
14 | }
15 |
16 | func (client *FlyClient) LocalSocks5Proxy(port string) {
17 | fly.StartSocks5(port)
18 | }
19 |
20 | func (client *FlyClient) LocalHttpProxy(port string) {
21 | fly.StartHttp(port)
22 | }
23 |
24 | func (client *FlyClient) Socks5ProxyForTCP(localPort, serverAddr, method, key string, pacMode bool) {
25 | fly.Socks5ForClientByTCP(localPort, serverAddr, method, key, pacMode)
26 | }
27 |
28 | func (client *FlyClient) Socks5ProxyForUDP(localPort, serverAddr string) {
29 | fly.Socks5ForClientByUDP(localPort, serverAddr)
30 | }
31 |
32 | func (client *FlyClient) PortForward(laborPort, serverAddr string) {
33 | fly.PortForwardForClient(laborPort, serverAddr)
34 | }
35 |
--------------------------------------------------------------------------------
/cmd/client/client.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "github.com/asche910/flynet/client"
6 | "github.com/asche910/flynet/fly"
7 | "gopkg.in/ini.v1"
8 | "os"
9 | "strings"
10 | )
11 |
12 | var (
13 | flyClient = client.FlyClient{}
14 | ModeMap = map[int]string{1: "http", 2: "socks5", 3: "socks5-tcp", 4: "socks5-udp", 5: "forward"}
15 | )
16 |
17 | func main() {
18 | if len(os.Args) < 2 {
19 | printHelp()
20 | return
21 | }
22 | parseArgs(os.Args[1:])
23 | checkArgs()
24 | initLog()
25 |
26 | switch flyClient.Mode {
27 | case 1:
28 | flyClient.LocalHttpProxy(flyClient.Ports[0])
29 | case 2:
30 | flyClient.LocalSocks5Proxy(flyClient.Ports[0])
31 | case 3:
32 | flyClient.Socks5ProxyForTCP(flyClient.Ports[0], flyClient.ServerAddr, flyClient.Method, flyClient.Password, flyClient.PACMode)
33 | case 4:
34 | flyClient.Socks5ProxyForUDP(flyClient.Ports[0], flyClient.ServerAddr)
35 | case 5:
36 | ports := flyClient.Ports
37 | flyClient.PortForward(ports[0], flyClient.ServerAddr)
38 | default:
39 | fmt.Println("flynet: unknown error!")
40 | os.Exit(1)
41 | }
42 | }
43 |
44 | func printHelp() {
45 | fmt.Println(`Usage: flynet [options]
46 | -M, --mode choose which mode to run. the mode must be one of['http', 'socks5',
47 | 'socks5-tcp', 'socks5-udp', 'forward']
48 | -L, --listen choose which port(s) to listen or forward
49 | -S, --server the server address client connect to
50 | -m, --method choose a encrypt method, which must be one of ['aes-128-cfb','aes-192-cfb',
51 | 'aes-256-cfb', 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'rc4-md5',
52 | 'rc4-md5-6', 'chacha20', 'chacha20-ietf'], default is 'aes-256-cfb'
53 | -P, --password password of server
54 | -p, --pac having this flag, pac-mode will open
55 | -C, --config read from config file
56 | -V, --verbose output detail info
57 | -l, --log output detail info to log file, which if not indicated "flynet.log" will
58 | be default
59 | -H, --help show detail usage
60 |
61 | Mail bug reports and suggestions to
62 | or github: https://github.com/asche910/flynet`)
63 | }
64 |
65 | func parseArgs(args []string) {
66 | if len(args) < 1 {
67 | return
68 | }
69 | switch args[0] {
70 | case "--mode", "-M":
71 | if len(args) > 1 {
72 | switch args[1] {
73 | case ModeMap[1]:
74 | flyClient.Mode = 1
75 | case ModeMap[2], "socks":
76 | flyClient.Mode = 2
77 | case ModeMap[3], "socks-tcp":
78 | flyClient.Mode = 3
79 | case ModeMap[4], "socks-udp":
80 | flyClient.Mode = 4
81 | case ModeMap[5]:
82 | flyClient.Mode = 5
83 | default:
84 | fmt.Println("flynet: no correct mode found!")
85 | printHelp()
86 | os.Exit(1)
87 | }
88 | parseArgs(args[2:])
89 | } else {
90 | fmt.Println("flynet: no detail mode found!")
91 | printHelp()
92 | os.Exit(1)
93 | }
94 | case "--listen", "-L":
95 | if hasNAttributes(args, 1) {
96 | fly.CheckPort(args[1])
97 | if hasNAttributes(args, 2) {
98 | fly.CheckPort(args[2])
99 | flyClient.Ports = []string{args[1], args[2]}
100 | parseArgs(args[3:])
101 | } else {
102 | flyClient.Ports = []string{args[1]}
103 | parseArgs(args[2:])
104 | }
105 | } else {
106 | fmt.Println("flynet: no port found!")
107 | printHelp()
108 | os.Exit(1)
109 | }
110 | case "--server", "-S":
111 | if hasNAttributes(args, 1) {
112 | flyClient.ServerAddr = args[1]
113 | parseArgs(args[2:])
114 | } else {
115 | fmt.Println("flynet: no correct serverAddr found!")
116 | printHelp()
117 | os.Exit(1)
118 | }
119 | case "--method", "-m":
120 | if hasNAttributes(args, 1) {
121 | flyClient.Method = args[1]
122 | parseArgs(args[2:])
123 | } else {
124 | fmt.Println("flynet: no password found!")
125 | printHelp()
126 | os.Exit(1)
127 | }
128 | case "--password", "-P":
129 | if hasNAttributes(args, 1) {
130 | flyClient.Password = args[1]
131 | parseArgs(args[2:])
132 | } else {
133 | fmt.Println("flynet: no password found!")
134 | printHelp()
135 | os.Exit(1)
136 | }
137 | case "--pac", "-p":
138 | flyClient.PACMode = true
139 | parseArgs(args[1:])
140 | case "--config", "-C":
141 | if hasNAttributes(args, 1) {
142 | readConfig(args[1])
143 | } else {
144 | fmt.Println("flynet: no config file found!")
145 | printHelp()
146 | os.Exit(1)
147 | }
148 | case "--verbose", "-V":
149 | fly.EnableDebug(true)
150 | parseArgs(args[1:])
151 | case "--logs", "-l":
152 | if len(args) > 1 && !strings.HasPrefix(args[1], "-") {
153 | fly.SetLogName(args[1])
154 | }
155 | fly.EnableLog(true)
156 | parseArgs(args[1:])
157 | case "--help", "-H":
158 | printHelp()
159 | parseArgs(args[1:])
160 | os.Exit(0)
161 | default:
162 | fmt.Println("flynet: please input correct command!")
163 | printHelp()
164 | os.Exit(1)
165 | }
166 | }
167 |
168 | // judge if the current args option has n attributes at least.
169 | // for example:
170 | // args = []string{"--listen", "1080", "8888"}
171 | // hasNAttributes(args, 2) will return true
172 | func hasNAttributes(args []string, n int) bool {
173 | if len(args) > n {
174 | for i := 1; i <= n; i++ {
175 | if strings.HasPrefix(args[i], "-") {
176 | return false
177 | }
178 | }
179 | return true
180 | }
181 | return false
182 | }
183 |
184 | func checkArgs() {
185 | mode := flyClient.Mode
186 | if mode == 0 {
187 | fmt.Println("Please choose a mode!")
188 | printHelp()
189 | os.Exit(1)
190 | } else if mode == 3 || mode == 4 || mode == 5 {
191 | if flyClient.ServerAddr == "" {
192 | fmt.Println("flynet: please input serverAddr!")
193 | printHelp()
194 | os.Exit(1)
195 | }
196 | }
197 |
198 | if len(flyClient.Ports) != 1 {
199 | fmt.Println("flynet: please choose a port!")
200 | printHelp()
201 | os.Exit(1)
202 | }
203 | }
204 |
205 | // load config file
206 | func readConfig(path string) {
207 | conf, err := ini.Load(path)
208 | if err != nil {
209 | fmt.Println("load config file fail --->", err)
210 | fmt.Println("you could refer to the example config file: https://github.com/asche910/flynet")
211 | os.Exit(1)
212 | }
213 | section, err := conf.NewSection("client")
214 | if err != nil {
215 | fmt.Println("read client tag failed --->", err)
216 | }
217 | mode := getAttr(section, "mode")
218 | port := getAttr(section, "port")
219 | serverAddr := getAttr(section, "serverAddr")
220 | method := getAttr(section, "method")
221 | password := getAttr(section, "password")
222 | pacOn := getAttr(section, "pac-mode")
223 | verbose := getAttr(section, "verbose")
224 | logs := getAttr(section, "log")
225 |
226 | switch mode {
227 | case ModeMap[1]:
228 | flyClient.Mode = 1
229 | case ModeMap[2], "socks":
230 | flyClient.Mode = 2
231 | case ModeMap[3], "socks-tcp":
232 | flyClient.Mode = 3
233 | case ModeMap[4], "socks-udp":
234 | flyClient.Mode = 4
235 | case ModeMap[5]:
236 | flyClient.Mode = 5
237 | default:
238 | fmt.Println("flynet: no correct mode found!")
239 | printHelp()
240 | os.Exit(1)
241 | }
242 |
243 | fly.CheckPort(port)
244 | flyClient.Ports = []string{port}
245 | flyClient.ServerAddr = serverAddr
246 | flyClient.Method = method
247 | flyClient.Password = password
248 |
249 | if pacOn == "true" {
250 | flyClient.PACMode = true
251 | }
252 |
253 | if verbose == "true" {
254 | fly.EnableDebug(true)
255 | }
256 |
257 | if logs != "" {
258 | fly.SetLogName(logs)
259 | fly.EnableLog(true)
260 | }
261 | }
262 |
263 | // read attr from config file
264 | func getAttr(section *ini.Section, name string) string {
265 | key, e := section.GetKey(name)
266 | if e != nil {
267 | return ""
268 | }
269 | return key.String()
270 | }
271 |
272 | func initLog() {
273 | fly.InitLog()
274 | }
275 |
--------------------------------------------------------------------------------
/cmd/server/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "github.com/asche910/flynet/fly"
6 | "github.com/asche910/flynet/server"
7 | "gopkg.in/ini.v1"
8 | "os"
9 | "strings"
10 | )
11 |
12 | var (
13 | flyServer = server.FlyServer{}
14 | ModeMap = map[int]string{1: "http", 2: "socks5", 3: "socks5-tcp", 4: "socks5-udp", 5: "forward"}
15 | )
16 |
17 | func main() {
18 | if len(os.Args) < 2 {
19 | printHelp()
20 | return
21 | }
22 | parseArgs(os.Args[1:])
23 | checkArgs()
24 | initLog()
25 |
26 | switch flyServer.Mode {
27 | case 1:
28 | flyServer.LocalHttpProxy(flyServer.Ports[0])
29 | case 2:
30 | flyServer.LocalSocks5Proxy(flyServer.Ports[0])
31 | case 3:
32 | flyServer.Socks5ProxyForTCP(flyServer.Ports[0], flyServer.Method, flyServer.Password)
33 | case 4:
34 | flyServer.Socks5ProxyForUDP(flyServer.Ports[0])
35 | case 5:
36 | ports := flyServer.Ports
37 | flyServer.PortForward(ports[0], ports[1])
38 | default:
39 | fmt.Println("flynet: unknown error!")
40 | os.Exit(1)
41 | }
42 | }
43 |
44 | func printHelp() {
45 | fmt.Println(`Usage: flynet [options]
46 | -M, --mode choose which mode to run. the mode must be one of['http', 'socks5',
47 | 'socks5-tcp', 'socks5-udp', 'forward']
48 | -L, --listen choose which port(s) to listen or forward
49 | -m, --method choose a encrypt method, which must be one of ['aes-128-cfb','aes-192-cfb',
50 | 'aes-256-cfb', 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'rc4-md5',
51 | 'rc4-md5-6', 'chacha20', 'chacha20-ietf'], default is 'aes-256-cfb'
52 | -P, --password password for client to connect
53 | -C, --config read from config file
54 | -V, --verbose output detail info
55 | -l, --log output detail info to log file, which if not indicated "flynet.log" will
56 | be default
57 | -H, --help show detail usage
58 |
59 | Mail bug reports and suggestions to
60 | or github: https://github.com/asche910/flynet`)
61 | }
62 |
63 | func parseArgs(args []string) {
64 | if len(args) < 1 {
65 | return
66 | }
67 | switch args[0] {
68 | case "--mode", "-M":
69 | if len(args) > 1 {
70 | switch args[1] {
71 | case ModeMap[1]:
72 | flyServer.Mode = 1
73 | case ModeMap[2], "socks":
74 | flyServer.Mode = 2
75 | case ModeMap[3], "socks-tcp":
76 | flyServer.Mode = 3
77 | case ModeMap[4], "socks-udp":
78 | flyServer.Mode = 4
79 | case ModeMap[5]:
80 | flyServer.Mode = 5
81 | default:
82 | fmt.Println("flynet: no correct mode found!")
83 | printHelp()
84 | os.Exit(1)
85 | }
86 | parseArgs(args[2:])
87 | } else {
88 | fmt.Println("flynet: no detail mode found!")
89 | printHelp()
90 | os.Exit(1)
91 | }
92 | case "--listen", "-L":
93 | if hasNAttributes(args, 1) {
94 | fly.CheckPort(args[1])
95 | if hasNAttributes(args, 2) {
96 | fly.CheckPort(args[2])
97 | flyServer.Ports = []string{args[1], args[2]}
98 | parseArgs(args[3:])
99 | } else {
100 | flyServer.Ports = []string{args[1]}
101 | parseArgs(args[2:])
102 | }
103 | } else {
104 | fmt.Println("flynet: no port found!")
105 | printHelp()
106 | os.Exit(1)
107 | }
108 | case "-m", "--method":
109 | if hasNAttributes(args, 1) {
110 | flyServer.Method = args[1]
111 | parseArgs(args[2:])
112 | } else {
113 | fmt.Println("fly: no password found!")
114 | printHelp()
115 | os.Exit(1)
116 | }
117 | case "--password", "-P":
118 | if hasNAttributes(args, 1) {
119 | flyServer.Password = args[1]
120 | parseArgs(args[2:])
121 | } else {
122 | fmt.Println("flynet: no password found!")
123 | printHelp()
124 | os.Exit(1)
125 | }
126 | case "--config", "-C":
127 | if hasNAttributes(args, 1) {
128 | readConfig(args[1])
129 | } else {
130 | fmt.Println("flynet: no config file found!")
131 | printHelp()
132 | os.Exit(1)
133 | }
134 | case "--verbose", "-V":
135 | fly.EnableDebug(true)
136 | parseArgs(args[1:])
137 | case "--logs", "-l":
138 | if hasNAttributes(args, 1) {
139 | fly.SetLogName(args[1])
140 | }
141 | fly.EnableLog(true)
142 | parseArgs(args[1:])
143 | case "--help", "-H":
144 | printHelp()
145 | parseArgs(args[1:])
146 | os.Exit(0)
147 | default:
148 | fmt.Println("flynet: please input correct command!")
149 | printHelp()
150 | os.Exit(1)
151 | }
152 | }
153 |
154 | // judge if the current args option has n attributes at least.
155 | // for example:
156 | // args = []string{"--listen", "1080", "8888"}
157 | // hasNAttributes(args, 2) will return true
158 | func hasNAttributes(args []string, n int) bool {
159 | if len(args) > n {
160 | for i := 1; i <= n; i++ {
161 | if strings.HasPrefix(args[i], "-") {
162 | return false
163 | }
164 | }
165 | return true
166 | }
167 | return false
168 | }
169 |
170 | func checkArgs() {
171 | if flyServer.Mode == 0 {
172 | fmt.Println("Please choose a mode!")
173 | printHelp()
174 | os.Exit(1)
175 | } else if flyServer.Mode == 5 {
176 | if len(flyServer.Ports) != 2 {
177 | fmt.Println("flynet: please input two port!")
178 | printHelp()
179 | os.Exit(1)
180 | }
181 | } else {
182 | if len(flyServer.Ports) != 1 {
183 | fmt.Println("flynet: please choose a port to listen!")
184 | printHelp()
185 | os.Exit(1)
186 | }
187 | }
188 | }
189 |
190 | // load config file
191 | func readConfig(path string) {
192 | conf, err := ini.Load(path)
193 | if err != nil {
194 | fmt.Println("load config file fail --->", err)
195 | fmt.Println("you could refer to the example config file: https://github.com/asche910/flynet")
196 | os.Exit(1)
197 | }
198 | section, err := conf.NewSection("server")
199 | if err != nil {
200 | fmt.Println("read client tag failed --->", err)
201 | }
202 | mode := getAttr(section, "mode")
203 | portStr := getAttr(section, "port")
204 | method := getAttr(section, "method")
205 | password := getAttr(section, "password")
206 | verbose := getAttr(section, "verbose")
207 | logs := getAttr(section, "log")
208 |
209 | switch mode {
210 | case ModeMap[1]:
211 | flyServer.Mode = 1
212 | case ModeMap[2], "socks":
213 | flyServer.Mode = 2
214 | case ModeMap[3], "socks-tcp":
215 | flyServer.Mode = 3
216 | case ModeMap[4], "socks-udp":
217 | flyServer.Mode = 4
218 | case ModeMap[5]:
219 | flyServer.Mode = 5
220 | default:
221 | fmt.Println("flynet: no correct mode found!")
222 | printHelp()
223 | os.Exit(1)
224 | }
225 |
226 | // in case of forward mode, which needs two port
227 | ports := strings.Fields(portStr)
228 | if len(ports) == 2 {
229 | fly.CheckPort(ports[0])
230 | fly.CheckPort(ports[1])
231 | flyServer.Ports = []string{ports[0], ports[1]}
232 | }else if len(ports) == 1 {
233 | fly.CheckPort(ports[0])
234 | flyServer.Ports = []string{ports[0]}
235 | }
236 | flyServer.Method = method
237 | flyServer.Password = password
238 |
239 | if verbose == "true" {
240 | fly.EnableDebug(true)
241 | }
242 |
243 | if logs != "" {
244 | fly.SetLogName(logs)
245 | fly.EnableLog(true)
246 | }
247 | }
248 |
249 | // read attr from config file
250 | func getAttr(section *ini.Section, name string) string {
251 | key, e := section.GetKey(name)
252 | if e != nil {
253 | return ""
254 | }
255 | return key.String()
256 | }
257 |
258 | func initLog() {
259 | fly.InitLog()
260 | }
261 |
--------------------------------------------------------------------------------
/fly/buf_pipe.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import "sync"
4 |
5 | type BufferedPipe struct {
6 | mu sync.Mutex
7 | cond *sync.Cond
8 | buf []byte
9 | start int
10 | size int
11 | }
12 |
13 | func NewBufferedPipe(size int) *BufferedPipe {
14 | p := &BufferedPipe{
15 | buf: make([]byte, size),
16 | start: 0,
17 | size: 0,
18 | }
19 | p.cond = sync.NewCond(&p.mu)
20 | return p
21 | }
22 |
23 | func (p *BufferedPipe) Write(b []byte) (int, error) {
24 | p.mu.Lock()
25 | defer p.mu.Unlock()
26 | for p.start+p.size+len(b) > cap(p.buf) {
27 | logger.Printf("Write pipe wait --- > start:%d, size:%d, len(b):%d, cap(buf):%d \n", p.start, p.size, len(b), cap(p.buf))
28 | p.cond.Wait()
29 | }
30 | //p.buf = append(p.buf, b...)
31 | copy(p.buf[p.start+p.size:p.start+p.size+len(b)], b)
32 | p.size += len(b)
33 | p.cond.Broadcast()
34 | return len(b), nil
35 | }
36 |
37 | func (p *BufferedPipe) Read(b []byte) (readSize int, err error) {
38 | p.mu.Lock()
39 | defer p.mu.Unlock()
40 | for p.size == 0 {
41 | p.cond.Wait()
42 | }
43 | if len(b) >= p.size {
44 | copy(b[0:p.size], p.buf[p.start:p.start+p.size])
45 | readSize = p.size
46 | p.start = 0
47 | p.size = 0
48 | } else {
49 | copy(b, p.buf[p.start:p.start+len(b)])
50 | readSize = len(b)
51 | p.start += readSize
52 | p.size -= readSize
53 | if p.start+p.size > cap(p.buf)/2 {
54 | newBuf := make([]byte, cap(p.buf))
55 | copy(newBuf[0:p.size], p.buf[p.start:p.start+p.size])
56 | p.buf = newBuf
57 | p.start = 0
58 | }
59 | }
60 |
61 | //n := copy(b, p.buf)
62 | //p.buf = p.buf[n:]
63 | p.cond.Broadcast()
64 | //return n, nil
65 | return
66 | }
67 |
68 | func (p *BufferedPipe) Size() int {
69 | return p.size
70 | }
71 |
--------------------------------------------------------------------------------
/fly/cipher.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "crypto/md5"
7 | "crypto/rc4"
8 | "fmt"
9 |
10 | "github.com/aead/chacha20"
11 | )
12 |
13 | var key = "asche910-flynet-"
14 |
15 | type EncOrDec int
16 |
17 | const (
18 | ENC EncOrDec = iota
19 | DEC
20 | )
21 |
22 | var (
23 | IV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}
24 | )
25 |
26 | var CipherMap = map[string]*cipherEntity{
27 | "aes-128-cfb": {16, 16, newAESCFBStream},
28 | "aes-192-cfb": {24, 16, newAESCFBStream},
29 | "aes-256-cfb": {32, 16, newAESCFBStream},
30 | "aes-128-ctr": {16, 16, newAESCTRStream},
31 | "aes-192-ctr": {24, 16, newAESCTRStream},
32 | "aes-256-ctr": {32, 16, newAESCTRStream},
33 | "rc4-md5": {16, 16, newRC4MD5Stream},
34 | "rc4-md5-6": {16, 6, newRC4MD5Stream},
35 | "chacha20": {32, 8, newChaCha20Stream},
36 | "chacha20-ietf": {32, 12, newChaCha20Stream},
37 | }
38 |
39 | // generate a fixed length key
40 | func genKey(rawKey string, len int) []byte {
41 | key := make([]byte, 256)
42 | cur := 0
43 | for cur < len {
44 | sum := md5.Sum([]byte(fmt.Sprintf("%s%d", rawKey, cur)))
45 | copy(key[cur:cur+16], sum[:])
46 | cur += 16
47 | }
48 | return key[:len]
49 | }
50 |
51 | type Cipher struct {
52 | encoder cipher.Stream
53 | decoder cipher.Stream
54 | key []byte
55 | method string
56 | }
57 |
58 | func (cipher *Cipher) Encrypt(dst, src []byte) {
59 | cipher.encoder.XORKeyStream(dst, src)
60 | }
61 |
62 | func (cipher *Cipher) EncryptAndGet(src []byte) (dst []byte) {
63 | dst = make([]byte, len(src))
64 | cipher.encoder.XORKeyStream(dst, src)
65 | return
66 | }
67 |
68 | func (cipher *Cipher) Decrypt(dst, src []byte) {
69 | cipher.decoder.XORKeyStream(dst, src)
70 | }
71 |
72 | func (cipher *Cipher) DecryptAndGet(src []byte) (dst []byte) {
73 | dst = make([]byte, len(src))
74 | cipher.decoder.XORKeyStream(dst, src)
75 | return
76 | }
77 |
78 | // a detail encrypt or decrypt method
79 | type cipherEntity struct {
80 | keyLen int
81 | ivLen int
82 | newStream func(key, iv []byte, eod EncOrDec) cipher.Stream
83 | }
84 |
85 | func NewCipherInstance(secretKey, method string) *Cipher {
86 | if secretKey == "" {
87 | secretKey = key
88 | }
89 | entity := CipherMap[method]
90 | if entity == nil {
91 | entity = CipherMap["aes-256-cfb"]
92 | }
93 |
94 | key := genKey(secretKey, entity.keyLen)
95 | newIV := IV[:entity.ivLen]
96 | enc := entity.newStream(key, newIV, ENC)
97 | dec := entity.newStream(key, newIV, DEC)
98 | return &Cipher{encoder: enc, decoder: dec}
99 | }
100 |
101 | func newAESCFBStream(key, iv []byte, eod EncOrDec) cipher.Stream {
102 | block, err := aes.NewCipher(key)
103 | if err != nil {
104 | logger.Println("aes.NewCipher failed --->", err)
105 | return nil
106 | }
107 | if eod == ENC {
108 | enc := cipher.NewCFBEncrypter(block, IV)
109 | return enc
110 | } else {
111 | dec := cipher.NewCFBDecrypter(block, IV)
112 | return dec
113 | }
114 | }
115 |
116 | func newAESCTRStream(key, iv []byte, eod EncOrDec) cipher.Stream {
117 | block, err := aes.NewCipher(key)
118 | if err != nil {
119 | logger.Println("aes.NewCipher failed --->", err)
120 | return nil
121 | }
122 | return cipher.NewCTR(block, iv)
123 | }
124 |
125 | func newChaCha20Stream(key, iv []byte, eod EncOrDec) cipher.Stream {
126 | stream, err := chacha20.NewCipher(iv, key)
127 | if err != nil {
128 | logger.Println("chacha20.NewCipher failed --->", err)
129 | return nil
130 | }
131 | return stream
132 | }
133 |
134 | func newRC4MD5Stream(key, iv []byte, eod EncOrDec) cipher.Stream {
135 | hs := md5.New()
136 | hs.Write(key)
137 | hs.Write(iv)
138 | rc4key := hs.Sum(nil)
139 | stream, err := rc4.NewCipher(rc4key)
140 | if err != nil {
141 | logger.Println("rc4.NewCipher failed --->", err)
142 | return nil
143 | }
144 | return stream
145 | }
146 |
--------------------------------------------------------------------------------
/fly/cipher_test.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | const text = "hello,world!----++++++"
9 | const text2 = "hello,world!worldworlds sdf sfj sa sfjslabb\n sfbzcvbxqeuqyuiyajhlfjdbz,v sf"
10 |
11 | func testCipher(t *testing.T, method string) {
12 | cipherInstance := NewCipherInstance(key, method)
13 | testSingleMethod(cipherInstance, text)
14 | testSingleMethod(cipherInstance, text2)
15 | testSingleMethod(cipherInstance, "safhj; sfafajksfb")
16 | testSingleMethod(cipherInstance, "\ttextLen := len(text)\n\ttextLen := len(text)\n\ttext"+
17 | "Len := len(text)\n\ttextLen :\ttextLen := len(text)\n\ttext"+
18 | "Len := len(text)\n\ttextLen := len(text)\n\ttextLen := len(text)\n\ttextLen"+
19 | "Len := len(text)\n\ttextLen := len(text)\n\ttextLen := len(text)\n\ttextLen"+
20 | "Len := len(text)\n\ttextLen := len(text)\n\ttextLen := len(text)\n\ttextLen"+
21 | " := len(text)\n= len(text)\n\ttextLen := len(tex\ttextLen := len(text)\n"+
22 | "t)\n\ttextLen := len(text)\n")
23 |
24 | testSingleMethod(cipherInstance, "safhj; sfsf sfafajksfb")
25 |
26 | }
27 |
28 | func testSingleMethod(cipher *Cipher, raw string) bool {
29 | textLen := len(raw)
30 | decryptBuff := make([]byte, textLen)
31 | encryptBuff := make([]byte, textLen)
32 | cipher.Encrypt(encryptBuff, []byte(raw))
33 | cipher.Decrypt(decryptBuff, encryptBuff)
34 | if string(decryptBuff) != raw {
35 | fmt.Println("NOT PASS!!! ", string(decryptBuff))
36 | return false
37 | } else {
38 | fmt.Println("PASS")
39 | return true
40 | }
41 | }
42 |
43 | func TestCipher(t *testing.T) {
44 | key := "123456"
45 | keyLen := len(key)
46 | buff := make([]byte, 1024)
47 | cipherInstance := NewCipherInstance(key, "aes-128-cfb")
48 | cipherInstance.encoder.XORKeyStream(buff, []byte(key))
49 | fmt.Println("before", string(buff[:keyLen]))
50 | cipherInstance.decoder.XORKeyStream(buff, buff[:keyLen])
51 | fmt.Println("after", string(buff[:keyLen]))
52 | }
53 |
54 | func TestAESCTR(t *testing.T) {
55 | testCipher(t, "aes-128-ctr")
56 | }
57 |
58 | func TestChacha20(t *testing.T) {
59 | testCipher(t, "chacha20")
60 | //testCipher(t, "chacha20-ietf")
61 | }
62 |
63 | func TestRC4MD5(t *testing.T) {
64 | testCipher(t, "rc4-md5")
65 | //testCipher(t, "rc4-md5-6")
66 | }
67 |
68 | func Test(t *testing.T) {
69 | by := []byte{'h', 'e', 'l', 'l', 'o'}
70 | newBy := by[2:4]
71 | fmt.Println(len(by), cap(by))
72 | fmt.Println(len(newBy), cap(newBy))
73 |
74 | b := make([]byte, 0, 10)
75 | fmt.Println(b)
76 | fmt.Println(len(b), cap(b))
77 | //b[7] = 7
78 | copy(b[3:3+len(by)], by)
79 | fmt.Println(b[0:10])
80 | fmt.Println(len(b), cap(b))
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/fly/conn.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "encoding/binary"
5 | "net"
6 | )
7 |
8 | // DataOffset refer to encrypted Data Package
9 | const DataOffset = 4
10 |
11 | type Conn struct {
12 | Conn net.Conn
13 | Cipher *Cipher
14 | BufPipe *BufferedPipe
15 | //PipeReader *io.PipeReader
16 | //PipeWriter *io.PipeWriter
17 | }
18 |
19 | func NewConn(con net.Conn, cipher *Cipher) *Conn {
20 | //pr, pw := io.Pipe()
21 | return &Conn{
22 | Conn: con,
23 | Cipher: cipher,
24 | //BufPipe: NewBufferedPipe(4096),
25 | BufPipe: NewBufferedPipe(8192),
26 | //PipeReader: pr,
27 | //PipeWriter: pw,
28 | }
29 | }
30 |
31 | // DialWithAddr pipeW dial server and send request addr of client
32 | func DialWithAddr(server, method, key string, addr []byte) *Conn {
33 | conn, err := net.Dial("tcp", server)
34 | if err != nil {
35 | logger.Println("Dial server failed --->", err)
36 | return nil
37 | }
38 | newConn := NewConn(conn, NewCipherInstance(key, method))
39 |
40 | // 2 byte of len + request data
41 | //body := make([]byte, len(addr)+2)
42 | //binary.BigEndian.PutUint16(body[:2], uint16(len(addr)))
43 | //copy(body[2:], addr)
44 | //fmt.Println("body ", body)
45 |
46 | if _, err := newConn.Write(addr); err != nil {
47 | logger.Println("Write addr to server failed --->", err)
48 | return nil
49 | }
50 | return newConn
51 | }
52 |
53 | // Request package
54 | // +----+-----+----------+
55 | // | MG | LEN | DATA |
56 | // +----+-----+----------+
57 | // | 2 | 2 | Variable |
58 | // +----+-----+----------+
59 | // MG: Magic num, 2byte, 0x255,0x255
60 | // LEN: length of DATA
61 | func (conn *Conn) Write(b []byte) (n int, err error) {
62 | dataSize := len(b)
63 | var buff []byte
64 | buff = make([]byte, dataSize+DataOffset)
65 | // Magic Number
66 | buff[0] = 255
67 | buff[1] = 255
68 |
69 | binary.BigEndian.PutUint16(buff[2:4], uint16(dataSize))
70 |
71 | //logger.Println("Before encrypt: ", b[:])
72 | //logger.Println("before", b)
73 | conn.Cipher.Encrypt(buff[DataOffset:], b)
74 | //logger.Println("after", buff)
75 | //logger.Println("After encrypt: ", len(buff))
76 | //n, err = conn.Conn.Write(b)
77 | //logger.Println("Conn write")
78 | n, err = conn.Conn.Write(buff)
79 | //logger.Println("Conn write len", n)
80 |
81 | if err != nil {
82 | logger.Println("Encrypt data write failed", err)
83 | }
84 | if n != len(buff) {
85 | logger.Println("Encrypt data short write ", n, len(buff))
86 | }
87 | return n, err
88 | }
89 |
90 | func (conn *Conn) Read(b []byte) (n int, err error) {
91 | return conn.Conn.Read(b)
92 | //buff := make([]byte, 1024)
93 | //logger.Println("Conn read")
94 | //n, err = conn.Conn.Read(buff)
95 | //if err != nil {
96 | // logger.Println("Conn read failed", err)
97 | //}
98 | ////logger.Println("before", buff[:n])
99 | //if n > 0 {
100 | // logger.Println("Conn read len", n)
101 | // b = b[:n]
102 | // conn.Decrypt(b, buff[:n])
103 | // //logger.Println("after", b[:n])
104 | //}
105 | //return n, err
106 | }
107 |
108 | func (conn *Conn) Close() error {
109 | err := conn.Conn.Close()
110 | return err
111 | }
112 |
--------------------------------------------------------------------------------
/fly/error_utils.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | // just check error and print if err is not nil
8 | func CheckError(err error, info string) {
9 | if err != nil {
10 | logger.Println(info, err)
11 | }
12 | }
13 |
14 | // check error and exit if err is not nil
15 | func CheckErrorOrExit(err error, info string) {
16 | if err != nil {
17 | logger.Panicln(info, err)
18 | }
19 | }
20 |
21 | // get info about port occupied
22 | func PortOccupiedInfo(port string) string {
23 | return fmt.Sprintf("port %s has been occuried!", port)
24 | }
25 |
26 | func AcceptErrorInfo() string {
27 | return "accept client error!"
28 | }
29 |
--------------------------------------------------------------------------------
/fly/http.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "io"
7 | "net"
8 | "net/url"
9 | "strings"
10 | )
11 |
12 | // start http proxy at port
13 | func StartHttp(port string) {
14 | ln := ListenTCP(port)
15 | for {
16 | client, err := ln.Accept()
17 | if err != nil {
18 | CheckError(err, AcceptErrorInfo())
19 | continue
20 | }
21 | logger.Println("accept success!")
22 | go handleHttpClient(client)
23 | }
24 | }
25 |
26 | func handleHttpClient(client net.Conn) {
27 | if client == nil {
28 | return
29 | }
30 | defer client.Close()
31 |
32 | var b [1024]byte
33 | n, err := client.Read(b[:])
34 | if err != nil {
35 | logger.Println(err)
36 | return
37 | }
38 | index := bytes.IndexByte(b[:], '\n')
39 |
40 | if index == -1 {
41 | index = len(b) - 1
42 | logger.Println("parse request error --->", string(b[:]))
43 | }
44 | var method, host, address string
45 | _, _ = fmt.Sscanf(string(b[:]), "%s%s", &method, &host)
46 | hostPortURL, err := url.Parse(host)
47 | if err != nil {
48 | logger.Println(err)
49 | return
50 | }
51 |
52 | if hostPortURL.Opaque == "443" { //https request
53 | address = hostPortURL.Scheme + ":443"
54 | } else { //http request
55 | if strings.Index(hostPortURL.Host, ":") == -1 { // host not end with a port, add the default port 80
56 | address = hostPortURL.Host + ":80"
57 | } else {
58 | address = hostPortURL.Host
59 | }
60 | }
61 |
62 | // having already get host and port, let's dial to the target server
63 | server, err := net.Dial("tcp", address)
64 | if err != nil {
65 | logger.Println(err)
66 | return
67 | }
68 | if method == "CONNECT" {
69 | _, _ = fmt.Fprint(client, "HTTP/1.1 200 Connection established\r\n\r\n")
70 | } else {
71 | _, _ = server.Write(b[:n])
72 | }
73 | // forward the traffic
74 | go io.Copy(server, client)
75 | io.Copy(client, server)
76 | }
77 |
--------------------------------------------------------------------------------
/fly/logs.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | nested "github.com/antonfisher/nested-logrus-formatter"
5 | log "github.com/sirupsen/logrus"
6 | "io"
7 | //"log"
8 | "os"
9 | )
10 |
11 | var (
12 | logFlag = false
13 | debugFlag = false
14 | logger *log.Logger
15 | logName = "flynet.log"
16 | )
17 |
18 | func InitLog() {
19 | logger = GetLogger()
20 | }
21 |
22 | func EnableLog(flag bool) {
23 | logFlag = flag
24 | }
25 |
26 | func EnableDebug(flag bool) {
27 | debugFlag = flag
28 | }
29 |
30 | // set log file name, which can include absolute path
31 | func SetLogName(name string) {
32 | logName = name
33 | }
34 |
35 | // return a logger
36 | func GetLogger() *log.Logger {
37 | if logger != nil {
38 | return logger
39 | }
40 | var f *os.File
41 | var err error
42 | if logFlag {
43 | f, err = os.OpenFile(logName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
44 | if err != nil {
45 | log.Println("create or open log file failed --->", err)
46 | }
47 | }
48 | var writers []io.Writer
49 |
50 | //if logFlag && debugFlag {
51 | // writers = []io.Writer{f, os.Stdout}
52 | //} else if !logFlag && !debugFlag {
53 | // writers = []io.Writer{}
54 | //} else if debugFlag {
55 | // writers = []io.Writer{os.Stdout}
56 | //} else {
57 | // writers = []io.Writer{f}
58 | //}
59 |
60 | if logFlag {
61 | writers = append(writers, f)
62 | }
63 | if debugFlag {
64 | writers = append(writers, os.Stdout)
65 | }
66 | targetWriter := io.MultiWriter(writers...)
67 |
68 | logs := log.New()
69 | logs.Out = targetWriter
70 | //logs := log.New(targetWriter, "", log.Ldate|log.Ltime)
71 |
72 | //logs.SetLevel(log.InfoLevel)
73 | logs.SetLevel(log.DebugLevel)
74 | logs.SetFormatter(&nested.Formatter{
75 | HideKeys: true,
76 | FieldsOrder: []string{"component", "category"},
77 | TimestampFormat: "2006-01-02 15:04:05",
78 | })
79 |
80 | //logs.SetReportCaller(true)
81 | return logs
82 | }
83 |
--------------------------------------------------------------------------------
/fly/net_utils.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "strconv"
7 | )
8 |
9 | // ListenTCP listen tcp port at the localPort
10 | func ListenTCP(localPort string) net.Listener {
11 | listener, err := net.Listen("tcp", fmt.Sprintf(":%s", localPort))
12 | if err != nil {
13 | logger.Panicln(PortOccupiedInfo(localPort), err.Error())
14 | }
15 | logger.Printf("listen tcp on: %s\n", localPort)
16 | return listener
17 | }
18 |
19 | // ListenUDP listen udp port at the localPort
20 | func ListenUDP(localPort string) net.Listener {
21 | listener, err := net.Listen("udp", fmt.Sprintf(":%s", localPort))
22 | if err != nil {
23 | logger.Panicln(PortOccupiedInfo(localPort), err.Error())
24 | }
25 | logger.Printf("listen udp on: %s\n", localPort)
26 | return listener
27 | }
28 |
29 | func CheckPort(port string) {
30 | portNum, err := strconv.Atoi(port)
31 | if err != nil {
32 | logger.Fatalln("port is not a number --->", err)
33 | }
34 | if portNum < 1 || portNum > 65535 {
35 | logger.Fatalln("port should be in range [1,65536)")
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/fly/pac.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "io"
5 | "net/http"
6 | "os"
7 | )
8 |
9 | // return the stream and size of pac file
10 | func GetPAC() ([]byte, int) {
11 | // run from the same dir with flynet.pac
12 | file, err := os.Open(`flynet.pac`)
13 | if err != nil {
14 | // run from cmd/client/client.go
15 | file, err = os.Open("../../flynet.pac")
16 | if err != nil {
17 | // run from fly/pac_test.go
18 | file, err = os.Open("../flynet.pac")
19 | if err != nil {
20 | logger.Println("pac file not found! start downlaod from github...")
21 | err := downloadPAC()
22 | logger.Println("pac file download completed!")
23 | if err != nil {
24 | return nil, 0
25 | }
26 | return GetPAC()
27 | }
28 | }
29 | }
30 |
31 | index := 0
32 | fileBuff := make([]byte, 200*1024)
33 | for {
34 | logger.Println("start reading...")
35 | n, err := file.Read(fileBuff[index:])
36 | if err != nil {
37 | if err == io.EOF {
38 | logger.Println("read pac file ok.")
39 | break
40 | }
41 | logger.Println("read pac file error --->", err)
42 | }
43 | index += n
44 | }
45 | return fileBuff, index
46 | }
47 |
48 | func downloadPAC() error {
49 | fileName := "flynet.pac"
50 | resp, err := http.Get("https://raw.githubusercontent.com/petronny/gfwlist2pac/master/gfwlist.pac")
51 | if err != nil {
52 | logger.Println("download pac file failed --->", err)
53 | logger.Panicln("please check your network or disable pac mode!")
54 | return err
55 | }
56 | defer resp.Body.Close()
57 |
58 | file, err := os.Create(fileName)
59 | if err != nil {
60 | logger.Println("create pac file failed --->", err)
61 | return err
62 | }
63 | io.Copy(file, resp.Body)
64 | return nil
65 | }
66 |
--------------------------------------------------------------------------------
/fly/pac_test.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import "testing"
4 |
5 | func TestStartPAC(t *testing.T) {
6 | GetPAC()
7 | }
8 |
--------------------------------------------------------------------------------
/fly/portforward.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "io"
5 | "net"
6 | "sync"
7 | )
8 |
9 | // forward your local port to server port -- client
10 | func PortForwardForClient(localPort, serverAddr string) {
11 | for {
12 | var localCon, serverCon net.Conn
13 | var err error
14 | for {
15 | localCon, err = net.Dial("tcp", ":"+localPort)
16 | if err != nil {
17 | logger.Println(err, "Dial to the target failed!")
18 | } else {
19 | logger.Printf("Dial to localhost:%s success!\n", localPort)
20 | break
21 | }
22 | }
23 |
24 | for {
25 | serverCon, err = net.Dial("tcp", serverAddr)
26 | if err != nil {
27 | logger.Println(err, "Dial to the target failed!")
28 | } else {
29 | logger.Printf("Dial to %s success!\n", serverAddr)
30 | break
31 | }
32 | }
33 | logger.Println("Connect success, start forwarding...")
34 | forward( serverCon, localCon)
35 | }
36 | }
37 |
38 | // forward your local port to server port -- server
39 | func PortForwardForServer(laborPort, queryPort string) {
40 | laborLn := ListenTCP(laborPort)
41 | queryLn := ListenTCP(queryPort)
42 | for {
43 | laborConn, e1 := laborLn.Accept()
44 | queryConn, e2 := queryLn.Accept()
45 | if e1 != nil || e2 != nil {
46 | CheckError(e1, "")
47 | CheckError(e2, "")
48 | continue
49 | }
50 | logger.Println("Connect success, start forwarding...")
51 | forward(laborConn, queryConn)
52 | }
53 | }
54 |
55 | func forward(con1, con2 net.Conn) {
56 | var wg sync.WaitGroup
57 | wg.Add(2)
58 | go copyConn(con1,con2, &wg)
59 | go copyConn(con2,con1, &wg)
60 | wg.Wait()
61 | }
62 |
63 | func copyConn(con1, con2 net.Conn, wg *sync.WaitGroup) {
64 | io.Copy(con1, con2)
65 | con1.Close()
66 | wg.Done()
67 | }
--------------------------------------------------------------------------------
/fly/relay.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "encoding/binary"
5 | "github.com/xtaci/kcp-go"
6 | "io"
7 | "net"
8 | )
9 |
10 | func TCPToUDP(session *kcp.UDPSession, conn net.Conn) {
11 | buff := make([]byte, 4096)
12 | for {
13 | n, err := conn.Read(buff)
14 | if err != nil {
15 | logger.Println(err)
16 | break
17 | }
18 | //logs.Printf("TCPToUDP read %d byte\n", n)
19 | n, err = session.Write(buff[:n])
20 | if err != nil {
21 | logger.Println(err)
22 | break
23 | }
24 | }
25 | }
26 |
27 | func UDPToTCP(conn net.Conn, session *kcp.UDPSession) {
28 | buff := make([]byte, 4096)
29 | for {
30 | n, err := session.Read(buff)
31 | if err != nil {
32 | logger.Println(err)
33 | break
34 | }
35 | //logs.Printf("UDPToTCP read %d byte\n", n)
36 | n, err = conn.Write(buff[:n])
37 | if err != nil {
38 | logger.Println(err)
39 | break
40 | }
41 | }
42 | }
43 |
44 | func RelayTraffic(dst, src net.Conn) {
45 | buff := make([]byte, 1024)
46 | for {
47 | n, err := src.Read(buff)
48 | if n > 0 {
49 | m, err := dst.Write(buff[:n])
50 | if err != nil {
51 | logger.Println("RelayTraffic write failed:", err)
52 | break
53 | }
54 | if m != n {
55 | logger.Println("RelayTraffic short write:", err)
56 | break
57 | }
58 | }
59 | if err != nil {
60 | if err != io.EOF {
61 | logger.Println("RelayTraffic read failed:", err)
62 | }
63 | break
64 | }
65 | }
66 | }
67 |
68 | func RelayTrafficWithFlag(dst *Conn, src net.Conn, flag string) {
69 | buff := make([]byte, 1024)
70 | //conn, needDecrypt := src.(*Conn)
71 | //conn, needEncrypt := dst.(*Conn)
72 | //
73 | //var buffR *io.PipeReader
74 | //var buffW *io.PipeWriter
75 | //if needDecrypt {
76 | // buffR, buffW = io.Pipe()
77 | //}
78 |
79 | for {
80 | logger.Debugln(flag, "start read...")
81 | n, err := src.Read(buff)
82 | if err != nil {
83 | if err != io.EOF {
84 | logger.Errorln(flag, "relayTraffic read failed:", err)
85 | } else {
86 | logger.Debugln(flag, "read EOF", n, err)
87 | }
88 | _ = dst.Close()
89 | break
90 | }
91 | if n > 0 {
92 | logger.Debugf("%s write: \n-------------- \n%s \n-------------- \n ", flag, string(buff[:n]))
93 | m, err := dst.Write(buff[:n]) // m = n + 4
94 | if err != nil {
95 | logger.Errorln(flag, "relayTraffic write failed", err)
96 | break
97 | }
98 | if m != n+DataOffset { // addition header size
99 | logger.Errorln(flag, "relayTraffic short write:", err)
100 | break
101 | }
102 | logger.Debugln(flag, "write", m)
103 | }
104 |
105 | //logger.Println(flag, "write one")
106 | }
107 | logger.Debugln(flag, "write done")
108 | }
109 |
110 | func RelayTrafficAndDecrypt(dst net.Conn, conn *Conn, flag string) {
111 | //pipeR, pipeW := io.Pipe()
112 | buff := make([]byte, 1024)
113 |
114 | // read pipeline
115 | go func() {
116 | headerBuff := make([]byte, DataOffset)
117 | var buffSize int
118 | var encryptBuff []byte
119 | var decryptBuff []byte
120 |
121 | for {
122 | logger.Debugln(flag, "start read header...")
123 | n, err := io.ReadFull(conn.BufPipe, headerBuff)
124 | if err != nil {
125 | logger.Errorln(flag, "readFull size error ", n, err)
126 | break
127 | }
128 | //binary.BigEndian.PutUint16(headerBuff[:2], uint16(buffSize))
129 | buffSize = int(binary.BigEndian.Uint16(headerBuff[2:DataOffset]))
130 | logger.Debugln(flag, "read header size", buffSize)
131 | logger.Debugln(flag, "current pipe size", conn.BufPipe.Size())
132 |
133 | // Check magic number
134 | if headerBuff[0] != 255 || headerBuff[1] != 255 {
135 | logger.Errorln(flag, "header error !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ", headerBuff)
136 | // TODO other side stop
137 | break
138 | }
139 |
140 | encryptBuff = make([]byte, buffSize)
141 | n, err = io.ReadFull(conn.BufPipe, encryptBuff)
142 | if err != nil {
143 | logger.Errorln(flag, "readFull data error ", n, err)
144 | break
145 | }
146 | decryptBuff = make([]byte, buffSize)
147 | conn.Cipher.Decrypt(decryptBuff, encryptBuff)
148 | logger.Debugf("%s read decrypt body: \n-------------- \n%s \n-------------- \n", flag, string(decryptBuff))
149 |
150 | n, err = dst.Write(decryptBuff)
151 | if err != nil {
152 | logger.Errorln(flag, "write dst error ", n, err)
153 | break
154 | }
155 | logger.Debugln(flag, "write dst", n)
156 | }
157 | }()
158 |
159 | //io.ReadFull()
160 | //flag := "M->S"
161 | for {
162 | logger.Debugln(flag, "start read...")
163 | n, err := conn.Read(buff)
164 | if n > 0 {
165 | //logger.Printf("%s write: \n-------------- \n%s \n-------------- \n ", flag, string(buff[:n]))
166 | }
167 | if err != nil {
168 | if err != io.EOF {
169 | logger.Errorln(flag, "relayTraffic read failed:", err)
170 | } else {
171 | logger.Debugln(flag, "read EOF", n, err)
172 | }
173 | _ = dst.Close()
174 | break
175 | }
176 | //go func() {
177 | logger.Debugln(flag, " start write pipe...")
178 | n, err = conn.BufPipe.Write(buff[:n])
179 | logger.Debugln(flag, " write pipe ", n, "size ", conn.BufPipe.Size())
180 | if err != nil {
181 | logger.Errorln(flag, "RelayTraffic write pipe failed:", err)
182 | }
183 | //}()
184 |
185 | //logger.Println(flag, "write one")
186 | }
187 | }
188 |
189 | func RelayTrafficAndEncrypt(conn *Conn, src net.Conn, flag string) {
190 | RelayTrafficWithFlag(conn, src, flag)
191 | //io.Copy(conn, src)
192 | }
193 |
--------------------------------------------------------------------------------
/fly/socks5.go:
--------------------------------------------------------------------------------
1 | package fly
2 |
3 | import (
4 | "bytes"
5 | "crypto/sha1"
6 | "encoding/binary"
7 | "fmt"
8 | "github.com/xtaci/kcp-go"
9 | "golang.org/x/crypto/pbkdf2"
10 | "io"
11 | "net"
12 | "strconv"
13 | "strings"
14 | )
15 |
16 | //
17 | // https://datatracker.ietf.org/doc/html/rfc1928
18 | //
19 |
20 | func StartSocks5(port string) {
21 | listener := ListenTCP(port)
22 | for {
23 | client, err := listener.Accept()
24 | if err != nil {
25 | logger.Println("Accept failed!")
26 | continue
27 | }
28 | logger.Println("Client accepted!")
29 |
30 | go handleLocalClient(client)
31 | }
32 | }
33 |
34 | func handleLocalClient(client net.Conn) {
35 | data := make([]byte, 1024)
36 | n, err := client.Read(data[:])
37 | if err != nil {
38 | logger.Println("read error!")
39 | return
40 | }
41 |
42 | if data[0] == 0x05 {
43 | // response success of the handshake to client
44 | _, err = client.Write([]byte{0x05, 0x00})
45 | if err != nil {
46 | logger.Println("response to client failed!")
47 | return
48 | }
49 |
50 | // read request
51 | n, err = client.Read(data[:])
52 | if err != nil {
53 | logger.Println("Read from client failed --->", err)
54 | return
55 | } else if n < 7 {
56 | logger.Println("Read error of request length --->", data[:n])
57 | return
58 | }
59 |
60 | var host, port = parseSocksRequest(data, n)
61 | logger.Printf("Start request %s:%s\n", host, port)
62 |
63 | // reply to the request
64 | // +----+-----+-------+------+----------+----------+
65 | // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
66 | // +----+-----+-------+------+----------+----------+
67 | // | 1 | 1 | X'00' | 1 | Variable | 2 |
68 | // +----+-----+-------+------+----------+----------+
69 | //
70 |
71 | // request to the target server
72 | server, err := net.Dial("tcp", net.JoinHostPort(host, port))
73 | if err != nil {
74 | CheckError(err, fmt.Sprintf("request to %s:%s failed!", host, port))
75 |
76 | by := []byte{0x05, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
77 | _, err = client.Write(by)
78 | return
79 | }
80 |
81 | // response request success to client
82 | by := []byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
83 | _, err = client.Write(by)
84 | CheckError(err, "response 'request success' to client failed!")
85 |
86 | //var relayBuf bytes.Buffer
87 | //outPR, outPW := io.Pipe()
88 | //inPR, inPW := io.Pipe()
89 | //
90 | //go RelayTrafficWithFlag(outPW, client, "C->M")
91 | //go RelayTrafficWithFlag(server, outPR, "M->S")
92 | //go RelayTrafficWithFlag(inPW, server, "S->M")
93 | //RelayTrafficWithFlag(client, inPR, "M->C")
94 |
95 | //go RelayTrafficWithFlag(server, client, "C->S")
96 | //RelayTrafficWithFlag(client, server, "S->C")
97 |
98 | go io.Copy(server, client)
99 | io.Copy(client, server)
100 |
101 | //cipherA := NewCipherInstance("", "")
102 | //cipherB := NewCipherInstance("", "")
103 | //serverConn := NewConn(server, cipherA)
104 | //clientConn := NewConn(client, cipherB)
105 | //
106 | //go io.Copy(serverConn, clientConn)
107 | //io.Copy(clientConn, serverConn)
108 | }
109 | }
110 |
111 | func Socks5ForClientByTCP(localPort, serverAddr, method, key string, pacMode bool) {
112 | listener := ListenTCP(localPort)
113 |
114 | cipherEntity := CipherMap[method]
115 | if cipherEntity == nil {
116 | logger.Println("Encrypt method: aes-256-cfb")
117 | } else {
118 | logger.Println("Encrypt method:", method)
119 | }
120 |
121 | if pacMode {
122 | GetPAC()
123 | logger.Printf("pac mode is on, the url is: http://localhost:%s/flynet.pac\n", localPort)
124 | }
125 |
126 | for {
127 | client, err := listener.Accept()
128 | if err != nil {
129 | logger.Println("Accept failed:", err)
130 | continue
131 | }
132 | logger.Println("Client accepted!")
133 |
134 | go func() {
135 | buff := make([]byte, 1024)
136 | n, err := client.Read(buff)
137 | if err != nil {
138 | logger.Println("Read handshake request failed:", err)
139 | return
140 | }
141 | // client hello
142 | // +----+----------+----------+
143 | // |VER | NMETHODS | METHODS |
144 | // +----+----------+----------+
145 | // | 1 | 1 | 1 to 255 |
146 | // +----+----------+----------+
147 | //
148 | if buff[0] == 0x05 {
149 | // accept socks5 connect
150 | if n, err = client.Write([]byte{0x05, 0x00}); err != nil {
151 | logger.Println("Write handshake response failed:", err)
152 | _ = client.Close()
153 | return
154 | }
155 |
156 | // read request
157 | if n, err = io.ReadAtLeast(client, buff, 5); err != nil {
158 | logger.Println("Read client quest failed:", err)
159 | return
160 | }
161 | // reply ok
162 | replyBy := []byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
163 | if _, err = client.Write(replyBy); err != nil {
164 | logger.Println("Reply request failed:", err)
165 | _ = client.Close()
166 | return
167 | }
168 |
169 | //
170 | // +----+-----+-------+------+----------+----------+
171 | // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
172 | // +----+-----+-------+------+----------+----------+
173 | // | 1 | 1 | X'00' | 1 | Variable | 2 |
174 | // +----+-----+-------+------+----------+----------+
175 | //
176 | serverConn := DialWithAddr(serverAddr, method, key, buff[:n])
177 | if serverConn == nil {
178 | _ = client.Close()
179 | return
180 | }
181 |
182 | go RelayTrafficAndEncrypt(serverConn, client, "C->M")
183 | RelayTrafficAndDecrypt(client, serverConn, "M->C")
184 |
185 | //go io.Copy(server, client)
186 | //io.Copy(client, server)
187 | } else {
188 | if pacMode {
189 | handlePACRequest(client, buff[:n], localPort)
190 | }
191 | }
192 | }()
193 | }
194 | }
195 |
196 | func Socks5ForServerByTCP(localPort, method, key string) {
197 | listener := ListenTCP(localPort)
198 |
199 | cipherEntity := CipherMap[method]
200 | if cipherEntity == nil {
201 | logger.Infoln("Encrypt method: aes-256-cfb")
202 | } else {
203 | logger.Infoln("Encrypt method:", method)
204 | }
205 | for {
206 | //logger.Println("waiting...")
207 | client, err := listener.Accept()
208 | if err != nil {
209 | logger.Errorln("Accept failed:", err)
210 | continue
211 | }
212 | go func() {
213 | buff := make([]byte, 1024)
214 | conn := NewConn(client, NewCipherInstance(key, method))
215 | n, err := conn.Read(buff)
216 | if err != nil {
217 | logger.Errorln("Parse target address failed:", err)
218 | return
219 | } else if n < 7 {
220 | logger.Errorln("Read error of request length:", buff[:n])
221 | return
222 | }
223 | // Check magic num
224 | if buff[0] != 255 || buff[1] != 255 {
225 | logger.Errorln("Request decrypt error", buff)
226 | return
227 | }
228 |
229 | var host, port string
230 | var reqLen int
231 | reqLen = int(binary.BigEndian.Uint16(buff[2:4]))
232 | decryptBuff := conn.Cipher.DecryptAndGet(buff[4 : 4+reqLen])
233 |
234 | //fmt.Println(buff[:n])
235 | logger.Debugln(decryptBuff)
236 | logger.Debugf("%d / %d \n", reqLen, n)
237 |
238 | if reqLen+4 == n {
239 | host, port = parseSocksRequest(decryptBuff, n)
240 | } else if reqLen+4 < n {
241 | host, port = parseSocksRequest(decryptBuff, n)
242 | //isOver = true
243 | //buff = buff[reqLen+2:]
244 |
245 | logger.Debugln("before write pipe")
246 | n, err := conn.BufPipe.Write(buff[4+reqLen : n])
247 | logger.Debugln("after write pipe")
248 |
249 | if err != nil {
250 | logger.Errorln("PipeWriter write", n, err)
251 | return
252 | }
253 | }
254 |
255 | logger.Infof("Request ---> %s:%s\n", host, port)
256 |
257 | // dial the target server
258 | server, err := net.Dial("tcp", net.JoinHostPort(host, port))
259 | if err != nil {
260 | logger.Println(fmt.Sprintf("Request %s:%s failed:", host, port), err)
261 | _ = conn.Close()
262 | return
263 | }
264 | go RelayTrafficAndDecrypt(server, conn, "M->S")
265 | RelayTrafficAndEncrypt(conn, server, "S->M")
266 |
267 | //go io.Copy(server, conn)
268 | //io.Copy(conn, server)
269 | }()
270 | }
271 | }
272 |
273 | func Socks5ForClientByUDP(localPort, serverAddr string) {
274 | listener := ListenTCP(localPort)
275 | for {
276 | con, err := listener.Accept()
277 | if err != nil {
278 | logger.Println("accept error --->", err)
279 | continue
280 | }
281 | logger.Println("Client accepted.")
282 |
283 | go func() {
284 | var b [1024]byte
285 | _, err := con.Read(b[:])
286 | if err != nil {
287 | logger.Println("read error --->", err)
288 | return
289 | }
290 | if b[0] == 0x05 {
291 | _, _ = con.Write([]byte{0x05, 0x00})
292 |
293 | // kcp can't resolve addr such as ":8080"
294 | if strings.HasPrefix(serverAddr, ":") {
295 | serverAddr = "127.0.0.1" + serverAddr
296 | }
297 |
298 | key := pbkdf2.Key([]byte("fly"), []byte("asche910"), 1024, 32, sha1.New)
299 | block, _ := kcp.NewAESBlockCrypt(key)
300 | session, err := kcp.DialWithOptions(serverAddr, block, 10, 3)
301 | if err != nil {
302 | logger.Println("connect targetServer failed --->", err)
303 | return
304 | }
305 | go TCPToUDP(session, con)
306 | UDPToTCP(con, session)
307 | }
308 | }()
309 | }
310 | }
311 |
312 | func Socks5ForServerByUDP(localPort string) {
313 | key := pbkdf2.Key([]byte("fly"), []byte("asche910"), 1024, 32, sha1.New)
314 | block, _ := kcp.NewAESBlockCrypt(key)
315 | if listener, err := kcp.ListenWithOptions(":"+localPort, block, 10, 3); err == nil {
316 | logger.Printf("server listent udp at %s\n", localPort)
317 | for {
318 | con, err := listener.AcceptKCP()
319 | if err != nil {
320 | logger.Fatal(err)
321 | }
322 | go func() {
323 | data := make([]byte, 1024)
324 | n, err := con.Read(data)
325 | if err != nil {
326 | logger.Println("read target address failed --->", err)
327 | return
328 | } else if n < 7 {
329 | logger.Println("read error of request length --->", data[:n])
330 | return
331 | }
332 | //logger.Println(string(data[:n]))
333 | if data[0] == 5 && data[1] == 1 && data[2] == 0 {
334 | var host, port = parseSocksRequest(data, n)
335 |
336 | // request to the target server
337 | server, err := net.Dial("tcp", net.JoinHostPort(host, port))
338 | logger.Printf("request remote %s:%s\n", host, port)
339 |
340 | if err != nil {
341 | logger.Println("dial failed!")
342 | CheckError(err, "dial remote failed!")
343 | return
344 | }
345 |
346 | // response request success to client
347 | by := []byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
348 | n, err = con.Write(by)
349 | if err != nil {
350 | logger.Println("response to client failed! ", err)
351 | return
352 | }
353 | go UDPToTCP(server, con)
354 | TCPToUDP(con, server)
355 | } else {
356 | logger.Println("unrecognized protocol!")
357 | return
358 | }
359 | }()
360 | }
361 | } else {
362 | logger.Panicln(err)
363 | }
364 | }
365 |
366 | // parse socks5 request for target host and port
367 | //
368 | // +----+-----+-------+------+----------+----------+
369 | // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
370 | // +----+-----+-------+------+----------+----------+
371 | // | 1 | 1 | X'00' | 1 | Variable | 2 |
372 | // +----+-----+-------+------+----------+----------+
373 | func parseSocksRequest(data []byte, n int) (string, string) {
374 | // TODO sometimes there are some nums, such as '22 3 1 2 0 1 0 1 252...' after port. why?
375 | logger.Debugln("start parse host", data)
376 | var host, port string
377 | var p1, p2 byte
378 | switch data[3] {
379 | case 0x01: // IPV4 address
380 | host = net.IPv4(data[4], data[5], data[6], data[7]).String()
381 | p1 = data[8]
382 | p2 = data[9]
383 | case 0x03: // domain
384 | host = string(data[5 : 5+data[4]]) // data[4] stands for the length of domain
385 | p1 = data[data[4]+5]
386 | p2 = data[data[4]+6]
387 | case 0x04: // IPV6 address
388 | host = net.IP{data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19]}.String()
389 | p1 = data[20]
390 | p2 = data[21]
391 | }
392 | port = strconv.Itoa(int(p1)<<8 | int(p2))
393 | return host, port
394 | }
395 |
396 | func handlePACRequest(conn net.Conn, buff []byte, port string) {
397 | if bytes.Contains(buff[:], []byte("flynet.pac HTTP")) {
398 | fileBuff, size := GetPAC()
399 | // replace the socks5 port of pac file with the port user choose
400 | fileBuff = bytes.Replace(fileBuff[:size], []byte("SOCKS5 127.0.0.1:1080"), []byte("SOCKS5 127.0.0.1:"+port), 1)
401 |
402 | _, _ = conn.Write([]byte(fmt.Sprintf("HTTP/1.1 200 OK\r\n"+
403 | "Content-Type: application/x-ns-proxy-autoconfig\r\n"+
404 | "Server: flynet\r\nContent-Length: %d\r\n\r\n", size)))
405 | _, _ = conn.Write(fileBuff[:size])
406 | } else {
407 | msg := "hello,flynet!"
408 | _, _ = conn.Write([]byte(fmt.Sprintf("HTTP/1.1 200 OK\r\n"+
409 | "Content-Type: text/html; charset=utf-8\r\n"+
410 | "Server: flynet\r\nContent-Length: %d\r\n\r\n%s", len(msg), msg)))
411 | }
412 | conn.Close()
413 | }
414 |
--------------------------------------------------------------------------------
/flynet.conf:
--------------------------------------------------------------------------------
1 | # flynet config file
2 | #
3 | # mode support:
4 | # ['http', 'socks5', 'socks5-tcp', 'socks5-udp', 'forward']
5 | #
6 | # method support:
7 | # ['aes-128-cfb','aes-192-cfb', 'aes-256-cfb', 'aes-128-ctr', 'aes-192-ctr',
8 | # 'aes-256-ctr', 'rc4-md5', 'rc4-md5-6', 'chacha20', 'chacha20-ietf']
9 | #
10 | # more information at https://github.com/asche910/flynet
11 | #
12 |
13 | # if you use flynet in server side, you just care about the the attributes below [server]
14 | [server]
15 | mode = socks5-tcp # work mode
16 | port = 8888 # listen port; multi port use space to divide
17 | method = aes-256-cfb
18 | password =
19 | verbose = true
20 | log = flynet.log
21 |
22 |
23 | # if you use flynet in client side, you just care about the the attributes below [client]
24 | [client]
25 | mode = socks5-tcp # work mode
26 | port = 1080 # local socks5 listen port
27 | serverAddr = example.com:8888 # include host and port
28 | method = aes-256-cfb
29 | password =
30 | pac-mode = true # if true, flynet will start pac mode, and listen at 'http://localhost:port/flynet.pac'(the port is the socks5 port)
31 | verbose = true
32 | log = # if log name is empty, the log will not be on
33 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/asche910/flynet
2 |
3 | go 1.19
4 |
5 | require (
6 | github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da
7 | github.com/antonfisher/nested-logrus-formatter v1.3.1
8 | github.com/sirupsen/logrus v1.9.0
9 | github.com/xtaci/kcp-go v5.4.20+incompatible
10 | golang.org/x/crypto v0.17.0
11 | gopkg.in/ini.v1 v1.67.0
12 | )
13 |
14 | require (
15 | github.com/klauspost/cpuid/v2 v2.1.1 // indirect
16 | github.com/klauspost/reedsolomon v1.11.7 // indirect
17 | github.com/pkg/errors v0.9.1 // indirect
18 | github.com/stretchr/testify v1.8.2 // indirect
19 | github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect
20 | github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b // indirect
21 | github.com/tjfoc/gmsm v1.4.1 // indirect
22 | github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37 // indirect
23 | golang.org/x/net v0.17.0 // indirect
24 | golang.org/x/sys v0.15.0 // indirect
25 | )
26 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
3 | github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY=
4 | github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
5 | github.com/antonfisher/nested-logrus-formatter v1.3.1 h1:NFJIr+pzwv5QLHTPyKz9UMEoHck02Q9L0FP13b/xSbQ=
6 | github.com/antonfisher/nested-logrus-formatter v1.3.1/go.mod h1:6WTfyWFkBc9+zyBaKIqRrg/KwMqBbodBjgbHjDz7zjA=
7 | github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
8 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
9 | github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
10 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
11 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
12 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
13 | github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
14 | github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
15 | github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
16 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
17 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
18 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
19 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
20 | github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
21 | github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
22 | github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
23 | github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
24 | github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
25 | github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
26 | github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
27 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
28 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
29 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
30 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
31 | github.com/klauspost/cpuid/v2 v2.1.1 h1:t0wUqjowdm8ezddV5k0tLWVklVuvLJpoHeb4WBdydm0=
32 | github.com/klauspost/cpuid/v2 v2.1.1/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
33 | github.com/klauspost/reedsolomon v1.11.7 h1:9uaHU0slncktTEEg4+7Vl7q7XUNMBUOK4R9gnKhMjAU=
34 | github.com/klauspost/reedsolomon v1.11.7/go.mod h1:4bXRN+cVzMdml6ti7qLouuYi32KHJ5MGv0Qd8a47h6A=
35 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
36 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
37 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
38 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
39 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
40 | github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
41 | github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
42 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
43 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
44 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
45 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
46 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
47 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
48 | github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
49 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
50 | github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 h1:89CEmDvlq/F7SJEOqkIdNDGJXrQIhuIx9D2DBXjavSU=
51 | github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU=
52 | github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b h1:fj5tQ8acgNUr6O8LEplsxDhUIe2573iLkJc+PqnzZTI=
53 | github.com/templexxx/xor v0.0.0-20191217153810-f85b25db303b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4=
54 | github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho=
55 | github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE=
56 | github.com/xtaci/kcp-go v5.4.20+incompatible h1:TN1uey3Raw0sTz0Fg8GkfM0uH3YwzhnZWQ1bABv5xAg=
57 | github.com/xtaci/kcp-go v5.4.20+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE=
58 | github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37 h1:EWU6Pktpas0n8lLQwDsRyZfmkPeRbdgPtW609es+/9E=
59 | github.com/xtaci/lossyconn v0.0.0-20200209145036-adba10fffc37/go.mod h1:HpMP7DB2CyokmAh4lp0EQnnWhmycP/TvwBGzvuie+H0=
60 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
61 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
62 | golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
63 | golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
64 | golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
65 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
66 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
67 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
68 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
69 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
70 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
71 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
72 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
73 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
74 | golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
75 | golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
76 | golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
77 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
78 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
79 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
80 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
81 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
82 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
83 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
84 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
85 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
86 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
87 | golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
88 | golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
89 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
90 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
91 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
92 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
93 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
94 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
95 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
96 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
97 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
98 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
99 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
100 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
101 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
102 | google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
103 | google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
104 | google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
105 | google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
106 | google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
107 | google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
108 | google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
109 | google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
110 | google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
111 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
112 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
113 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
114 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
115 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
116 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
117 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
118 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
119 |
--------------------------------------------------------------------------------
/server/flyserver.go:
--------------------------------------------------------------------------------
1 | package server
2 |
3 | import (
4 | "github.com/asche910/flynet/fly"
5 | "net"
6 | )
7 |
8 | type FlyServer struct {
9 | Mode int // which function to use, [1:'http', 2:'socks5', 3:'socks5-tcp', 4:'socks5-udp', 5:'forward']
10 | //localHost string
11 | Ports []string // ports[0] stands for the listening port; others are for reserve
12 | Method string
13 | Password string
14 | //protocol string // tcp or udp protocol
15 | clients map[string]net.Conn
16 | }
17 |
18 | func (server *FlyServer) LocalSocks5Proxy(port string) {
19 | fly.StartSocks5(port)
20 | }
21 |
22 | func (server *FlyServer) LocalHttpProxy(port string) {
23 | fly.StartHttp(port)
24 | }
25 |
26 | func (server *FlyServer) Socks5ProxyForTCP(localPort, method, key string) {
27 | fly.Socks5ForServerByTCP(localPort, method, key)
28 | }
29 |
30 | func (server *FlyServer) Socks5ProxyForUDP(localPort string) {
31 | fly.Socks5ForServerByUDP(localPort)
32 | }
33 |
34 | func (server *FlyServer) PortForward(laborPort, queryPort string) {
35 | fly.PortForwardForServer(laborPort, queryPort)
36 | }
37 |
--------------------------------------------------------------------------------