├── .gitignore
├── .travis.yml
├── COPYING
├── README.md
├── cal_speed.py
├── checkack.py
├── docs
├── suft-state.graphml
└── suft-state.png
├── examples
├── rap
│ └── rap.go
├── suft-nc
│ └── main.go
└── tors
│ ├── README.md
│ ├── io.go
│ ├── io_windows.go
│ └── main.go
├── protocol
├── conn.go
├── conn_test.go
├── debug.go
├── endpoint.go
├── endpoint_test.go
├── linked.go
├── linked_test.go
├── netfd_unix.go
├── netfd_windows.go
├── netpoll.go
├── packet.go
├── state.go
├── stopwatch.go
├── timer.go
├── timer.s
└── timing_test.go
└── wireshark-plugin
├── README.md
└── suft.lua
/.gitignore:
--------------------------------------------------------------------------------
1 | *.exe
2 | *.bat
3 | *.sh
4 | *.pprof
5 | *.pdf
6 | *.log
7 | *.tmp
8 | *.dmp
9 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 | go:
3 | - 1.7.3
4 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
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 | # Introduction
2 |
3 | [](https://travis-ci.org/spance/suft)
4 | [](https://godoc.org/github.com/spance/suft/protocol)
5 |
6 | The SUFT (Small-scale UDP Fast Transmission) Protocol is an application layer transmission protocol based on UDP and implemented in Golang. It has lower latency than TCP and provides reliable and ordered delivery of a stream of octets under plain congestion control.
7 |
8 | The protocol seeks for maximized throughput and minimizes impact of lost packets on throughput. It is only for small/medium-scale communication or some situations where TCP is not applicable.
9 |
10 | # Goals & Features
11 |
12 | - Transmitting model has predictable performance.
13 | - Fast retransmission mode does better on lossy link.
14 | - Minimum retransmission mode doesn't waste traffic.
15 | - No resource consumption while the connection is idle.
16 | - Special modes for certain situations.
17 |
18 | # Protocol APIs
19 |
20 | SUFT implements the Golang: [net.Conn](https://golang.org/pkg/net/#Conn) and [net.Listener](https://golang.org/pkg/net/#Listener) interfaces completely.
21 |
22 | ```go
23 | import "github.com/spance/suft/protocol"
24 |
25 | e, err := suft.NewEndpoint(p *suft.Params)
26 | // for server
27 | conn := e.Listen() // or e.Accept()
28 | // for client
29 | conn, err := e.Dial(rAddr string)
30 | // your business ...
31 | conn.Close()
32 | e.Close()
33 | ```
34 |
35 | # Basic Theories
36 |
37 | scnt(sender: the count of unique data packets) and dups(sender: retransmission counter)
38 |
39 | ```
40 | Lose Rate = dups/(scnt + dups)
41 |
42 | Retransmit Rate = dups/scnt
43 | ```
44 |
45 | latency, window and traffic speed
46 |
47 | ```
48 | Speed = (1000 / latency) * mss * win
49 | ```
50 |
51 | # License
52 |
53 | GPL version 3 or any later version
54 |
55 | SUFT Protocol
56 | Copyright (C) 2016 spance, l2dy
57 |
58 | This program is free software: you can redistribute it and/or modify
59 | it under the terms of the GNU General Public License as published by
60 | the Free Software Foundation, either version 3 of the License, or
61 | (at your option) any later version.
62 |
63 | This program is distributed in the hope that it will be useful,
64 | but WITHOUT ANY WARRANTY; without even the implied warranty of
65 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
66 | GNU General Public License for more details.
67 |
68 | You should have received a copy of the GNU General Public License
69 | along with this program. If not, see .
70 |
71 | # Tool Usage
72 |
73 | "suft-nc" package include a tool for testing, similar to netcat (nc).
74 |
75 | Build with `go get -u -v github.com/spance/suft/examples/suft-nc`
76 |
77 | ```
78 | ./suft-nc [-l addr:port] [-r addr:port] [-s] [-b 10] [-fr] < [send_file] > [recv_file]
79 |
80 | -l: local bind address, e.g. localhost:9090 or :8080
81 | -r: remote address (for client), e.g. 8.8.8.8:9090 or examples.com:8080
82 | -b: max bandwidth of sending in mbps (be careful, see Notes#2)
83 | -s: for server
84 | -fr: enable fast retransmission (useful for lossy link)
85 | -ft: flat traffic (slow down bursty traffic, useful when sender has more bandwidth than receiver)
86 | ```
87 |
88 | Examples:
89 |
90 | ```
91 | // send my_file to remote in 10mbps
92 | remote# ./suft-nc -l :9090 -s > recv_file
93 | local# ./suft-nc -r remote:9090 -b 10 -fr < my_file
94 | ```
95 |
96 | ```
97 | // recv my_file from remote in 50mbps
98 | remote# ./suft-nc -l :9090 -s -b 50 -fr < my_file
99 | local# ./suft-nc -r remote:9090 > recv_file
100 | ```
101 |
102 | ```
103 | // simple chat room
104 | remote# ./suft-nc -l :9090 -s
105 | local# ./suft-nc -r remote:9090
106 | ```
107 |
108 | Notes:
109 |
110 | 1. The target to be connected shouldn't be behind NAT (or should use port mapping).
111 | 2. Use improper bandwidth(-b) may waste huge bandwidth and may be suspected of carrying out flood attack.
112 |
113 | # How to test?
114 |
115 | ```
116 | // remote, send 100MB stream in 50mbps (your bandwidth bottleneck)
117 | remote# dd if=/dev/zero bs=1M count=100 status=none | ./suft-nc -s -l :9090 -b 50 -fr -ft
118 | // status=none or status=noxfer
119 |
120 | // local console#1, monitor traffic(for simplicity, we can use bmon)
121 | local# bmon -p eth0
122 | // local console#2, recv stream
123 | local# ./suft-nc -r remote:9090 > /dev/null
124 | ```
125 |
--------------------------------------------------------------------------------
/cal_speed.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | import sys
3 |
4 | def speed(latency, win):
5 | return (1000.0/latency)*win*1400.0/1024.0
6 |
7 | if len(sys.argv) == 3:
8 | latency = int(sys.argv[1])
9 | win = int(sys.argv[2])
10 | print "Theoretical speed %.2fKB/s" % speed(latency, win)
11 | else:
12 | print "%s [latency] [win]" % sys.argv[0]
13 |
14 |
--------------------------------------------------------------------------------
/checkack.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | import sys
3 |
4 | args=sys.argv[1:]
5 | if len(args) < 2:
6 | print 'args: ackNo bitmap...'
7 | sys.exit(1)
8 |
9 | on=int(args[0])
10 |
11 | args=''.join(args[1:])
12 | args=args.replace('[', '')
13 | args=args.replace(']', '')
14 | print args
15 |
16 | def getBits():
17 | global args
18 | bits=list(args[:16])
19 | args=args[16:]
20 | for i in range(8):
21 | bits[i]=bits[14-i]
22 | bits[i+1]=bits[15-i]
23 | return int(''.join(bits), 16)
24 |
25 | while len(args)>0:
26 | bits=getBits()
27 | for i in range(64):
28 | print '%d %s' % (on, '.' if bits&1 else 'miss')
29 | bits>>=1
30 | on+=1
31 |
32 |
--------------------------------------------------------------------------------
/docs/suft-state.graphml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | FIN
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | SYN0
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | SYN1
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 | SYN1
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 | EST1
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 | EST1
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 | Working
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 | FIN0
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 | FIN1
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 | FIN
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 | FIN1
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 | FIN1
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 | FIN0
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 | FIN1
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 | Listen
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 | Dial
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 | send syn, waiting syn+ack
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 | reply syn+ack, waiting ack
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 | send ack
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 | active close
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 | reply ack
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 | passsive close
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 | recv ack
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 | Close/W
443 | send fin, waiting ack
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 | recv fin
462 | Close/R
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 | recv fin
481 | Close/R
482 | reply ack
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 |
491 |
492 |
493 |
494 |
495 |
496 |
497 |
498 |
499 |
500 | Close/W
501 | send fin, waiting ack
502 |
503 |
504 |
505 |
506 |
507 |
508 |
509 |
510 |
511 |
512 |
513 |
514 |
515 |
516 |
517 |
518 |
519 |
520 |
521 |
522 |
523 |
524 |
525 |
526 |
527 |
528 |
529 | recv syn
530 |
531 |
532 |
533 |
534 |
535 |
536 |
537 |
538 |
539 |
540 |
541 |
542 |
543 |
544 |
545 |
546 |
--------------------------------------------------------------------------------
/docs/suft-state.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/spance/suft/358fdb24d82d1292cd7e9f824e367936de3ecfee/docs/suft-state.png
--------------------------------------------------------------------------------
/examples/rap/rap.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "io"
6 | "log"
7 | "net"
8 | "os"
9 | "time"
10 |
11 | "github.com/spance/suft/protocol"
12 | )
13 |
14 | func init() {
15 | log.SetOutput(os.Stderr)
16 | log.SetFlags(log.Flags() | log.Lmicroseconds)
17 | }
18 |
19 | func main() {
20 | var raddr string
21 | var p suft.Params
22 |
23 | flag.StringVar(&p.LocalAddr, "l", "", "local")
24 | flag.StringVar(&raddr, "r", "", "AtServer => backend_tcp_peer, AtClient => remote_suft_peer")
25 | flag.BoolVar(&p.IsServ, "s", false, "is server")
26 | flag.BoolVar(&p.FastRetransmit, "fr", true, "FastRetransmit")
27 | flag.BoolVar(&p.FlatTraffic, "ft", true, "FlatTraffic")
28 | flag.Int64Var(&p.Bandwidth, "b", 4, "bandwidth in mbps")
29 |
30 | flag.IntVar(&p.Debug, "debug", 0, "debug")
31 | flag.BoolVar(&p.EnablePprof, "pprof", false, "pprof")
32 | flag.BoolVar(&p.Stacktrace, "stacktrace", false, "stacktrace")
33 | flag.Parse()
34 |
35 | if !p.IsServ && raddr == "" {
36 | log.Fatalln("missing -r")
37 | }
38 |
39 | e, err := suft.NewEndpoint(&p)
40 | checkErr(err)
41 | defer e.Close()
42 | log.Println("start", e.Addr())
43 |
44 | var suConn *suft.Conn
45 | if !p.IsServ { // client
46 | ln, err := net.Listen("tcp", p.LocalAddr)
47 | checkErr(err)
48 | defer ln.Close()
49 |
50 | for {
51 | local, err := ln.Accept()
52 | checkErr(err)
53 | suConn, err = e.Dial(raddr)
54 | if checkWarn(err) {
55 | log.Printf("connected to %s for %s", suConn.RemoteAddr(), local.RemoteAddr())
56 | go duplexPipe(suConn, local)
57 | } else {
58 | safeClose(suConn)
59 | }
60 | }
61 | } else {
62 | for {
63 | suConn = e.Listen()
64 | backend, err := net.Dial("tcp", raddr)
65 | if checkWarn(err) {
66 | log.Printf("connected from %s to %s", suConn.RemoteAddr(), backend.RemoteAddr())
67 | go duplexPipe(suConn, backend)
68 | } else {
69 | safeClose(backend)
70 | }
71 | }
72 | }
73 | }
74 |
75 | func checkErr(e error) {
76 | if e != nil {
77 | log.Panicln(e)
78 | }
79 | }
80 |
81 | func checkWarn(e error) bool {
82 | if e != nil {
83 | log.Println(e)
84 | return false
85 | }
86 | return true
87 | }
88 |
89 | func safeClose(c io.Closer) {
90 | if c != nil {
91 | c.Close()
92 | }
93 | }
94 |
95 | func duplexPipe(s *suft.Conn, t net.Conn) {
96 | const BUF_SIZE = 1 << 20
97 | t.(*net.TCPConn).SetNoDelay(true)
98 | defer t.Close()
99 | defer s.Close()
100 |
101 | var wait = make(chan byte, 2)
102 | go func() {
103 | buf := make([]byte, BUF_SIZE)
104 | io.CopyBuffer(s, t, buf)
105 | wait <- 1
106 | }()
107 | go func() {
108 | buf := make([]byte, BUF_SIZE)
109 | io.CopyBuffer(t, s, buf)
110 | wait <- 1
111 | }()
112 | // one channel closed
113 | <-wait
114 | select {
115 | case <-wait: // second
116 | case <-time.After(10e9):
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/examples/suft-nc/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "io"
7 | "log"
8 | "os"
9 | "time"
10 |
11 | "github.com/spance/suft/protocol"
12 | )
13 |
14 | func init() {
15 | log.SetOutput(os.Stderr)
16 | log.SetFlags(log.Flags() | log.Lmicroseconds)
17 | }
18 |
19 | var timeWaiting int64
20 | var waiting = make(chan *eofStatus, 2)
21 |
22 | func main() {
23 | var raddr string
24 | var p suft.Params
25 | flag.StringVar(&p.LocalAddr, "l", "", "local")
26 | flag.StringVar(&raddr, "r", "", "remote")
27 | flag.BoolVar(&p.IsServ, "s", false, "is server")
28 | flag.BoolVar(&p.FastRetransmit, "fr", true, "FastRetransmit")
29 | flag.BoolVar(&p.FlatTraffic, "ft", true, "FlatTraffic")
30 | flag.Int64Var(&p.Bandwidth, "b", 2, "bandwidth in mbps")
31 | flag.IntVar(&p.Debug, "debug", 0, "debug")
32 | flag.BoolVar(&p.EnablePprof, "pprof", false, "pprof")
33 | flag.BoolVar(&p.Stacktrace, "stacktrace", false, "stacktrace")
34 | flag.Int64Var(&timeWaiting, "w", 0, "Timeout waiting for half-closed connection")
35 | flag.Parse()
36 |
37 | if !p.IsServ && raddr == "" {
38 | log.Fatalln("missing -r")
39 | }
40 |
41 | e, err := suft.NewEndpoint(&p)
42 | checkErr(err)
43 | defer e.Close()
44 |
45 | log.Println("start", e.Addr())
46 | var conn *suft.Conn
47 | if !p.IsServ { // client
48 | conn, err = e.Dial(raddr)
49 | checkErr(err)
50 | log.Println("connected to", conn.RemoteAddr())
51 | go writeOut(conn)
52 | go readIn(conn)
53 | } else {
54 | conn = e.Listen()
55 | log.Println("connected from", conn.RemoteAddr())
56 | go writeOut(conn)
57 | go readIn(conn)
58 | }
59 |
60 | var eof1, eof2 *eofStatus
61 | // there is one direction channel has been released
62 | eof1 = <-waiting
63 | log.Println(eof1.status)
64 |
65 | if timeWaiting > 0 {
66 | for1:
67 | for i, v := range [2]int64{1, timeWaiting} {
68 | select {
69 | case eof2 = <-waiting:
70 | // stdin reader released
71 | break for1
72 | case <-time.After(time.Duration(v * 1e9)):
73 | if i == 0 { // first second for preparing countdown
74 | log.Printf("the countdown to %c has started", "RW"[(eof1.channel+1)%2])
75 | } else { // kill
76 | conn.Close()
77 | }
78 | }
79 | }
80 | } else {
81 | for2:
82 | for { // special case for close stdin
83 | select {
84 | case eof2 = <-waiting:
85 | // stdin reader released
86 | break for2
87 | case <-time.After(1e9):
88 | // conn is closed but reading stdin was still blocking
89 | if conn.IsClosed() {
90 | break for2
91 | }
92 | }
93 | }
94 | }
95 |
96 | if eof2 != nil {
97 | log.Println(eof2.status)
98 | }
99 | conn.PrintState()
100 | }
101 |
102 | func readIn(c *suft.Conn) {
103 | var (
104 | n int64
105 | err1, err2 error
106 | )
107 | wa := suft.StartWatch("R")
108 | n, err1 = io.Copy(c, os.Stdin)
109 | wa.Stop(int(n))
110 |
111 | if timeWaiting <= 0 {
112 | err2 = c.Close()
113 | }
114 | waiting <- &eofStatus{
115 | channel: 0,
116 | status: fmt.Sprint("readIn done", err1, err2),
117 | }
118 | }
119 |
120 | func writeOut(c *suft.Conn) {
121 | var (
122 | n int64
123 | err1, err2 error
124 | )
125 | wa := suft.StartWatch("W")
126 | n, err1 = io.Copy(os.Stdout, c)
127 | os.Stdout.Sync()
128 | wa.Stop(int(n))
129 |
130 | if timeWaiting <= 0 {
131 | err2 = c.Close()
132 | }
133 | waiting <- &eofStatus{
134 | channel: 1,
135 | status: fmt.Sprint("writeOut done", err1, err2),
136 | }
137 | }
138 |
139 | func checkErr(e error) {
140 | if e != nil {
141 | log.Fatalln(e)
142 | }
143 | }
144 |
145 | type eofStatus struct {
146 | channel int
147 | status string
148 | }
149 |
--------------------------------------------------------------------------------
/examples/tors/README.md:
--------------------------------------------------------------------------------
1 | # Usage
2 |
3 | 1. for server
4 |
5 | ```
6 | ./tors -l : -b
7 | ```
8 |
9 | 2. for client - pull file from remote
10 |
11 | ```
12 | rsync -P --blocking-io -e './tors -r :' x: .
13 | ```
14 |
15 | 3. for client - push file to remote
16 |
17 | ```
18 | rsync -P --blocking-io -e './tors -r : -b ' x:
19 | ```
20 |
--------------------------------------------------------------------------------
/examples/tors/io.go:
--------------------------------------------------------------------------------
1 | // +build !windows
2 |
3 | package main
4 |
5 | import (
6 | "io"
7 | "os"
8 | )
9 |
10 | func getStdin() io.Reader {
11 | return os.Stdin
12 | }
13 |
14 | func getStdout() io.Writer {
15 | return os.Stdout
16 | }
17 |
--------------------------------------------------------------------------------
/examples/tors/io_windows.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "io"
5 | "log"
6 | "os"
7 | "syscall"
8 | "unsafe"
9 | )
10 |
11 | var (
12 | _CreateEvent *syscall.Proc
13 | _GetOverlappedResult *syscall.Proc
14 | )
15 |
16 | func init() {
17 | wk, _ := syscall.LoadDLL("kernel32.dll")
18 | _CreateEvent = wk.MustFindProc("CreateEventW")
19 | _GetOverlappedResult = wk.MustFindProc("GetOverlappedResult")
20 | }
21 |
22 | func getStdin() io.Reader {
23 | return newWinAsyncIOFile(os.Stdin.Fd())
24 | }
25 |
26 | func getStdout() io.Writer {
27 | return newWinAsyncIOFile(os.Stdout.Fd())
28 | }
29 |
30 | type winAsyncIOFile struct {
31 | hd syscall.Handle
32 | he syscall.Handle
33 | overlapped syscall.Overlapped
34 | }
35 |
36 | func newWinAsyncIOFile(h uintptr) *winAsyncIOFile {
37 | s := &winAsyncIOFile{hd: syscall.Handle(h)}
38 | s.he = createEvent()
39 | s.overlapped.HEvent = s.he
40 | return s
41 | }
42 |
43 | func createEvent() syscall.Handle {
44 | // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
45 | h, _, e := _CreateEvent.Call(0, 0, 0, 0)
46 | if h == 0 { // return NULL
47 | log.Fatalln("_CreateEventW", e)
48 | }
49 | return syscall.Handle(h)
50 | }
51 |
52 | func (s *winAsyncIOFile) getOverlappedResult(done *uint32) error {
53 | // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683209(v=vs.85).aspx
54 | r, _, en := syscall.Syscall6(_GetOverlappedResult.Addr(), 4,
55 | uintptr(s.hd),
56 | uintptr(unsafe.Pointer(&s.overlapped)),
57 | uintptr(unsafe.Pointer(done)),
58 | 1,
59 | 0, 0)
60 | if r != 0 {
61 | return nil
62 | } else {
63 | // 995=The I/O operation has been aborted because of either a thread exit or an application request.
64 | if en == syscall.ERROR_OPERATION_ABORTED {
65 | return io.EOF
66 | } else {
67 | return en
68 | }
69 | }
70 | }
71 |
72 | func (s *winAsyncIOFile) Read(b []byte) (int, error) {
73 | var done uint32
74 | e := syscall.ReadFile(s.hd, b, &done, &s.overlapped)
75 | if en, y := e.(syscall.Errno); y {
76 | if en == syscall.ERROR_IO_PENDING {
77 | e = s.getOverlappedResult(&done)
78 | }
79 | }
80 | return int(done), e
81 | }
82 |
83 | func (s *winAsyncIOFile) Write(b []byte) (int, error) {
84 | var done uint32
85 | e := syscall.WriteFile(s.hd, b, &done, &s.overlapped)
86 | if en, y := e.(syscall.Errno); y {
87 | if en == syscall.ERROR_IO_PENDING {
88 | e = s.getOverlappedResult(&done)
89 | }
90 | }
91 | return int(done), e
92 | }
93 |
94 | func (s *winAsyncIOFile) Close() error {
95 | return syscall.CancelIoEx(s.hd, &s.overlapped)
96 | }
97 |
--------------------------------------------------------------------------------
/examples/tors/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/binary"
5 | "flag"
6 | "io"
7 | "log"
8 | "net"
9 | "os"
10 | "os/exec"
11 | "strings"
12 |
13 | "github.com/spance/suft/protocol"
14 | )
15 |
16 | var (
17 | transMode int
18 | endpoint *suft.Endpoint
19 | )
20 |
21 | func init() {
22 | log.SetFlags(log.LstdFlags | log.Lshortfile)
23 | log.SetOutput(os.Stderr)
24 | }
25 |
26 | func main() {
27 | var lAddr, rAddr, trans string
28 | var bw int64
29 | flag.StringVar(&lAddr, "l", "", "listen addr for server")
30 | flag.StringVar(&rAddr, "r", "", "remote addr for client")
31 | flag.StringVar(&trans, "t", "suft", "transport layer")
32 | flag.Int64Var(&bw, "b", 4, "bandwidth in mbps")
33 | flag.Parse()
34 |
35 | if (lAddr != "" && rAddr != "") || (lAddr == "" && rAddr == "") {
36 | log.Fatalln("-l for server and -r for client")
37 | }
38 | var isServ bool
39 | var err error
40 | isServ = !(rAddr != "" && flag.NArg() >= 2)
41 |
42 | switch trans {
43 | case "suft":
44 | transMode = 'S'
45 | endpoint, err = suft.NewEndpoint(&suft.Params{
46 | LocalAddr: lAddr,
47 | Bandwidth: bw,
48 | FastRetransmit: true,
49 | FlatTraffic: true,
50 | IsServ: isServ,
51 | })
52 | abortIf(err)
53 |
54 | case "tcp":
55 | transMode = 'T'
56 |
57 | default:
58 | log.Fatalln("Unknown -t", trans)
59 | }
60 |
61 | if isServ {
62 | listen(lAddr)
63 | } else {
64 | connect(rAddr, flag.Args())
65 | }
66 |
67 | }
68 |
69 | func netListen(addr string) net.Listener {
70 | if transMode == 'T' {
71 | ln, err := net.Listen("tcp", addr)
72 | abortIf(err)
73 | return ln
74 | } else {
75 | return endpoint
76 | }
77 | }
78 |
79 | func netDial(addr string) net.Conn {
80 | var conn net.Conn
81 | var err error
82 | if transMode == 'T' {
83 | conn, err = net.Dial("tcp", addr)
84 | } else {
85 | conn, err = endpoint.Dial(addr)
86 | }
87 | abortIf(err)
88 | return conn
89 | }
90 |
91 | func listen(addr string) {
92 | ln := netListen(addr)
93 | defer ln.Close()
94 | log.Println("listen at", ln.Addr())
95 |
96 | for {
97 | conn, err := ln.Accept()
98 | if err == nil {
99 | log.Println("Client from", conn.RemoteAddr())
100 | go sessionHandle(conn)
101 | } else if isTemporaryError(err) {
102 | continue
103 | } else {
104 | break
105 | }
106 | }
107 | }
108 |
109 | func sessionHandle(conn net.Conn) {
110 | defer conn.Close()
111 |
112 | cmdline := readInitialHeader(conn)
113 | if !(len(cmdline) > 1 && cmdline[0] == "rsync") {
114 | return
115 | }
116 | log.Printf("RUN %s", cmdline)
117 |
118 | cmd := exec.Command(cmdline[0], cmdline[1:]...)
119 | stdin, err := cmd.StdinPipe()
120 | abortIf(err)
121 | stdout, err := cmd.StdoutPipe()
122 | abortIf(err)
123 | stderr, err := cmd.StderrPipe()
124 | abortIf(err)
125 | abortIf(cmd.Start())
126 |
127 | go func() {
128 | // conn -> cmd.stdin
129 | n, e := io.Copy(stdin, conn)
130 | e = consumeClosedError(e)
131 | log.Println("net/Rx", n, e)
132 | }()
133 | go func() {
134 | // cmd.stdout -> conn
135 | n, e := io.Copy(conn, stdout)
136 | log.Println("net/Tx", n, e)
137 | }()
138 | // cmd.stderr -> current.stderr
139 | go io.Copy(os.Stderr, stderr)
140 |
141 | err = cmd.Wait()
142 | conn.Close()
143 | log.Println("finished", err)
144 | }
145 |
146 | func connect(addr string, args []string) {
147 | conn := netDial(addr)
148 | defer conn.Close()
149 | writeInitialHeader(conn, args[1:])
150 |
151 | var done = make(chan int, 1)
152 | var stdin = getStdin()
153 |
154 | go func() {
155 | // stdin -> conn
156 | n, e := io.Copy(conn, stdin)
157 | log.Println("net/Tx", n, e)
158 | done <- 1
159 | }()
160 | go func() {
161 | // conn -> stdout
162 | n, e := io.Copy(getStdout(), conn)
163 | log.Println("net/Rx", n, e)
164 | done <- 2
165 | }()
166 | <-done
167 | }
168 |
169 | func isTemporaryError(err error) bool {
170 | if err != nil {
171 | if ne, y := err.(net.Error); y {
172 | return ne.Temporary()
173 | }
174 | }
175 | return false
176 | }
177 |
178 | func abortIf(err error) {
179 | if err != nil {
180 | log.Fatalln(err)
181 | }
182 | }
183 |
184 | func readInitialHeader(rd net.Conn) []string {
185 | var l4 = make([]byte, 4)
186 | _, err := io.ReadFull(rd, l4)
187 | abortIf(err)
188 | nlen := binary.BigEndian.Uint32(l4)
189 | var cmd = make([]byte, nlen)
190 | _, err = io.ReadFull(rd, cmd)
191 | abortIf(err)
192 | return strings.Split(string(cmd), "\x00")
193 | }
194 |
195 | func writeInitialHeader(rd net.Conn, args []string) {
196 | var cmdline = strings.Join(args, "\x00")
197 | var l4 = make([]byte, 4)
198 | binary.BigEndian.PutUint32(l4, uint32(len(cmdline)))
199 | _, err := rd.Write(l4)
200 | abortIf(err)
201 | _, err = rd.Write([]byte(cmdline))
202 | abortIf(err)
203 | }
204 |
205 | func consumeClosedError(e error) error {
206 | if e != nil && strings.Contains(e.Error(), "closed") {
207 | return nil
208 | } else {
209 | return e
210 | }
211 | }
212 |
--------------------------------------------------------------------------------
/protocol/conn.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "encoding/binary"
5 | "fmt"
6 | "io"
7 | "log"
8 | "net"
9 | "time"
10 | )
11 |
12 | const (
13 | _MAX_RETRIES = 6
14 | _MIN_RTT = 8
15 | _MIN_RTO = 30
16 | _MIN_ATO = 2
17 | _MAX_ATO = 10
18 | _MIN_SWND = 10
19 | _MAX_SWND = 960
20 | )
21 |
22 | const (
23 | _VACK_SCHED = iota + 1
24 | _VACK_QUICK
25 | _VACK_MUST
26 | _VSWND_ACTIVE
27 | _VRETR_IMMED
28 | )
29 |
30 | const (
31 | _RETR_REST = -1
32 | _CLOSE = 0xff
33 | )
34 |
35 | var debug int
36 |
37 | func nodeOf(pk *packet) *qNode {
38 | return &qNode{packet: pk}
39 | }
40 |
41 | func (c *Conn) internalRecvLoop() {
42 | defer func() {
43 | // avoid send to closed channel while some replaying
44 | // data packets were received in shutting down.
45 | _ = recover()
46 | }()
47 | var buf, body []byte
48 | for {
49 | select {
50 | case buf = <-c.evRecv:
51 | if buf != nil {
52 | body = buf[_TH_SIZE:]
53 | } else { // shutdown
54 | return
55 | }
56 | }
57 | pk := new(packet)
58 | // keep the original buffer, so we could recycle it in future
59 | pk.buffer = buf
60 | unmarshall(pk, body)
61 | if pk.flag&_F_SACK != 0 {
62 | c.processSAck(pk)
63 | continue
64 | }
65 | if pk.flag&_F_ACK != 0 {
66 | c.processAck(pk)
67 | }
68 | if pk.flag&_F_DATA != 0 {
69 | c.insertData(pk)
70 | } else if pk.flag&_F_FIN != 0 {
71 | if pk.flag&_F_RESET != 0 {
72 | go c.forceShutdownWithLock()
73 | } else {
74 | go c.closeR(pk)
75 | }
76 | }
77 | }
78 | }
79 |
80 | func (c *Conn) internalSendLoop() {
81 | var timer = newTimer(c.rtt)
82 | for {
83 | select {
84 | case v := <-c.evSWnd:
85 | switch v {
86 | case _VRETR_IMMED:
87 | c.outlock.Lock()
88 | c.retransmit2()
89 | c.outlock.Unlock()
90 | case _VSWND_ACTIVE:
91 | timer.TryActive(c.rtt)
92 | case _CLOSE:
93 | return
94 | }
95 | case <-timer.C: // timeout yet
96 | var notifySender bool
97 | c.outlock.Lock()
98 | rest, _ := c.retransmit()
99 | switch rest {
100 | case _RETR_REST, 0: // nothing to send
101 | if c.outQ.size() > 0 {
102 | timer.Reset(c.rtt)
103 | } else {
104 | timer.Stop()
105 | // avoid sender blocking
106 | notifySender = true
107 | }
108 | default: // recent rto point
109 | timer.Reset(minI64(rest, c.rtt))
110 | }
111 | c.outlock.Unlock()
112 | if notifySender {
113 | select {
114 | case c.evSend <- 1:
115 | default:
116 | }
117 | }
118 | }
119 | }
120 | }
121 |
122 | func (c *Conn) internalAckLoop() {
123 | var ackTimer = newTimer(c.ato)
124 | var lastAckState byte
125 | for {
126 | var v byte
127 | select {
128 | case <-ackTimer.C:
129 | // may cause sending duplicated ack if ato>rtt
130 | v = _VACK_QUICK
131 | case v = <-c.evAck:
132 | ackTimer.TryActive(c.ato)
133 | state := lastAckState
134 | lastAckState = v
135 | if state != v {
136 | if v == _CLOSE {
137 | return
138 | }
139 | v = _VACK_MUST
140 | }
141 | }
142 | c.inlock.Lock()
143 | if pkAck := c.makeAck(v); pkAck != nil {
144 | c.internalWrite(nodeOf(pkAck))
145 | }
146 | c.inlock.Unlock()
147 | }
148 | }
149 |
150 | func (c *Conn) retransmit() (rest int64, count int32) {
151 | var now, rto = Now(), c.rto
152 | var limit = c.cwnd
153 | for item := c.outQ.head; item != nil && limit > 0; item = item.next {
154 | if item.scnt != _SENT_OK { // ACKed has scnt==-1
155 | diff := now - item.sent
156 | if diff > rto { // already rto
157 | c.internalWrite(item)
158 | count++
159 | } else {
160 | // continue search next min rto duration
161 | if rest > 0 {
162 | rest = minI64(rest, rto-diff+1)
163 | } else {
164 | rest = rto - diff + 1
165 | }
166 | limit--
167 | }
168 | }
169 | }
170 | c.outDupCnt += int(count)
171 | if count > 0 {
172 | shrcond := (c.fastRetransmit && count > maxI32(c.cwnd>>5, 4)) || (!c.fastRetransmit && count > c.cwnd>>3)
173 | if shrcond && now-c.lastShrink > c.rto {
174 | log.Printf("shrink cwnd from=%d to=%d s/4=%d", c.cwnd, c.cwnd>>1, c.swnd>>2)
175 | c.lastShrink = now
176 | // shrink cwnd and ensure cwnd >= swnd/4
177 | if c.cwnd > c.swnd>>1 {
178 | c.cwnd >>= 1
179 | }
180 | }
181 | }
182 | if c.outQ.size() > 0 {
183 | return
184 | }
185 | return _RETR_REST, 0
186 | }
187 |
188 | func (c *Conn) retransmit2() (count int32) {
189 | var limit, now = minI32(c.outPending>>4, 8), Now()
190 | var fRtt = c.rtt
191 | if now-c.lastShrink > c.rto {
192 | fRtt += maxI64(c.rtt>>4, 1)
193 | } else {
194 | fRtt += maxI64(c.rtt>>1, 2)
195 | }
196 | for item := c.outQ.head; item != nil && count < limit; item = item.next {
197 | if item.scnt != _SENT_OK { // ACKed has scnt==-1
198 | if item.miss >= 3 && now-item.sent >= fRtt {
199 | item.miss = 0
200 | c.internalWrite(item)
201 | count++
202 | }
203 | }
204 | }
205 | c.fRCnt += int(count)
206 | c.outDupCnt += int(count)
207 | return
208 | }
209 |
210 | func (c *Conn) inputAndSend(pk *packet) error {
211 | item := &qNode{packet: pk}
212 | if c.mySeq&3 == 1 {
213 | c.tSlotT0 = NowNS()
214 | }
215 | c.outlock.Lock()
216 | // inflight packets exceeds cwnd
217 | // inflight includes: 1, unacked; 2, missed
218 | for c.outPending >= c.cwnd+c.missed {
219 | c.outlock.Unlock()
220 | if c.wtmo > 0 {
221 | var tmo int64
222 | tmo, c.wtmo = c.wtmo, 0
223 | select {
224 | case v := <-c.evSend:
225 | if v == _CLOSE {
226 | return io.EOF
227 | }
228 | case <-NewTimerChan(tmo):
229 | return ErrIOTimeout
230 | }
231 | } else {
232 | if v := <-c.evSend; v == _CLOSE {
233 | return io.EOF
234 | }
235 | }
236 | c.outlock.Lock()
237 | }
238 | c.outPending++
239 | c.outPkCnt++
240 | c.mySeq++
241 | pk.seq = c.mySeq
242 | c.outQ.appendTail(item)
243 | c.internalWrite(item)
244 | c.outlock.Unlock()
245 | // active resending timer, must blocking
246 | c.evSWnd <- _VSWND_ACTIVE
247 | if c.mySeq&3 == 0 && c.flatTraffic {
248 | // calculate time error bewteen tslot with actual usage.
249 | // consider last sleep time error
250 | t1 := NowNS()
251 | terr := c.tSlot<<2 - c.lastSErr - (t1 - c.tSlotT0)
252 | // rest terr/2 if current time usage less than tslot of 100us.
253 | if terr > 1e5 { // 100us
254 | time.Sleep(time.Duration(terr >> 1))
255 | c.lastSErr = maxI64(NowNS()-t1-terr, 0)
256 | } else {
257 | c.lastSErr >>= 1
258 | }
259 | }
260 | return nil
261 | }
262 |
263 | func (c *Conn) internalWrite(item *qNode) {
264 | if item.scnt >= 20 {
265 | // no exception of sending fin
266 | if item.flag&_F_FIN != 0 {
267 | c.fakeShutdown()
268 | c.dest = nil
269 | return
270 | } else {
271 | log.Println("Warn: too many retries", item)
272 | if c.urgent > 0 { // abort
273 | c.forceShutdown()
274 | return
275 | } else { // continue to retry 10
276 | c.urgent++
277 | item.scnt = 10
278 | }
279 | }
280 | }
281 | // update current sent time and prev sent time
282 | item.sent, item.sent_1 = Now(), item.sent
283 | item.scnt++
284 | buf := item.marshall(c.connID)
285 | if debug >= 3 {
286 | var pkType = packetTypeNames[item.flag]
287 | if item.flag&_F_SACK != 0 {
288 | log.Printf("send %s trp=%d on=%d %x", pkType, item.seq, item.ack, buf[_AH_SIZE+4:])
289 | } else {
290 | log.Printf("send %s seq=%d ack=%d scnt=%d len=%d", pkType, item.seq, item.ack, item.scnt, len(buf)-_TH_SIZE)
291 | }
292 | }
293 | c.sock.WriteToUDP(buf, c.dest)
294 | }
295 |
296 | func (c *Conn) logAck(ack uint32) {
297 | c.lastAck = ack
298 | c.lastAckTime = Now()
299 | }
300 |
301 | func (c *Conn) makeLastAck() (pk *packet) {
302 | c.inlock.Lock()
303 | defer c.inlock.Unlock()
304 | if Now()-c.lastAckTime < c.rtt {
305 | return nil
306 | }
307 | pk = &packet{
308 | ack: maxU32(c.lastAck, c.inQ.maxCtnSeq),
309 | flag: _F_ACK,
310 | }
311 | c.logAck(pk.ack)
312 | return
313 | }
314 |
315 | func (c *Conn) makeAck(level byte) (pk *packet) {
316 | now := Now()
317 | if level < _VACK_MUST && now-c.lastAckTime < c.ato {
318 | if level < _VACK_QUICK || now-c.lastAckTime < minI64(c.ato>>2, 1) {
319 | return
320 | }
321 | }
322 | // ready Q <-|
323 | // |-> outQ start (or more right)
324 | // |-> bitmap start
325 | // [predecessor] [predecessor+1] [predecessor+2] .....
326 | var fakeSAck bool
327 | var predecessor = c.inQ.maxCtnSeq
328 | bmap, tbl := c.inQ.makeHolesBitmap(predecessor)
329 | if len(bmap) <= 0 { // fake sack
330 | bmap = make([]uint64, 1)
331 | bmap[0], tbl = 1, 1
332 | fakeSAck = true
333 | }
334 | // head 4-byte: TBL:1 | SCNT:1 | DELAY:2
335 | buf := make([]byte, len(bmap)*8+4)
336 | pk = &packet{
337 | ack: predecessor + 1,
338 | flag: _F_SACK,
339 | payload: buf,
340 | }
341 | if fakeSAck {
342 | pk.ack--
343 | }
344 | buf[0] = byte(tbl)
345 | // mark delayed time according to the time reference point
346 | if trp := c.inQ.lastIns; trp != nil {
347 | delayed := now - trp.sent
348 | if delayed < c.rtt {
349 | pk.seq = trp.seq
350 | pk.flag |= _F_TIME
351 | buf[1] = trp.scnt
352 | if delayed <= 0 {
353 | delayed = 1
354 | }
355 | binary.BigEndian.PutUint16(buf[2:], uint16(delayed))
356 | }
357 | }
358 | buf1 := buf[4:]
359 | for i, b := range bmap {
360 | binary.BigEndian.PutUint64(buf1[i*8:], b)
361 | }
362 | c.logAck(predecessor)
363 | return
364 | }
365 |
366 | func unmarshallSAck(data []byte) (bmap []uint64, tbl uint32, delayed uint16, scnt uint8) {
367 | if len(data) > 0 {
368 | bmap = make([]uint64, len(data)>>3)
369 | } else {
370 | return
371 | }
372 | tbl = uint32(data[0])
373 | scnt = data[1]
374 | delayed = binary.BigEndian.Uint16(data[2:])
375 | data = data[4:]
376 | for i := 0; i < len(bmap); i++ {
377 | bmap[i] = binary.BigEndian.Uint64(data[i*8:])
378 | }
379 | return
380 | }
381 |
382 | func calSwnd(bandwidth, rtt int64) int32 {
383 | w := int32(bandwidth * rtt / (8000 * _MSS))
384 | if w <= _MAX_SWND {
385 | if w >= _MIN_SWND {
386 | return w
387 | } else {
388 | return _MIN_SWND
389 | }
390 | } else {
391 | return _MAX_SWND
392 | }
393 | }
394 |
395 | func (c *Conn) measure(seq uint32, delayed int64, scnt uint8) {
396 | target := c.outQ.get(seq)
397 | if target != nil {
398 | var lastSent int64
399 | switch target.scnt - scnt {
400 | case 0:
401 | // not sent again since this ack was sent out
402 | lastSent = target.sent
403 | case 1:
404 | // sent again once since this ack was sent out
405 | // then use prev sent time
406 | lastSent = target.sent_1
407 | default:
408 | // can't measure here because the packet was sent too many times
409 | return
410 | }
411 | // real-time rtt
412 | rtt := Now() - lastSent - delayed
413 | // reject these abnormal measures:
414 | // 1. rtt too small -> rtt/8
415 | // 2. backlogging too long
416 | if rtt < maxI64(c.rtt>>3, 1) || delayed > c.rtt>>1 {
417 | return
418 | }
419 | // srtt: update 1/8
420 | err := rtt - (c.srtt >> 3)
421 | c.srtt += err
422 | c.rtt = c.srtt >> 3
423 | if c.rtt < _MIN_RTT {
424 | c.rtt = _MIN_RTT
425 | }
426 | // s-swnd: update 1/4
427 | swnd := c.swnd<<3 - c.swnd + calSwnd(c.bandwidth, c.rtt)
428 | c.swnd = swnd >> 3
429 | c.tSlot = c.rtt * 1e6 / int64(c.swnd)
430 | c.ato = c.rtt >> 4
431 | if c.ato < _MIN_ATO {
432 | c.ato = _MIN_ATO
433 | } else if c.ato > _MAX_ATO {
434 | c.ato = _MAX_ATO
435 | }
436 | if err < 0 {
437 | err = -err
438 | err -= c.mdev >> 2
439 | if err > 0 {
440 | err >>= 3
441 | }
442 | } else {
443 | err -= c.mdev >> 2
444 | }
445 | // mdev: update 1/4
446 | c.mdev += err
447 | rto := c.rtt + maxI64(c.rtt<<1, c.mdev)
448 | if rto >= c.rto {
449 | c.rto = rto
450 | } else {
451 | c.rto = (c.rto + rto) >> 1
452 | }
453 | if c.rto < _MIN_RTO {
454 | c.rto = _MIN_RTO
455 | }
456 | if debug >= 1 {
457 | log.Printf("--- rtt=%d srtt=%d rto=%d swnd=%d", c.rtt, c.srtt, c.rto, c.swnd)
458 | }
459 | }
460 | }
461 |
462 | func (c *Conn) processSAck(pk *packet) {
463 | c.outlock.Lock()
464 | bmap, tbl, delayed, scnt := unmarshallSAck(pk.payload)
465 | if bmap == nil { // bad packet
466 | c.outlock.Unlock()
467 | return
468 | }
469 | if pk.flag&_F_TIME != 0 {
470 | c.measure(pk.seq, int64(delayed), scnt)
471 | }
472 | deleted, missed, continuous := c.outQ.deleteByBitmap(bmap, pk.ack, tbl)
473 | if deleted > 0 {
474 | c.ackHit(deleted, missed)
475 | // lock is released
476 | } else {
477 | c.outlock.Unlock()
478 | }
479 | if c.fastRetransmit && !continuous {
480 | // peer Q is uncontinuous, then trigger FR
481 | if deleted == 0 {
482 | c.evSWnd <- _VRETR_IMMED
483 | } else {
484 | select {
485 | case c.evSWnd <- _VRETR_IMMED:
486 | default:
487 | }
488 | }
489 | }
490 | if debug >= 2 {
491 | log.Printf("SACK qhead=%d deleted=%d outPending=%d on=%d %016x",
492 | c.outQ.distanceOfHead(0), deleted, c.outPending, pk.ack, bmap)
493 | }
494 | }
495 |
496 | func (c *Conn) processAck(pk *packet) {
497 | c.outlock.Lock()
498 | if end := c.outQ.get(pk.ack); end != nil { // ack hit
499 | _, deleted := c.outQ.deleteBefore(end)
500 | c.ackHit(deleted, 0) // lock is released
501 | if debug >= 2 {
502 | log.Printf("ACK hit on=%d", pk.ack)
503 | }
504 | // special case: ack the FIN
505 | if pk.seq == _FIN_ACK_SEQ {
506 | select {
507 | case c.evClose <- _S_FIN0:
508 | default:
509 | }
510 | }
511 | } else { // duplicated ack
512 | if debug >= 2 {
513 | log.Printf("ACK miss on=%d", pk.ack)
514 | }
515 | if pk.flag&_F_SYN != 0 { // No.3 Ack lost
516 | if pkAck := c.makeLastAck(); pkAck != nil {
517 | c.internalWrite(nodeOf(pkAck))
518 | }
519 | }
520 | c.outlock.Unlock()
521 | }
522 | }
523 |
524 | func (c *Conn) ackHit(deleted, missed int32) {
525 | // must in outlock
526 | c.outPending -= deleted
527 | now := Now()
528 | if c.cwnd < c.swnd && now-c.lastShrink > c.rto {
529 | if c.cwnd < c.swnd>>1 {
530 | c.cwnd <<= 1
531 | } else {
532 | c.cwnd += deleted << 1
533 | }
534 | }
535 | if c.cwnd > c.swnd {
536 | c.cwnd = c.swnd
537 | }
538 | if now-c.lastRstMis > c.ato {
539 | c.lastRstMis = now
540 | c.missed = missed
541 | } else {
542 | c.missed = c.missed>>1 + missed
543 | }
544 | if qswnd := c.swnd >> 4; c.missed > qswnd {
545 | c.missed = qswnd
546 | }
547 | c.outlock.Unlock()
548 | select {
549 | case c.evSend <- 1:
550 | default:
551 | }
552 | }
553 |
554 | func (c *Conn) insertData(pk *packet) {
555 | c.inlock.Lock()
556 | defer c.inlock.Unlock()
557 | exists := c.inQ.contains(pk.seq)
558 | // duplicated with already queued or history
559 | // means: last ACK were lost
560 | if exists || pk.seq <= c.inQ.maxCtnSeq {
561 | // then send ACK for dups
562 | select {
563 | case c.evAck <- _VACK_MUST:
564 | default:
565 | }
566 | if debug >= 2 {
567 | dumpQ(fmt.Sprint("duplicated ", pk.seq), c.inQ)
568 | }
569 | c.inDupCnt++
570 | return
571 | }
572 | // record current time in sent and regard as received time
573 | item := &qNode{packet: pk, sent: Now()}
574 | dis := c.inQ.searchInsert(item, c.lastReadSeq)
575 | if debug >= 3 {
576 | log.Printf("\t\t\trecv DATA seq=%d dis=%d maxCtn=%d lastReadSeq=%d", item.seq, dis, c.inQ.maxCtnSeq, c.lastReadSeq)
577 | }
578 |
579 | var ackState byte = _VACK_MUST
580 | var available bool
581 | switch dis {
582 | case 0: // impossible
583 | return
584 | case 1:
585 | if c.inQDirty {
586 | available = c.inQ.updateContinuous(item)
587 | if c.inQ.isWholeContinuous() { // whole Q is ordered
588 | c.inQDirty = false
589 | } else { //those holes still exists.
590 | ackState = _VACK_QUICK
591 | }
592 | } else {
593 | // here is an ideal situation
594 | c.inQ.maxCtnSeq = pk.seq
595 | available = true
596 | ackState = _VACK_SCHED
597 | }
598 |
599 | default: // there is an unordered packet, hole occurred here.
600 | if !c.inQDirty {
601 | c.inQDirty = true
602 | }
603 | }
604 |
605 | // write valid received count
606 | c.inPkCnt++
607 | c.inQ.lastIns = item
608 | // try notify ack
609 | select {
610 | case c.evAck <- ackState:
611 | default:
612 | }
613 | if available { // try notify reader
614 | select {
615 | case c.evRead <- 1:
616 | default:
617 | }
618 | }
619 | }
620 |
621 | func (c *Conn) readInQ() bool {
622 | c.inlock.Lock()
623 | defer c.inlock.Unlock()
624 | // read already <-|-> expected Q
625 | // [lastReadSeq] | [lastReadSeq+1] [lastReadSeq+2] ......
626 | if c.inQ.isEqualsHead(c.lastReadSeq+1) && c.lastReadSeq < c.inQ.maxCtnSeq {
627 | c.lastReadSeq = c.inQ.maxCtnSeq
628 | availabled := c.inQ.get(c.inQ.maxCtnSeq)
629 | availabled, _ = c.inQ.deleteBefore(availabled)
630 | for i := availabled; i != nil; i = i.next {
631 | c.inQReady = append(c.inQReady, i.payload...)
632 | // data was copied, then could recycle memory
633 | bpool.Put(i.buffer)
634 | i.payload = nil
635 | i.buffer = nil
636 | }
637 | return true
638 | }
639 | return false
640 | }
641 |
642 | // should not call this function concurrently.
643 | func (c *Conn) Read(buf []byte) (nr int, err error) {
644 | for {
645 | if len(c.inQReady) > 0 {
646 | n := copy(buf, c.inQReady)
647 | c.inQReady = c.inQReady[n:]
648 | return n, nil
649 | }
650 | if !c.readInQ() {
651 | if c.rtmo > 0 {
652 | var tmo int64
653 | tmo, c.rtmo = c.rtmo, 0
654 | select {
655 | case _, y := <-c.evRead:
656 | if !y && len(c.inQReady) == 0 {
657 | return 0, io.EOF
658 | }
659 | case <-NewTimerChan(tmo):
660 | return 0, ErrIOTimeout
661 | }
662 | } else {
663 | // only when evRead is closed and inQReady is empty
664 | // then could reply eof
665 | if _, y := <-c.evRead; !y && len(c.inQReady) == 0 {
666 | return 0, io.EOF
667 | }
668 | }
669 | }
670 | }
671 | }
672 |
673 | // should not call this function concurrently.
674 | func (c *Conn) Write(data []byte) (nr int, err error) {
675 | for len(data) > 0 && err == nil {
676 | //buf := make([]byte, _MSS+_AH_SIZE)
677 | buf := bpool.Get(c.mss + _AH_SIZE)
678 | body := buf[_TH_SIZE+_CH_SIZE:]
679 | n := copy(body, data)
680 | nr += n
681 | data = data[n:]
682 | pk := &packet{flag: _F_DATA, payload: body[:n], buffer: buf[:_AH_SIZE+n]}
683 | err = c.inputAndSend(pk)
684 | }
685 | return
686 | }
687 |
688 | func (c *Conn) LocalAddr() net.Addr {
689 | return c.sock.LocalAddr()
690 | }
691 |
692 | func (c *Conn) RemoteAddr() net.Addr {
693 | return c.dest
694 | }
695 |
696 | func (c *Conn) SetDeadline(t time.Time) error {
697 | c.SetReadDeadline(t)
698 | c.SetWriteDeadline(t)
699 | return nil
700 | }
701 |
702 | func (c *Conn) SetReadDeadline(t time.Time) error {
703 | if d := t.UnixNano()/Millisecond - Now(); d > 0 {
704 | c.rtmo = d
705 | }
706 | return nil
707 | }
708 |
709 | func (c *Conn) SetWriteDeadline(t time.Time) error {
710 | if d := t.UnixNano()/Millisecond - Now(); d > 0 {
711 | c.wtmo = d
712 | }
713 | return nil
714 | }
715 |
--------------------------------------------------------------------------------
/protocol/conn_test.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "math/rand"
5 | "sort"
6 | "testing"
7 | )
8 |
9 | var conn *Conn
10 |
11 | func init() {
12 | conn = &Conn{
13 | outQ: newLinkedMap(_QModeOut),
14 | inQ: newLinkedMap(_QModeIn),
15 | }
16 | }
17 |
18 | func assert(cond bool, t testing.TB, format string, args ...interface{}) {
19 | if !cond {
20 | t.Errorf(format, args...)
21 | panic("last error")
22 | }
23 | }
24 |
25 | func Test_ordered_insert(t *testing.T) {
26 | data := []byte{1}
27 | var pk *packet
28 | for i := int32(1); i < 33; i++ {
29 | pk = &packet{
30 | seq: uint32(i),
31 | payload: data,
32 | }
33 | conn.insertData(pk)
34 | assert(conn.inQ.size() == i, t, "len inQ=%d", conn.inQ.size())
35 | assert(conn.inQ.maxCtnSeq == pk.seq, t, "lastCtnIn")
36 | assert(!conn.inQDirty, t, "dirty")
37 | }
38 | }
39 |
40 | func Test_unordered_insert(t *testing.T) {
41 | conn.inQ.reset()
42 |
43 | data := []byte{1}
44 | var pk *packet
45 | var seqs = make([]int, 0xfff)
46 | // unordered insert, and assert size
47 | for i := 1; i < len(seqs); i++ {
48 | var seq uint32
49 | for conn.inQ.contains(seq) || seq == 0 {
50 | seq = uint32(rand.Int31n(0xFFffff))
51 | }
52 | seqs[i] = int(seq)
53 | pk = &packet{
54 | seq: seq,
55 | payload: data,
56 | }
57 | conn.insertData(pk)
58 | assert(conn.inQ.size() == int32(i), t, "i=%d inQ.len=%d", i, conn.inQ.size())
59 | }
60 | // assert lastCtnSeq
61 | sort.Ints(seqs)
62 | var zero = 0
63 | var last *int
64 | for i := 0; i < len(seqs); i++ {
65 | if i == 0 && seqs[0] != 0 {
66 | last = &zero
67 | break
68 | }
69 | if last != nil && seqs[i]-*last > 1 {
70 | if i == 1 {
71 | last = &zero
72 | }
73 | break
74 | }
75 | last = &seqs[i]
76 | }
77 | if *last != int(conn.inQ.maxCtnSeq) {
78 | for i, j := range seqs {
79 | if i < 10 {
80 | t.Logf("seq %d", j)
81 | }
82 | }
83 | }
84 | assert(*last == int(conn.inQ.maxCtnSeq), t, "lastCtnSeq=%d but expected=%d", conn.inQ.maxCtnSeq, *last)
85 | t.Logf("lastCtnSeq=%d dirty=%v", conn.inQ.maxCtnSeq, conn.inQDirty)
86 | }
87 |
--------------------------------------------------------------------------------
/protocol/debug.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "encoding/hex"
5 | "fmt"
6 | "log"
7 | "os"
8 | "os/signal"
9 | "runtime"
10 | "runtime/pprof"
11 | "sync/atomic"
12 | "syscall"
13 | )
14 |
15 | var enable_pprof bool
16 | var enable_stacktrace bool
17 | var debug_inited int32
18 |
19 | func set_debug_params(p *Params) {
20 | if atomic.CompareAndSwapInt32(&debug_inited, 0, 1) {
21 | debug = p.Debug
22 | enable_pprof = p.EnablePprof
23 | enable_stacktrace = p.Stacktrace
24 | if enable_pprof {
25 | f, err := os.Create("suft.pprof")
26 | if err != nil {
27 | log.Fatalln(err)
28 | }
29 | pprof.StartCPUProfile(f)
30 | }
31 | }
32 | }
33 |
34 | func (c *Conn) PrintState() {
35 | log.Printf("inQ=%d inQReady=%d outQ=%d", c.inQ.size(), len(c.inQReady), c.outQ.size())
36 | log.Printf("inMaxCtnSeq=%d lastAck=%d lastReadSeq=%d", c.inQ.maxCtnSeq, c.lastAck, c.lastReadSeq)
37 | if c.inPkCnt > 0 {
38 | log.Printf("Rx pcnt=%d dups=%d %%d=%f%%", c.inPkCnt, c.inDupCnt, 100*float32(c.inDupCnt)/float32(c.inPkCnt))
39 | }
40 | if c.outPkCnt > 0 {
41 | log.Printf("Tx pcnt=%d dups=%d %%d=%f%%", c.outPkCnt, c.outDupCnt, 100*float32(c.outDupCnt)/float32(c.outPkCnt))
42 | }
43 | log.Printf("current-rtt=%d FastRetransmit=%d", c.rtt, c.fRCnt)
44 | if enable_stacktrace {
45 | var buf = make([]byte, 6400)
46 | for i := 0; i < 3; i++ {
47 | n := runtime.Stack(buf, true)
48 | if n >= len(buf) {
49 | buf = make([]byte, len(buf)<<1)
50 | } else {
51 | buf = buf[:n]
52 | break
53 | }
54 | }
55 | fmt.Println(string(buf))
56 | }
57 | if enable_pprof {
58 | pprof.StopCPUProfile()
59 | }
60 | }
61 |
62 | func (c *Conn) internal_state() {
63 | ev := make(chan os.Signal, 10)
64 | signal.Notify(ev, syscall.Signal(12), syscall.SIGINT)
65 | for v := range ev {
66 | c.PrintState()
67 | if v == syscall.SIGINT {
68 | os.Exit(1)
69 | }
70 | }
71 | }
72 |
73 | func printBits(b uint64, j, s, d uint32) {
74 | fmt.Printf("bits=%064b j=%d seq=%d dis=%d\n", b, j, s, d)
75 | }
76 |
77 | func dumpb(label string, buf []byte) {
78 | log.Println(label, "\n", hex.Dump(buf))
79 | }
80 |
81 | func dumpQ(s string, q *linkedMap) {
82 | var seqs = make([]uint32, 0, 20)
83 | n := q.head
84 | for i, m := int32(0), q.size(); i < m && n != nil; i++ {
85 | seqs = append(seqs, n.seq)
86 | n = n.next
87 | if len(seqs) == 20 {
88 | log.Printf("%s: Q=%d", s, seqs)
89 | seqs = seqs[:0]
90 | }
91 | }
92 | if len(seqs) > 0 {
93 | log.Printf("%s: Q=%d", s, seqs)
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/protocol/endpoint.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "encoding/binary"
5 | "fmt"
6 | "io"
7 | "log"
8 | "math/rand"
9 | "net"
10 | "sort"
11 | "sync"
12 | "sync/atomic"
13 | "time"
14 |
15 | "github.com/cloudflare/golibs/bytepool"
16 | )
17 |
18 | const (
19 | _SO_BUF_SIZE = 8 << 20
20 | )
21 |
22 | var (
23 | bpool bytepool.BytePool
24 | )
25 |
26 | type Params struct {
27 | LocalAddr string
28 | Bandwidth int64
29 | Mtu int
30 | IsServ bool
31 | FastRetransmit bool
32 | FlatTraffic bool
33 | EnablePprof bool
34 | Stacktrace bool
35 | Debug int
36 | }
37 |
38 | type connID struct {
39 | lid uint32
40 | rid uint32
41 | }
42 |
43 | type Endpoint struct {
44 | udpconn *net.UDPConn
45 | state int32
46 | idSeq uint32
47 | isServ bool
48 | listenChan chan *Conn
49 | lRegistry map[uint32]*Conn
50 | rRegistry map[string][]uint32
51 | mlock sync.RWMutex
52 | timeout *iTimer
53 | params Params
54 | }
55 |
56 | func (c *connID) setRid(b []byte) {
57 | c.rid = binary.BigEndian.Uint32(b[_MAGIC_SIZE+6:])
58 | }
59 |
60 | func init() {
61 | bpool.Init(0, 2000)
62 | rand.Seed(NowNS())
63 | }
64 |
65 | func NewEndpoint(p *Params) (*Endpoint, error) {
66 | set_debug_params(p)
67 | if p.Bandwidth <= 0 || p.Bandwidth > 100 {
68 | return nil, fmt.Errorf("bw->(0,100]")
69 | }
70 | conn, err := net.ListenPacket("udp", p.LocalAddr)
71 | if err != nil {
72 | return nil, err
73 | }
74 | e := &Endpoint{
75 | udpconn: conn.(*net.UDPConn),
76 | idSeq: 1,
77 | isServ: p.IsServ,
78 | listenChan: make(chan *Conn, 1),
79 | lRegistry: make(map[uint32]*Conn),
80 | rRegistry: make(map[string][]uint32),
81 | timeout: newTimer(0),
82 | params: *p,
83 | }
84 | if e.isServ {
85 | e.state = _S_EST0
86 | } else { // client
87 | e.state = _S_EST1
88 | e.idSeq = uint32(rand.Int31())
89 | }
90 | e.params.Bandwidth = p.Bandwidth << 20 // mbps to bps
91 | e.udpconn.SetReadBuffer(_SO_BUF_SIZE)
92 | go e.internal_listen()
93 | return e, nil
94 | }
95 |
96 | func (e *Endpoint) internal_listen() {
97 | const rtmo = 30 * 1e9
98 | var id connID
99 | var pdCtx = getPollCtx(e.udpconn)
100 | for {
101 | //var buf = make([]byte, 1600)
102 | var buf = bpool.Get(1600)
103 | net_pollSetDeadline(pdCtx, rtmo+runtimeNano(), 'r')
104 | n, addr, err := e.udpconn.ReadFromUDP(buf)
105 | if err == nil && n >= _AH_SIZE {
106 | buf = buf[:n]
107 | e.getConnID(&id, buf)
108 |
109 | switch id.lid {
110 | case 0: // new connection
111 | if e.isServ {
112 | go e.acceptNewConn(id, addr, buf)
113 | } else {
114 | dumpb("drop", buf)
115 | }
116 |
117 | case _INVALID_SEQ:
118 | dumpb("drop invalid", buf)
119 |
120 | default: // old connection
121 | e.mlock.RLock()
122 | conn := e.lRegistry[id.lid]
123 | e.mlock.RUnlock()
124 | if conn != nil {
125 | e.dispatch(conn, buf)
126 | } else {
127 | e.resetPeer(addr, id)
128 | dumpb("drop null", buf)
129 | }
130 | }
131 |
132 | } else if err != nil {
133 | // idle process
134 | if nerr, y := err.(net.Error); y && nerr.Timeout() {
135 | e.idleProcess()
136 | continue
137 | }
138 | // other errors
139 | if atomic.LoadInt32(&e.state) == _S_FIN {
140 | return
141 | } else {
142 | log.Println("Error: read sock", err)
143 | }
144 | }
145 | }
146 | }
147 |
148 | func (e *Endpoint) idleProcess() {
149 | // recycle/shrink memory
150 | bpool.Drain()
151 | e.mlock.Lock()
152 | defer e.mlock.Unlock()
153 | // reset urgent
154 | for _, c := range e.lRegistry {
155 | c.outlock.Lock()
156 | if c.outQ.size() == 0 && c.urgent != 0 {
157 | c.urgent = 0
158 | }
159 | c.outlock.Unlock()
160 | }
161 | }
162 |
163 | func (e *Endpoint) Dial(addr string) (*Conn, error) {
164 | rAddr, err := net.ResolveUDPAddr("udp", addr)
165 | if err != nil {
166 | return nil, err
167 | }
168 | e.mlock.Lock()
169 | e.idSeq++
170 | id := connID{e.idSeq, 0}
171 | conn := NewConn(e, rAddr, id)
172 | e.lRegistry[id.lid] = conn
173 | e.mlock.Unlock()
174 | if atomic.LoadInt32(&e.state) != _S_FIN {
175 | err = conn.initConnection(nil)
176 | return conn, err
177 | }
178 | return nil, io.EOF
179 | }
180 |
181 | func (e *Endpoint) acceptNewConn(id connID, addr *net.UDPAddr, buf []byte) {
182 | rKey := addr.String()
183 | e.mlock.Lock()
184 | // map: remoteAddr => remoteConnID
185 | // filter duplicated syn packets
186 | if newArr := insertRid(e.rRegistry[rKey], id.rid); newArr != nil {
187 | e.rRegistry[rKey] = newArr
188 | } else {
189 | e.mlock.Unlock()
190 | log.Println("Warn: duplicated connection", addr)
191 | return
192 | }
193 | e.idSeq++
194 | id.lid = e.idSeq
195 | conn := NewConn(e, addr, id)
196 | e.lRegistry[id.lid] = conn
197 | e.mlock.Unlock()
198 | err := conn.initConnection(buf)
199 | if err == nil {
200 | select {
201 | case e.listenChan <- conn:
202 | case <-time.After(_10ms):
203 | log.Println("Warn: no listener")
204 | }
205 | } else {
206 | e.removeConn(id, addr)
207 | log.Println("Error: init_connection", addr, err)
208 | }
209 | }
210 |
211 | func (e *Endpoint) removeConn(id connID, addr *net.UDPAddr) {
212 | e.mlock.Lock()
213 | delete(e.lRegistry, id.lid)
214 | rKey := addr.String()
215 | if newArr := deleteRid(e.rRegistry[rKey], id.rid); newArr != nil {
216 | if len(newArr) > 0 {
217 | e.rRegistry[rKey] = newArr
218 | } else {
219 | delete(e.rRegistry, rKey)
220 | }
221 | }
222 | e.mlock.Unlock()
223 | }
224 |
225 | // net.Listener
226 | func (e *Endpoint) Close() error {
227 | state := atomic.LoadInt32(&e.state)
228 | if state > 0 && atomic.CompareAndSwapInt32(&e.state, state, _S_FIN) {
229 | err := e.udpconn.Close()
230 | e.lRegistry = nil
231 | e.rRegistry = nil
232 | select { // release listeners
233 | case e.listenChan <- nil:
234 | default:
235 | }
236 | return err
237 | }
238 | return nil
239 | }
240 |
241 | // net.Listener
242 | func (e *Endpoint) Addr() net.Addr {
243 | return e.udpconn.LocalAddr()
244 | }
245 |
246 | // net.Listener
247 | func (e *Endpoint) Accept() (net.Conn, error) {
248 | if atomic.LoadInt32(&e.state) == _S_EST0 {
249 | return <-e.listenChan, nil
250 | } else {
251 | return nil, io.EOF
252 | }
253 | }
254 |
255 | func (e *Endpoint) Listen() *Conn {
256 | if atomic.LoadInt32(&e.state) == _S_EST0 {
257 | return <-e.listenChan
258 | } else {
259 | return nil
260 | }
261 | }
262 |
263 | // tmo in MS
264 | func (e *Endpoint) ListenTimeout(tmo int64) *Conn {
265 | if tmo <= 0 {
266 | return e.Listen()
267 | }
268 | if atomic.LoadInt32(&e.state) == _S_EST0 {
269 | select {
270 | case c := <-e.listenChan:
271 | return c
272 | case <-NewTimerChan(tmo):
273 | }
274 | }
275 | return nil
276 | }
277 |
278 | func (e *Endpoint) getConnID(idPtr *connID, buf []byte) {
279 | // TODO determine magic header
280 | magicAndLen := binary.BigEndian.Uint64(buf)
281 | if int(magicAndLen&0xFFff) == len(buf) {
282 | id := binary.BigEndian.Uint64(buf[_MAGIC_SIZE+2:])
283 | idPtr.lid = uint32(id >> 32)
284 | idPtr.rid = uint32(id)
285 | } else {
286 | idPtr.lid = _INVALID_SEQ
287 | }
288 | }
289 |
290 | func (e *Endpoint) dispatch(c *Conn, buf []byte) {
291 | e.timeout.Reset(30)
292 | select {
293 | case c.evRecv <- buf:
294 | case <-e.timeout.C:
295 | log.Println("Warn: dispatch packet failed")
296 | }
297 | }
298 |
299 | func (e *Endpoint) resetPeer(addr *net.UDPAddr, id connID) {
300 | pk := &packet{flag: _F_FIN | _F_RESET}
301 | buf := nodeOf(pk).marshall(id)
302 | e.udpconn.WriteToUDP(buf, addr)
303 | }
304 |
305 | type u32Slice []uint32
306 |
307 | func (p u32Slice) Len() int { return len(p) }
308 | func (p u32Slice) Less(i, j int) bool { return p[i] < p[j] }
309 | func (p u32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
310 |
311 | // if the rid is not existed in array then insert it return new array
312 | func insertRid(array []uint32, rid uint32) []uint32 {
313 | if len(array) > 0 {
314 | pos := sort.Search(len(array), func(n int) bool {
315 | return array[n] >= rid
316 | })
317 | if pos < len(array) && array[pos] == rid {
318 | return nil
319 | }
320 | }
321 | array = append(array, rid)
322 | sort.Sort(u32Slice(array))
323 | return array
324 | }
325 |
326 | // if rid was existed in array then delete it return new array
327 | func deleteRid(array []uint32, rid uint32) []uint32 {
328 | if len(array) > 0 {
329 | pos := sort.Search(len(array), func(n int) bool {
330 | return array[n] >= rid
331 | })
332 | if pos < len(array) && array[pos] == rid {
333 | newArray := make([]uint32, len(array)-1)
334 | n := copy(newArray, array[:pos])
335 | copy(newArray[n:], array[pos+1:])
336 | return newArray
337 | }
338 | }
339 | return nil
340 | }
341 |
--------------------------------------------------------------------------------
/protocol/endpoint_test.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "sort"
7 | "testing"
8 | )
9 |
10 | func Test_insert_delete_rid(t *testing.T) {
11 | var a []uint32
12 | var b = make([]uint32, 0, 1e3)
13 | var uniq = make(map[uint32]int)
14 | // insert into a with random
15 | for i := 0; i < cap(b); i++ {
16 | n := uint32(rand.Int31())
17 | if _, y := uniq[n]; !y {
18 | b = append(b, n)
19 | uniq[n] = 1
20 | }
21 | dups := 1
22 | if i&0xf == 0xf {
23 | dups = 3
24 | }
25 | for j := 0; j < dups; j++ {
26 | if aa := insertRid(a, n); aa != nil {
27 | a = aa
28 | }
29 | }
30 | }
31 | sort.Sort(u32Slice(b))
32 | bStr := fmt.Sprintf("%d", b)
33 | aStr := fmt.Sprintf("%d", a)
34 | assert(aStr == bStr, t, "a!=b")
35 |
36 | for i := 0; i < len(b); i++ {
37 | if aa := deleteRid(a, b[i]); aa != nil {
38 | a = aa
39 | }
40 | }
41 | assert(len(a) == 0, t, "a!=0")
42 | }
43 |
--------------------------------------------------------------------------------
/protocol/linked.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | type qNode struct {
4 | *packet
5 | prev *qNode
6 | next *qNode
7 | sent int64 // last sent time
8 | sent_1 int64 // prev sent time
9 | miss int // sack miss count
10 | }
11 |
12 | type linkedMap struct {
13 | head *qNode
14 | tail *qNode
15 | qmap map[uint32]*qNode
16 | lastIns *qNode
17 | maxCtnSeq uint32
18 | mode int
19 | }
20 |
21 | const (
22 | _QModeIn = 1
23 | _QModeOut = 2
24 | )
25 |
26 | func newLinkedMap(qmode int) *linkedMap {
27 | return &linkedMap{
28 | qmap: make(map[uint32]*qNode),
29 | mode: qmode,
30 | }
31 | }
32 |
33 | func (l *linkedMap) get(seq uint32) (i *qNode) {
34 | i = l.qmap[seq]
35 | return
36 | }
37 |
38 | func (l *linkedMap) contains(seq uint32) bool {
39 | _, y := l.qmap[seq]
40 | return y
41 | }
42 |
43 | func (l *linkedMap) size() int32 {
44 | return int32(len(l.qmap))
45 | }
46 |
47 | func (l *linkedMap) reset() {
48 | l.head = nil
49 | l.tail = nil
50 | l.lastIns = nil
51 | l.maxCtnSeq = 0
52 | l.qmap = make(map[uint32]*qNode)
53 | }
54 |
55 | func (l *linkedMap) isEqualsHead(seq uint32) bool {
56 | return l.head != nil && seq == l.head.seq
57 | }
58 |
59 | func (l *linkedMap) distanceOfHead(seq uint32) int32 {
60 | if l.head != nil {
61 | return int32(seq - l.head.seq)
62 | } else {
63 | return -1
64 | }
65 | }
66 |
67 | func (l *linkedMap) appendTail(one *qNode) {
68 | if l.tail != nil {
69 | l.tail.next = one
70 | one.prev = l.tail
71 | l.tail = one
72 | } else {
73 | l.head = one
74 | l.tail = one
75 | }
76 | l.qmap[one.seq] = one
77 | }
78 |
79 | // xxx - n - yyy
80 | // xxx - yyy
81 | func (l *linkedMap) deleteAt(n *qNode) {
82 | x, y := n.prev, n.next
83 | if x != nil {
84 | x.next = y
85 | } else {
86 | l.head = y
87 | }
88 | if y != nil {
89 | y.prev = x
90 | } else {
91 | l.tail = x
92 | }
93 | n.prev, n.next = nil, nil
94 | delete(l.qmap, n.seq)
95 | }
96 |
97 | // delete with n <- ...n |
98 | func (l *linkedMap) deleteBefore(n *qNode) (left *qNode, deleted int32) {
99 | for i := n; i != nil; i = i.prev {
100 | delete(l.qmap, i.seq)
101 | if i.scnt != _SENT_OK {
102 | deleted++
103 | // only outQ could delete at here
104 | if l.mode == _QModeOut {
105 | bpool.Put(i.buffer)
106 | i.buffer = nil
107 | }
108 | }
109 | }
110 | left = l.head
111 | l.head = n.next
112 | n.next = nil
113 | if l.head != nil {
114 | l.head.prev = nil
115 | } else { // n.next is the tail and is nil
116 | l.tail = nil
117 | }
118 | return
119 | }
120 |
121 | // xxx - ref
122 | // xxx - one - ref
123 | func (l *linkedMap) insertBefore(ref, one *qNode) {
124 | x := ref.prev
125 | if x != nil {
126 | x.next = one
127 | one.prev = x
128 | } else {
129 | l.head = one
130 | }
131 | ref.prev = one
132 | one.next = ref
133 | l.qmap[one.seq] = one
134 | }
135 |
136 | // ref - zzz
137 | // ref - one - zzz
138 | func (l *linkedMap) insertAfter(ref, one *qNode) {
139 | z := ref.next
140 | if z == nil { // append
141 | ref.next = one
142 | l.tail = one
143 | } else { // insert mid
144 | z.prev = one
145 | ref.next = one
146 | }
147 | one.prev = ref
148 | one.next = z
149 | l.qmap[one.seq] = one
150 | }
151 |
152 | // baseHead: the left outside boundary
153 | // if inserted, return the distance between newNode with baseHead
154 | func (l *linkedMap) searchInsert(one *qNode, baseHead uint32) (dis int64) {
155 | for i := l.tail; i != nil; i = i.prev {
156 | dis = int64(one.seq) - int64(i.seq)
157 | if dis > 0 {
158 | l.insertAfter(i, one)
159 | return
160 | } else if dis == 0 {
161 | // duplicated
162 | return
163 | }
164 | }
165 | if one.seq <= baseHead {
166 | return 0
167 | }
168 | if l.head != nil {
169 | l.insertBefore(l.head, one)
170 | } else {
171 | l.head = one
172 | l.tail = one
173 | l.qmap[one.seq] = one
174 | }
175 | dis = int64(one.seq) - int64(baseHead)
176 | return
177 | }
178 |
179 | func (l *linkedMap) updateContinuous(i *qNode) bool {
180 | var lastCtnSeq = l.maxCtnSeq
181 | for ; i != nil; i = i.next {
182 | if i.seq-lastCtnSeq == 1 {
183 | lastCtnSeq = i.seq
184 | } else {
185 | break
186 | }
187 | }
188 | if lastCtnSeq != l.maxCtnSeq {
189 | l.maxCtnSeq = lastCtnSeq
190 | return true
191 | }
192 | return false
193 | }
194 |
195 | func (l *linkedMap) isWholeContinuous() bool {
196 | return l.tail != nil && l.maxCtnSeq == l.tail.seq
197 | }
198 |
199 | /*
200 | func (l *linkedMap) searchMaxContinued(baseHead uint32) (*qNode, bool) {
201 | var last *qNode
202 | for i := l.head; i != nil; i = i.next {
203 | if last != nil {
204 | if i.seq-last.seq > 1 {
205 | return last, true
206 | }
207 | } else {
208 | if i.seq != baseHead {
209 | return nil, false
210 | }
211 | }
212 | last = i
213 | }
214 | if last != nil {
215 | return last, true
216 | } else {
217 | return nil, false
218 | }
219 | }
220 | */
221 |
222 | func (q *qNode) forward(n int) *qNode {
223 | for ; n > 0 && q != nil; n-- {
224 | q = q.next
225 | }
226 | return q
227 | }
228 |
229 | // prev of bitmap start point
230 | func (l *linkedMap) makeHolesBitmap(prev uint32) ([]uint64, uint32) {
231 | var start *qNode
232 | var bits uint64
233 | var j uint32
234 | for i := l.head; i != nil; i = i.next {
235 | if i.seq >= prev+1 {
236 | start = i
237 | break
238 | }
239 | }
240 | var bitmap []uint64
241 | // search start which is the recent successor of [prev]
242 | Iterator:
243 | for i := start; i != nil; i = i.next {
244 | dis := i.seq - prev
245 | prev = i.seq
246 | j += dis // j is next bit index
247 | for j >= 65 {
248 | if len(bitmap) >= 20 { // bitmap too long
249 | break Iterator
250 | }
251 | bitmap = append(bitmap, bits)
252 | bits = 0
253 | j -= 64
254 | }
255 | bits |= 1 << (j - 1)
256 | }
257 | if j > 0 {
258 | // j -> (0, 64]
259 | bitmap = append(bitmap, bits)
260 | }
261 | return bitmap, j
262 | }
263 |
264 | // from= the bitmap start point
265 | func (l *linkedMap) deleteByBitmap(bmap []uint64, from uint32, tailBitsLen uint32) (deleted, missed int32, lastContinued bool) {
266 | var start = l.qmap[from]
267 | if start != nil {
268 | // delete predecessors
269 | if pred := start.prev; pred != nil {
270 | _, n := l.deleteBefore(pred)
271 | deleted += n
272 | }
273 | } else {
274 | // [from] is out of bounds
275 | return
276 | }
277 | var j, bitsLen uint32
278 | var bits uint64
279 | bits, bmap = bmap[0], bmap[1:]
280 | if len(bmap) > 0 {
281 | bitsLen = 64
282 | } else {
283 | // bmap.len==1, tail is here
284 | bitsLen = tailBitsLen
285 | }
286 | // maxContinued will save the max continued node (from [start]) which could be deleted safely.
287 | // keep the queue smallest
288 | var maxContinued *qNode
289 | lastContinued = true
290 |
291 | for i := start; i != nil; j++ {
292 | if j >= bitsLen {
293 | if len(bmap) > 0 {
294 | j = 0
295 | bits, bmap = bmap[0], bmap[1:]
296 | if len(bmap) > 0 {
297 | bitsLen = 64
298 | } else {
299 | bitsLen = tailBitsLen
300 | }
301 | } else {
302 | // no more pages
303 | goto finished
304 | }
305 | }
306 | if bits&1 == 1 {
307 | if lastContinued {
308 | maxContinued = i
309 | }
310 | if i.scnt != _SENT_OK {
311 | // no mark means first deleting
312 | deleted++
313 | }
314 | // don't delete, just mark it
315 | i.scnt = _SENT_OK
316 | } else {
317 | // known it may be lost
318 | if i.miss == 0 {
319 | missed++
320 | }
321 | i.miss++
322 | lastContinued = false
323 | }
324 | bits >>= 1
325 | i = i.next
326 | }
327 |
328 | finished:
329 | if maxContinued != nil {
330 | l.deleteBefore(maxContinued)
331 | }
332 | return
333 | }
334 |
--------------------------------------------------------------------------------
/protocol/linked_test.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "testing"
7 | )
8 |
9 | var lmap *linkedMap
10 |
11 | func init() {
12 | lmap = newLinkedMap(_QModeIn)
13 | }
14 |
15 | func node(seq int) *qNode {
16 | return &qNode{packet: &packet{seq: uint32(seq)}}
17 | }
18 |
19 | func Test_get(t *testing.T) {
20 | var i, n *qNode
21 | assert(!lmap.contains(0), t, "0 nil")
22 | n = node(0)
23 | lmap.head = n
24 | lmap.tail = n
25 | lmap.qmap[0] = n
26 | i = lmap.get(0)
27 | assert(i == n, t, "0=n")
28 | }
29 |
30 | func Test_insert(t *testing.T) {
31 | lmap.reset()
32 | n := node(1)
33 | // appendTail
34 | lmap.appendTail(n)
35 | assert(lmap.head == n, t, "head n")
36 | assert(lmap.tail == n, t, "head n")
37 | n = node(2)
38 | lmap.appendTail(n)
39 | assert(lmap.head != n, t, "head n")
40 | assert(lmap.tail == n, t, "head n")
41 | assert(lmap.size() == 2, t, "size")
42 | }
43 |
44 | func Test_insertAfter(t *testing.T) {
45 | n1 := lmap.get(1)
46 | n2 := n1.next
47 | n3 := node(3)
48 | lmap.insertAfter(n1, n3)
49 | assert(n1.next == n3, t, "n3")
50 | assert(n1 == n3.prev, t, "left n3")
51 | assert(n2 == n3.next, t, "n3 right")
52 | }
53 |
54 | func Test_insertBefore(t *testing.T) {
55 | n3 := lmap.get(3)
56 | n2 := n3.next
57 | n4 := node(4)
58 | lmap.insertAfter(n3, n4)
59 | assert(n3.next == n4, t, "n4")
60 | assert(n3 == n4.prev, t, "left n4")
61 | assert(n2 == n4.next, t, "n4 right")
62 | }
63 |
64 | func Test_deleteBefore(t *testing.T) {
65 | lmap.reset()
66 | for i := 1; i < 10; i++ {
67 | n := node(i)
68 | lmap.appendTail(n)
69 | }
70 |
71 | var assertRangeEquals = func(n *qNode, start, wantCount int) {
72 | var last *qNode
73 | var count int
74 | for ; n != nil; n = n.next {
75 | assert(int(n.seq) == start, t, "nseq=%d start=%d", n.seq, start)
76 | last = n
77 | start++
78 | count++
79 | }
80 | assert(last.next == nil, t, "tail nil")
81 | assert(count == wantCount, t, "count")
82 | }
83 | assertRangeEquals(lmap.head, 1, 9)
84 | var n *qNode
85 | n = lmap.get(3)
86 | n, _ = lmap.deleteBefore(n)
87 | assertRangeEquals(n, 1, 3)
88 | assert(lmap.head.seq == 4, t, "head")
89 |
90 | n = lmap.get(8)
91 | n, _ = lmap.deleteBefore(n)
92 | assertRangeEquals(n, 4, 5)
93 | assert(lmap.head.seq == 9, t, "head")
94 |
95 | n = lmap.get(9)
96 | n, _ = lmap.deleteBefore(n)
97 | assertRangeEquals(n, 9, 1)
98 |
99 | assert(lmap.size() == 0, t, "size 0")
100 | assert(lmap.head == nil, t, "head nil")
101 | assert(lmap.tail == nil, t, "tail nil")
102 | }
103 |
104 | func testBitmap(t *testing.T, bmap []uint64, prev uint32) {
105 | var j uint
106 | var k int
107 | bits := bmap[k]
108 | t.Logf("test-%d %016x", k, bits)
109 | var checkNextPage = func() {
110 | if j >= 64 {
111 | j = 0
112 | k++
113 | bits = bmap[k]
114 | t.Logf("test-%d %016x", k, bits)
115 | }
116 | }
117 | for i := lmap.head; i != nil && k < len(bmap); i = i.next {
118 | checkNextPage()
119 | dis := i.seq - prev
120 | prev = i.seq
121 | if dis == 1 {
122 | bit := (bits >> j) & 1
123 | assert(bit == 1, t, "1 bit=%d j=%d", bit, j)
124 | j++
125 | } else {
126 | for ; dis > 0; dis-- {
127 | checkNextPage()
128 | bit := (bits >> j) & 1
129 | want := uint64(0)
130 | if dis == 1 {
131 | want = 1
132 | }
133 | assert(bit == want, t, "?=%d bit=%d j=%d", want, bit, j)
134 | j++
135 | }
136 | }
137 | }
138 | // remains bits should be 0
139 | for i := j & 63; i > 0; i-- {
140 | bit := (bits >> j) & 1
141 | assert(bit == 0, t, "00 bit=%d j=%d", bit, j)
142 | j++
143 | }
144 | }
145 |
146 | func Test_bitmap(t *testing.T) {
147 | var prev uint32
148 | var head uint32 = prev + 1
149 |
150 | lmap.reset()
151 | // test 66-%3 and record holes
152 | var holes = make([]uint32, 0, 50)
153 | for i := head; i < 366; i++ {
154 | if i%3 == 0 {
155 | holes = append(holes, i)
156 | continue
157 | }
158 | n := node(int(i))
159 | lmap.appendTail(n)
160 | }
161 | bmap, tbl := lmap.makeHolesBitmap(prev)
162 | testBitmap(t, bmap, prev)
163 |
164 | lmap.reset()
165 | // full 66, do deleteByBitmap then compare
166 | for i := head; i < 366; i++ {
167 | n := node(int(i))
168 | lmap.appendTail(n)
169 | }
170 |
171 | lmap.deleteByBitmap(bmap, head, tbl)
172 | var holesResult = make([]uint32, 0, 50)
173 | for i := lmap.head; i != nil; i = i.next {
174 | if i.scnt != _SENT_OK {
175 | holesResult = append(holesResult, i.seq)
176 | }
177 | }
178 | a := fmt.Sprintf("%x", holes)
179 | b := fmt.Sprintf("%x", holesResult)
180 | assert(a == b, t, "deleteByBitmap \na=%s \nb=%s", a, b)
181 |
182 | lmap.reset()
183 | // test stride across page 1
184 | for i := head; i < 69; i++ {
185 | if i >= 63 && i <= 65 {
186 | continue
187 | }
188 | n := node(int(i))
189 | lmap.appendTail(n)
190 | }
191 | bmap, _ = lmap.makeHolesBitmap(prev)
192 | testBitmap(t, bmap, prev)
193 |
194 | lmap.reset()
195 | prev = 65
196 | head = prev + 1
197 | // test stride across page 0
198 | for i := head; i < 68; i++ {
199 | n := node(int(i))
200 | lmap.appendTail(n)
201 | }
202 | bmap, _ = lmap.makeHolesBitmap(prev)
203 | testBitmap(t, bmap, prev)
204 | }
205 |
206 | var ackbitmap []uint64
207 |
208 | func init_benchmark_map() {
209 | if lmap.size() != 640 {
210 | lmap.reset()
211 | for i := 1; i <= 640; i++ {
212 | lmap.appendTail(node(i))
213 | }
214 | ackbitmap = make([]uint64, 10)
215 | for i := 0; i < len(ackbitmap); i++ {
216 | n := rand.Int63()
217 | ackbitmap[i] = uint64(n) << 1
218 | }
219 | }
220 | }
221 |
222 | func Benchmark_make_bitmap(b *testing.B) {
223 | init_benchmark_map()
224 |
225 | for i := 0; i < b.N; i++ {
226 | lmap.makeHolesBitmap(0)
227 | }
228 | }
229 |
230 | func Benchmark_apply_bitmap(b *testing.B) {
231 | init_benchmark_map()
232 |
233 | for i := 0; i < b.N; i++ {
234 | lmap.deleteByBitmap(ackbitmap, 1, 64)
235 | }
236 | }
237 |
--------------------------------------------------------------------------------
/protocol/netfd_unix.go:
--------------------------------------------------------------------------------
1 | // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
2 |
3 | package suft
4 |
5 | import (
6 | "net"
7 | )
8 |
9 | // Network file descriptor.
10 | type netFD struct {
11 | // locking/lifetime of sysfd + serialize access to Read and Write methods
12 | fdmu fdMutex
13 |
14 | // immutable until Close
15 | sysfd int
16 | family int
17 | sotype int
18 | isConnected bool
19 | net string
20 | laddr net.Addr
21 | raddr net.Addr
22 |
23 | // wait server
24 | pd pollDesc
25 | }
26 |
--------------------------------------------------------------------------------
/protocol/netfd_windows.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "net"
5 | "syscall"
6 | )
7 |
8 | // Network file descriptor.
9 | type netFD struct {
10 | // locking/lifetime of sysfd + serialize access to Read and Write methods
11 | fdmu fdMutex
12 |
13 | // immutable until Close
14 | sysfd syscall.Handle
15 | family int
16 | sotype int
17 | isConnected bool
18 | skipSyncNotif bool
19 | net string
20 | laddr net.Addr
21 | raddr net.Addr
22 |
23 | rop operation // read operation
24 | wop operation // write operation
25 |
26 | // wait server
27 | pd pollDesc
28 | }
29 |
30 | // operation contains superset of data necessary to perform all async IO.
31 | type operation struct {
32 | // Used by IOCP interface, it must be first field
33 | // of the struct, as our code rely on it.
34 | o syscall.Overlapped
35 |
36 | // fields used by runtime.netpoll
37 | runtimeCtx uintptr
38 | mode int32
39 | errno int32
40 | qty uint32
41 |
42 | // fields used only by net package
43 | fd *netFD
44 | errc chan error
45 | buf syscall.WSABuf
46 | sa syscall.Sockaddr
47 | rsa *syscall.RawSockaddrAny
48 | rsan int32
49 | handle syscall.Handle
50 | flags uint32
51 | }
52 |
--------------------------------------------------------------------------------
/protocol/netpoll.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "net"
5 | "unsafe"
6 | )
7 |
8 | func net_pollSetDeadline(ctx uintptr, d int64, mode int)
9 |
10 | func popcnt(src uint64) int
11 |
12 | type fdMutex struct {
13 | state uint64
14 | rsema uint32
15 | wsema uint32
16 | }
17 |
18 | type pollDesc struct {
19 | runtimeCtx uintptr
20 | }
21 |
22 | type netConn struct {
23 | fd *netFD
24 | }
25 |
26 | func getPollCtx(c *net.UDPConn) uintptr {
27 | connPtr := (*netConn)(unsafe.Pointer(c))
28 | return connPtr.fd.pd.runtimeCtx
29 | }
30 |
--------------------------------------------------------------------------------
/protocol/packet.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "encoding/binary"
5 | "fmt"
6 | )
7 |
8 | const (
9 | _F_NIL = 0
10 | _F_SYN = 1
11 | _F_ACK = 1 << 1
12 | _F_SACK = 1 << 2
13 | _F_TIME = 1 << 3
14 | _F_DATA = 1 << 4
15 | // reserved = 1 << 5
16 | _F_RESET = 1 << 6
17 | _F_FIN = 1 << 7
18 | )
19 |
20 | var packetTypeNames = map[byte]string{
21 | 0: "NOOP",
22 | 1: "SYN",
23 | 2: "ACK",
24 | 3: "SYN+ACK",
25 | 4: "SACK",
26 | 8: "TIME",
27 | 12: "SACK+TIME",
28 | 16: "DATA",
29 | 64: "RESET",
30 | 128: "FIN",
31 | 192: "FIN+RESET",
32 | }
33 |
34 | const (
35 | _S_FIN = iota
36 | _S_FIN0
37 | _S_FIN1
38 | _S_SYN0
39 | _S_SYN1
40 | _S_EST0
41 | _S_EST1
42 | )
43 |
44 | // Magic-6 | TH-10 | CH-10 | payload
45 | const (
46 | _MAGIC_SIZE = 6
47 | _TH_SIZE = 10 + _MAGIC_SIZE
48 | _CH_SIZE = 10
49 | _AH_SIZE = _TH_SIZE + _CH_SIZE
50 | )
51 |
52 | const (
53 | // Max UDP payload: 1500 MTU - 20 IP hdr - 8 UDP hdr = 1472 bytes
54 | // Then: MSS = 1472-26 = 1446
55 | // And For ADSL: 1446-8 = 1438
56 | _MSS = 1438
57 | )
58 |
59 | const (
60 | _SENT_OK = 0xff
61 | )
62 |
63 | type packet struct {
64 | seq uint32
65 | ack uint32
66 | flag uint8
67 | scnt uint8
68 | payload []byte
69 | buffer []byte
70 | }
71 |
72 | func (p *packet) marshall(id connID) []byte {
73 | buf := p.buffer
74 | if buf == nil {
75 | buf = make([]byte, _AH_SIZE+len(p.payload))
76 | copy(buf[_TH_SIZE+10:], p.payload)
77 | }
78 | binary.BigEndian.PutUint16(buf[_MAGIC_SIZE:], uint16(len(buf)))
79 | binary.BigEndian.PutUint32(buf[_MAGIC_SIZE+2:], id.rid)
80 | binary.BigEndian.PutUint32(buf[_MAGIC_SIZE+6:], id.lid)
81 | binary.BigEndian.PutUint32(buf[_TH_SIZE:], p.seq)
82 | binary.BigEndian.PutUint32(buf[_TH_SIZE+4:], p.ack)
83 | buf[_TH_SIZE+8] = p.flag
84 | buf[_TH_SIZE+9] = p.scnt
85 | return buf
86 | }
87 |
88 | func unmarshall(pk *packet, buf []byte) {
89 | if len(buf) >= _CH_SIZE {
90 | pk.seq = binary.BigEndian.Uint32(buf)
91 | pk.ack = binary.BigEndian.Uint32(buf[4:])
92 | pk.flag = buf[8]
93 | pk.scnt = buf[9]
94 | pk.payload = buf[10:]
95 | }
96 | }
97 |
98 | func (n *qNode) String() string {
99 | now := Now()
100 | return fmt.Sprintf("type=%s seq=%d scnt=%d sndtime~=%d,%d miss=%d",
101 | packetTypeNames[n.flag], n.seq, n.scnt, n.sent-now, n.sent_1-now, n.miss)
102 | }
103 |
104 | func maxI64(a, b int64) int64 {
105 | if a >= b {
106 | return a
107 | } else {
108 | return b
109 | }
110 | }
111 |
112 | func maxU32(a, b uint32) uint32 {
113 | if a >= b {
114 | return a
115 | } else {
116 | return b
117 | }
118 | }
119 |
120 | func minI64(a, b int64) int64 {
121 | if a <= b {
122 | return a
123 | } else {
124 | return b
125 | }
126 | }
127 |
128 | func maxI32(a, b int32) int32 {
129 | if a >= b {
130 | return a
131 | } else {
132 | return b
133 | }
134 | }
135 |
136 | func minI32(a, b int32) int32 {
137 | if a <= b {
138 | return a
139 | } else {
140 | return b
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/protocol/state.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "errors"
5 | "log"
6 | "net"
7 | "sync"
8 | "sync/atomic"
9 | "time"
10 | )
11 |
12 | const (
13 | _10ms = time.Millisecond * 10
14 | _100ms = time.Millisecond * 100
15 | )
16 |
17 | const (
18 | _FIN_ACK_SEQ uint32 = 0xffFF0000
19 | _INVALID_SEQ uint32 = 0xffFFffFF
20 | )
21 |
22 | var (
23 | ErrIOTimeout error = &TimeoutError{}
24 | ErrUnknown = errors.New("Unknown error")
25 | ErrInexplicableData = errors.New("Inexplicable data")
26 | ErrTooManyAttempts = errors.New("Too many attempts to connect")
27 | )
28 |
29 | type TimeoutError struct{}
30 |
31 | func (e *TimeoutError) Error() string { return "i/o timeout" }
32 | func (e *TimeoutError) Timeout() bool { return true }
33 | func (e *TimeoutError) Temporary() bool { return true }
34 |
35 | type Conn struct {
36 | sock *net.UDPConn
37 | dest *net.UDPAddr
38 | edp *Endpoint
39 | connID connID // 8 bytes
40 | // events
41 | evRecv chan []byte
42 | evRead chan byte
43 | evSend chan byte
44 | evSWnd chan byte
45 | evAck chan byte
46 | evClose chan byte
47 | // protocol state
48 | inlock sync.Mutex
49 | outlock sync.Mutex
50 | state int32
51 | mySeq uint32
52 | swnd int32
53 | cwnd int32
54 | missed int32
55 | outPending int32
56 | lastAck uint32
57 | lastAckTime int64
58 | lastAckTime2 int64
59 | lastShrink int64
60 | lastRstMis int64
61 | ato int64
62 | rto int64
63 | rtt int64
64 | srtt int64
65 | mdev int64
66 | rtmo int64
67 | wtmo int64
68 | tSlot int64
69 | tSlotT0 int64
70 | lastSErr int64
71 | // queue
72 | outQ *linkedMap
73 | inQ *linkedMap
74 | inQReady []byte
75 | inQDirty bool
76 | lastReadSeq uint32 // last user read seq
77 | // params
78 | bandwidth int64
79 | fastRetransmit bool
80 | flatTraffic bool
81 | mss int
82 | // statistics
83 | urgent int
84 | inPkCnt int
85 | inDupCnt int
86 | outPkCnt int
87 | outDupCnt int
88 | fRCnt int
89 | }
90 |
91 | func NewConn(e *Endpoint, dest *net.UDPAddr, id connID) *Conn {
92 | c := &Conn{
93 | sock: e.udpconn,
94 | dest: dest,
95 | edp: e,
96 | connID: id,
97 | evRecv: make(chan []byte, 128),
98 | evRead: make(chan byte, 1),
99 | evSWnd: make(chan byte, 2),
100 | evSend: make(chan byte, 4),
101 | evAck: make(chan byte, 1),
102 | evClose: make(chan byte, 2),
103 | outQ: newLinkedMap(_QModeOut),
104 | inQ: newLinkedMap(_QModeIn),
105 | }
106 | p := e.params
107 | c.bandwidth = p.Bandwidth
108 | c.fastRetransmit = p.FastRetransmit
109 | c.flatTraffic = p.FlatTraffic
110 | c.mss = _MSS
111 | if dest.IP.To4() == nil {
112 | // typical ipv6 header length=40
113 | c.mss -= 20
114 | }
115 | return c
116 | }
117 |
118 | func (c *Conn) initConnection(buf []byte) (err error) {
119 | if buf == nil {
120 | err = c.initDialing()
121 | } else { //server
122 | err = c.acceptConnection(buf[_TH_SIZE:])
123 | }
124 | if err != nil {
125 | return
126 | }
127 | if c.state == _S_EST1 {
128 | c.lastReadSeq = c.lastAck
129 | c.inQ.maxCtnSeq = c.lastAck
130 | c.rtt = maxI64(c.rtt, _MIN_RTT)
131 | c.mdev = c.rtt << 1
132 | c.srtt = c.rtt << 3
133 | c.rto = maxI64(c.rtt*2, _MIN_RTO)
134 | c.ato = maxI64(c.rtt>>4, _MIN_ATO)
135 | c.ato = minI64(c.ato, _MAX_ATO)
136 | // initial cwnd
137 | c.swnd = calSwnd(c.bandwidth, c.rtt) >> 1
138 | c.cwnd = 8
139 | go c.internalRecvLoop()
140 | go c.internalSendLoop()
141 | go c.internalAckLoop()
142 | if debug >= 0 {
143 | go c.internal_state()
144 | }
145 | return nil
146 | } else {
147 | return ErrUnknown
148 | }
149 | }
150 |
151 | func (c *Conn) initDialing() error {
152 | // first syn
153 | pk := &packet{
154 | seq: c.mySeq,
155 | flag: _F_SYN,
156 | }
157 | item := nodeOf(pk)
158 | var buf []byte
159 | c.state = _S_SYN0
160 | t0 := Now()
161 | for i := 0; i < _MAX_RETRIES && c.state == _S_SYN0; i++ {
162 | // send syn
163 | c.internalWrite(item)
164 | select {
165 | case buf = <-c.evRecv:
166 | c.rtt = Now() - t0
167 | c.state = _S_SYN1
168 | c.connID.setRid(buf)
169 | buf = buf[_TH_SIZE:]
170 | case <-time.After(time.Second):
171 | continue
172 | }
173 | }
174 | if c.state == _S_SYN0 {
175 | return ErrTooManyAttempts
176 | }
177 |
178 | unmarshall(pk, buf)
179 | // expected syn+ack
180 | if pk.flag == _F_SYN|_F_ACK && pk.ack == c.mySeq {
181 | if scnt := pk.scnt - 1; scnt > 0 {
182 | c.rtt -= int64(scnt) * 1e3
183 | }
184 | log.Println("rtt", c.rtt)
185 | c.state = _S_EST0
186 | // build ack3
187 | pk.scnt = 0
188 | pk.ack = pk.seq
189 | pk.flag = _F_ACK
190 | item := nodeOf(pk)
191 | // send ack3
192 | c.internalWrite(item)
193 | // update lastAck
194 | c.logAck(pk.ack)
195 | c.state = _S_EST1
196 | return nil
197 | } else {
198 | return ErrInexplicableData
199 | }
200 | }
201 |
202 | func (c *Conn) acceptConnection(buf []byte) error {
203 | var pk = new(packet)
204 | var item *qNode
205 | unmarshall(pk, buf)
206 | // expected syn
207 | if pk.flag == _F_SYN {
208 | c.state = _S_SYN1
209 | // build syn+ack
210 | pk.ack = pk.seq
211 | pk.seq = c.mySeq
212 | pk.flag |= _F_ACK
213 | // update lastAck
214 | c.logAck(pk.ack)
215 | item = nodeOf(pk)
216 | item.scnt = pk.scnt - 1
217 | } else {
218 | dumpb("Syn1 ?", buf)
219 | return ErrInexplicableData
220 | }
221 | for i := 0; i < 5 && c.state == _S_SYN1; i++ {
222 | t0 := Now()
223 | // reply syn+ack
224 | c.internalWrite(item)
225 | // recv ack3
226 | select {
227 | case buf = <-c.evRecv:
228 | c.state = _S_EST0
229 | c.rtt = Now() - t0
230 | buf = buf[_TH_SIZE:]
231 | log.Println("rtt", c.rtt)
232 | case <-time.After(time.Second):
233 | continue
234 | }
235 | }
236 | if c.state == _S_SYN1 {
237 | return ErrTooManyAttempts
238 | }
239 |
240 | pk = new(packet)
241 | unmarshall(pk, buf)
242 | // expected ack3
243 | if pk.flag == _F_ACK && pk.ack == c.mySeq {
244 | c.state = _S_EST1
245 | } else {
246 | // if ack3 lost, resend syn+ack 3-times
247 | // and drop these coming data
248 | if pk.flag&_F_DATA != 0 && pk.seq > c.lastAck {
249 | c.internalWrite(item)
250 | c.state = _S_EST1
251 | } else {
252 | dumpb("Ack3 ?", buf)
253 | return ErrInexplicableData
254 | }
255 | }
256 | return nil
257 | }
258 |
259 | // 20,20,20,20, 100,100,100,100, 1s,1s,1s,1s
260 | func selfSpinWait(fn func() bool) error {
261 | const _MAX_SPIN = 12
262 | for i := 0; i < _MAX_SPIN; i++ {
263 | if fn() {
264 | return nil
265 | } else if i <= 3 {
266 | time.Sleep(_10ms * 2)
267 | } else if i <= 7 {
268 | time.Sleep(_100ms)
269 | } else {
270 | time.Sleep(time.Second)
271 | }
272 | }
273 | return ErrIOTimeout
274 | }
275 |
276 | func (c *Conn) IsClosed() bool {
277 | return atomic.LoadInt32(&c.state) <= _S_FIN1
278 | }
279 |
280 | /*
281 | active close:
282 | 1 <- send fin-W: closeW()
283 | before sending, ensure all outQ items has beed sent out and all of them has been acked.
284 | 2 -> wait to recv ack{fin-W}
285 | then trigger closeR, including send fin-R and wait to recv ack{fin-R}
286 |
287 | passive close:
288 | -> fin:
289 | if outQ is not empty then self-spin wait.
290 | if outQ empty, send ack{fin-W} then goto closeW().
291 | */
292 | func (c *Conn) Close() (err error) {
293 | if !atomic.CompareAndSwapInt32(&c.state, _S_EST1, _S_FIN0) {
294 | return selfSpinWait(func() bool {
295 | return atomic.LoadInt32(&c.state) == _S_FIN
296 | })
297 | }
298 | var err0 error
299 | err0 = c.closeW()
300 | // waiting for fin-2 of peer
301 | err = selfSpinWait(func() bool {
302 | select {
303 | case v := <-c.evClose:
304 | if v == _S_FIN {
305 | return true
306 | } else {
307 | time.AfterFunc(_100ms, func() { c.evClose <- v })
308 | }
309 | default:
310 | }
311 | return false
312 | })
313 | defer c.afterShutdown()
314 | if err != nil {
315 | // backup path for wait ack(finW) timeout
316 | c.closeR(nil)
317 | }
318 | if err0 != nil {
319 | return err0
320 | } else {
321 | return
322 | }
323 | }
324 |
325 | func (c *Conn) beforeCloseW() (err error) {
326 | // check outQ was empty and all has been acked.
327 | // self-spin waiting
328 | for i := 0; i < 2; i++ {
329 | err = selfSpinWait(func() bool {
330 | return atomic.LoadInt32(&c.outPending) <= 0
331 | })
332 | if err == nil {
333 | break
334 | }
335 | }
336 | // send fin, reliably
337 | c.outlock.Lock()
338 | c.mySeq++
339 | c.outPending++
340 | pk := &packet{seq: c.mySeq, flag: _F_FIN}
341 | item := nodeOf(pk)
342 | c.outQ.appendTail(item)
343 | c.internalWrite(item)
344 | c.outlock.Unlock()
345 | c.evSWnd <- _VSWND_ACTIVE
346 | return
347 | }
348 |
349 | func (c *Conn) closeW() (err error) {
350 | // close resource of sending
351 | defer c.afterCloseW()
352 | // send fin
353 | err = c.beforeCloseW()
354 | var closed bool
355 | var max = 20
356 | if c.rtt > 200 {
357 | max = int(c.rtt) / 10
358 | }
359 | // waiting for outQ means:
360 | // 1. all outQ has been acked, for passive
361 | // 2. fin has been acked, for active
362 | for i := 0; i < max && (atomic.LoadInt32(&c.outPending) > 0 || !closed); i++ {
363 | select {
364 | case v := <-c.evClose:
365 | if v == _S_FIN0 {
366 | // namely, last fin has been acked.
367 | closed = true
368 | } else {
369 | time.AfterFunc(_100ms, func() { c.evClose <- v })
370 | }
371 | case <-time.After(_100ms):
372 | }
373 | }
374 | if closed || err != nil {
375 | return
376 | } else {
377 | return ErrIOTimeout
378 | }
379 | }
380 |
381 | func (c *Conn) afterCloseW() {
382 | // can't close(c.evRecv), avoid endpoint dispatch exception
383 | // stop pending inputAndSend
384 | select {
385 | case c.evSend <- _CLOSE:
386 | default:
387 | }
388 | // stop internalSendLoop
389 | c.evSWnd <- _CLOSE
390 | }
391 |
392 | // called by active and passive close()
393 | func (c *Conn) afterShutdown() {
394 | // stop internalRecvLoop
395 | c.evRecv <- nil
396 | // remove registry
397 | c.edp.removeConn(c.connID, c.dest)
398 | log.Println("shutdown", c.state)
399 | }
400 |
401 | // trigger by reset
402 | func (c *Conn) forceShutdownWithLock() {
403 | c.outlock.Lock()
404 | defer c.outlock.Unlock()
405 | c.forceShutdown()
406 | }
407 |
408 | // called by:
409 | // 1/ send exception
410 | // 2/ recv reset
411 | // drop outQ and force shutdown
412 | func (c *Conn) forceShutdown() {
413 | if atomic.CompareAndSwapInt32(&c.state, _S_EST1, _S_FIN) {
414 | defer c.afterShutdown()
415 | // stop sender
416 | for i := 0; i < cap(c.evSend); i++ {
417 | select {
418 | case <-c.evSend:
419 | default:
420 | }
421 | }
422 | select {
423 | case c.evSend <- _CLOSE:
424 | default:
425 | }
426 | c.outQ.reset()
427 | // stop reader
428 | close(c.evRead)
429 | c.inQ.reset()
430 | // stop internalLoops
431 | c.evSWnd <- _CLOSE
432 | c.evAck <- _CLOSE
433 | //log.Println("force shutdown")
434 | }
435 | }
436 |
437 | // for sending fin failed
438 | func (c *Conn) fakeShutdown() {
439 | select {
440 | case c.evClose <- _S_FIN0:
441 | default:
442 | }
443 | }
444 |
445 | func (c *Conn) closeR(pk *packet) {
446 | var passive = true
447 | for {
448 | state := atomic.LoadInt32(&c.state)
449 | switch state {
450 | case _S_FIN:
451 | return
452 | case _S_FIN1: // multiple FIN, maybe lost
453 | c.passiveCloseReply(pk, false)
454 | return
455 | case _S_FIN0: // active close preformed
456 | passive = false
457 | }
458 | if !atomic.CompareAndSwapInt32(&c.state, state, _S_FIN1) {
459 | continue
460 | }
461 | c.passiveCloseReply(pk, true)
462 | break
463 | }
464 | // here, R is closed.
465 | // ^^^^^^^^^^^^^^^^^^^^^
466 | if passive {
467 | // passive closing call closeW contains sending fin and recv ack
468 | // may the ack of fin-2 was lost, then the closeW will timeout
469 | c.closeW()
470 | }
471 | // here, R,W both were closed.
472 | // ^^^^^^^^^^^^^^^^^^^^^
473 | atomic.StoreInt32(&c.state, _S_FIN)
474 | // stop internalAckLoop
475 | c.evAck <- _CLOSE
476 |
477 | if passive {
478 | // close evRecv within here
479 | c.afterShutdown()
480 | } else {
481 | // notify active close thread
482 | select {
483 | case c.evClose <- _S_FIN:
484 | default:
485 | }
486 | }
487 | }
488 |
489 | func (c *Conn) passiveCloseReply(pk *packet, first bool) {
490 | if pk != nil && pk.flag&_F_FIN != 0 {
491 | if first {
492 | c.checkInQ(pk)
493 | close(c.evRead)
494 | }
495 | // ack the FIN
496 | pk = &packet{seq: _FIN_ACK_SEQ, ack: pk.seq, flag: _F_ACK}
497 | item := nodeOf(pk)
498 | c.internalWrite(item)
499 | }
500 | }
501 |
502 | // check inQ ends orderly, and copy queue data to user space
503 | func (c *Conn) checkInQ(pk *packet) {
504 | if nil != selfSpinWait(func() bool {
505 | return c.inQ.maxCtnSeq+1 == pk.seq
506 | }) { // timeout for waiting inQ to finish
507 | return
508 | }
509 | c.inlock.Lock()
510 | defer c.inlock.Unlock()
511 | if c.inQ.size() > 0 {
512 | for i := c.inQ.head; i != nil; i = i.next {
513 | c.inQReady = append(c.inQReady, i.payload...)
514 | }
515 | }
516 | }
517 |
--------------------------------------------------------------------------------
/protocol/stopwatch.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "time"
7 | )
8 |
9 | type watch struct {
10 | label string
11 | t1 time.Time
12 | }
13 |
14 | func StartWatch(s string) *watch {
15 | return &watch{
16 | label: s,
17 | t1: time.Now(),
18 | }
19 | }
20 |
21 | func (w *watch) StopLoops(loop int, size int) {
22 | tu := time.Now().Sub(w.t1).Nanoseconds()
23 | timePerLoop := float64(tu) / float64(loop)
24 | throughput := float64(loop*size) * 1e6 / float64(tu)
25 | tu_ms := float64(tu) / 1e6
26 | fmt.Fprintf(os.Stderr, "%s tu=%.2f ms tpl=%.0f ns throughput=%.2f K/s\n", w.label, tu_ms, timePerLoop, throughput)
27 | }
28 |
29 | var _kt = float64(1e9 / 1024)
30 |
31 | func (w *watch) Stop(size int) {
32 | tu := time.Now().Sub(w.t1).Nanoseconds()
33 | throughput := float64(size) * _kt / float64(tu)
34 | tu_ms := float64(tu) / 1e6
35 | fmt.Fprintf(os.Stderr, "%s tu=%.2f ms throughput=%.2f K/s\n", w.label, tu_ms, throughput)
36 | }
37 |
--------------------------------------------------------------------------------
/protocol/timer.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | const Millisecond = 1e6
4 |
5 | type iTimer struct {
6 | C chan byte
7 | r runtimeTimer
8 | }
9 |
10 | type runtimeTimer struct {
11 | i int
12 | when int64
13 | period int64
14 | f func(c interface{}, seq uintptr) // NOTE: must not be closure
15 | arg interface{}
16 | seq uintptr
17 | }
18 |
19 | func startTimer(*runtimeTimer)
20 | func stopTimer(*runtimeTimer) bool
21 | func runtimeNano() int64
22 | func currentTime() (sec int64, nsec int32)
23 |
24 | func Now() int64 {
25 | s, n := currentTime()
26 | return s*1e3 + int64(n/1e6)
27 | }
28 |
29 | func NowNS() int64 {
30 | s, n := currentTime()
31 | return s*1e9 + int64(n)
32 | }
33 |
34 | func newTimer(d int64) *iTimer {
35 | t := iTimer{
36 | C: make(chan byte, 1),
37 | r: runtimeTimer{
38 | i: -1,
39 | when: d*Millisecond + runtimeNano(),
40 | f: timerCallback,
41 | },
42 | }
43 | t.r.arg = t.C
44 | return &t
45 | }
46 |
47 | func timerCallback(c interface{}, seq uintptr) {
48 | select {
49 | case c.(chan byte) <- 1:
50 | default:
51 | }
52 | }
53 |
54 | func (t *iTimer) Stop() {
55 | stopTimer(&t.r)
56 | }
57 |
58 | func (t *iTimer) Reset(d int64) {
59 | stopTimer(&t.r)
60 | select {
61 | case <-t.C:
62 | default:
63 | }
64 | t.r.when = d*Millisecond + runtimeNano()
65 | startTimer(&t.r)
66 | }
67 |
68 | func (t *iTimer) TryActive(d int64) {
69 | if t.r.i < 0 {
70 | select {
71 | case <-t.C:
72 | default:
73 | }
74 | t.r.when = d*Millisecond + runtimeNano()
75 | startTimer(&t.r)
76 | }
77 | }
78 |
79 | func NewTimerChan(d int64) <-chan byte {
80 | t := iTimer{
81 | C: make(chan byte, 1),
82 | r: runtimeTimer{
83 | i: -1,
84 | when: d*Millisecond + runtimeNano(),
85 | f: timerCallback,
86 | },
87 | }
88 | t.r.arg = t.C
89 | startTimer(&t.r)
90 | return t.C
91 | }
92 |
--------------------------------------------------------------------------------
/protocol/timer.s:
--------------------------------------------------------------------------------
1 | #include "textflag.h"
2 |
3 | TEXT ·currentTime(SB),NOSPLIT,$0
4 | JMP time·now(SB)
5 |
6 | TEXT ·startTimer(SB),NOSPLIT,$0
7 | JMP time·startTimer(SB)
8 |
9 | TEXT ·stopTimer(SB),NOSPLIT,$0
10 | JMP time·stopTimer(SB)
11 |
12 | TEXT ·runtimeNano(SB),NOSPLIT,$0
13 | JMP time·runtimeNano(SB)
14 |
15 | TEXT ·net_pollSetDeadline(SB),NOSPLIT,$0
16 | JMP net·runtime_pollSetDeadline(SB)
17 |
18 |
--------------------------------------------------------------------------------
/protocol/timing_test.go:
--------------------------------------------------------------------------------
1 | package suft
2 |
3 | import (
4 | "math"
5 | "testing"
6 | "time"
7 | )
8 |
9 | func Test_sleep(t *testing.T) {
10 | const loops = 10
11 | var intervals = [...]int64{1, 1e3, 1e4, 1e5, 1e6, 1e7}
12 | var ret [len(intervals)][loops]int64
13 | for j := 0; j < len(intervals); j++ {
14 | v := time.Duration(intervals[j])
15 | for i := 0; i < loops; i++ {
16 | t0 := NowNS()
17 | time.Sleep(v)
18 | ret[j][i] = NowNS() - t0
19 | }
20 | }
21 | for j := 0; j < len(intervals); j++ {
22 | var exp, sum, stdev float64
23 | exp = float64(intervals[j])
24 | for _, v := range ret[j] {
25 | sum += float64(v)
26 | stdev += math.Pow(float64(v)-exp, 2)
27 | }
28 | stdev /= float64(loops)
29 | stdev = math.Sqrt(stdev)
30 | t.Logf("interval=%s sleeping=%s stdev/k=%.2f", time.Duration(intervals[j]), time.Duration(sum/loops), stdev/1e3)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/wireshark-plugin/README.md:
--------------------------------------------------------------------------------
1 | # Usage
2 |
3 | Run `wireshark -X lua_script:suft.lua`.
4 |
5 | # Install
6 |
7 | Copy `suft.lua` to wireshark/plugins/.
8 |
9 | Append `dofile(DATA_DIR.."/plugins/suft.lua")` at the end of wireshark/init.lua.
10 |
--------------------------------------------------------------------------------
/wireshark-plugin/suft.lua:
--------------------------------------------------------------------------------
1 | -- create suft_p protocol and its fields
2 | suft_p = Proto.new("suft","SUFT Protocol")
3 |
4 | -- ProtoField.new(name, abbr, type, [voidstring], [base], [mask], [descr])
5 | local f_margic = ProtoField.new("Magic Header", "suft.magic", ftypes.BYTES)
6 | local f_len = ProtoField.new("Length", "suft.len", ftypes.UINT16)
7 | local f_rcid = ProtoField.new("Remote ConnId", "suft.rcid", ftypes.UINT32)
8 | local f_lcid = ProtoField.new("Local ConnId", "suft.lcid", ftypes.UINT32)
9 | local f_seq = ProtoField.new("Seq", "suft.seq", ftypes.UINT32)
10 | local f_ack = ProtoField.new("Ack", "suft.ack", ftypes.UINT32)
11 | local f_flags = ProtoField.new("Flags", "suft.flags", ftypes.UINT8, nil, base.HEX)
12 | local f_flag_syn = ProtoField.new("SYN", "suft.flags.syn", ftypes.UINT8, nil, base.HEX, 1)
13 | local f_flag_ack = ProtoField.new("ACK", "suft.flags.ack", ftypes.UINT8, nil, base.HEX, 2)
14 | local f_flag_sack = ProtoField.new("SACK", "suft.flags.sack", ftypes.UINT8, nil, base.HEX, 4)
15 | local f_flag_time = ProtoField.new("TIME", "suft.flags.time", ftypes.UINT8, nil, base.HEX, 8)
16 | local f_flag_data = ProtoField.new("DATA", "suft.flags.data", ftypes.UINT8, nil, base.HEX, 16)
17 | local f_flag_reset = ProtoField.new("RESET", "suft.flags.reset", ftypes.UINT8, nil, base.HEX, 64)
18 | local f_flag_fin = ProtoField.new("FIN", "suft.flags.fin", ftypes.UINT8, nil, base.HEX, 128)
19 | local f_scnt = ProtoField.new("Sent Count", "suft.scnt", ftypes.UINT8)
20 | local f_payload = ProtoField.new("Payload", "suft.payload", ftypes.BYTES)
21 |
22 | local f_sack_tbl = ProtoField.new("SACK TBL", "suft.sack.tbl", ftypes.UINT8)
23 | local f_sack_scnt = ProtoField.new("SACK Sent Count", "suft.sack.scnt", ftypes.UINT8)
24 | local f_sack_delayed = ProtoField.new("SACK Delayed", "suft.sack.delayed", ftypes.UINT16)
25 | local f_sack_bitmap = ProtoField.new("SACK Bitmap", "suft.sack.bitmap", ftypes.UINT64, nil, base.HEX)
26 |
27 | suft_p.fields = {
28 | f_margic,f_len,f_rcid,f_lcid,f_seq,f_ack,f_flags,
29 | f_flag_syn,f_flag_ack,f_flag_sack,f_flag_time,f_flag_data,f_flag_reset,f_flag_fin,
30 | f_scnt,f_payload,f_sack_tbl,f_sack_scnt,f_sack_delayed,f_sack_bitmap,
31 | }
32 |
33 | local packet_type = {
34 | [1] = "SYN",
35 | [2] = "ACK",
36 | [3] = "SYN+ACK",
37 | [4] = "SACK",
38 | [12] = "SACK+TIME",
39 | [16] = "DATA",
40 | [128] = "FIN",
41 | [192] = "FIN+RESET",
42 | }
43 |
44 | -- suft_p dissector function
45 | function suft_p.dissector (buf, pinfo, root)
46 | -- validate packet length is adequate, otherwise quit
47 | if buf:len() < 26 then return end
48 | pinfo.cols.protocol = suft_p.name
49 |
50 | -- create subtree for suft_p
51 | local subtree = root:add(suft_p, buf())
52 | -- add protocol fields to subtree
53 | subtree:add(f_margic, buf(0,6))
54 | subtree:add(f_len, buf(6,2))
55 | subtree:add(f_rcid, buf(8,4))
56 | subtree:add(f_lcid, buf(12,4))
57 | local v_seq, v_ack = buf(16,4), buf(20,4)
58 | local t_seq = subtree:add(f_seq, v_seq)
59 | subtree:add(f_ack, v_ack)
60 |
61 | local flags = buf(24,1)
62 | local ft = subtree:add(f_flags, flags)
63 | ft:add(f_flag_syn, flags)
64 | ft:add(f_flag_ack, flags)
65 | ft:add(f_flag_sack, flags)
66 | ft:add(f_flag_time, flags)
67 | ft:add(f_flag_data, flags)
68 | ft:add(f_flag_reset, flags)
69 | ft:add(f_flag_fin, flags)
70 | local v_flag = flags:uint()
71 | local ptype = packet_type[v_flag]
72 | local v_scnt = buf(25,1)
73 | if ptype then
74 | local fmt = "[%s] seq=%u ack=%u scnt=%u"
75 | if v_flag == 1 then
76 | fmt = fmt .. " ###### New Connection ######"
77 | end
78 | pinfo.cols.info = string.format(fmt, ptype, v_seq:uint(), v_ack:uint(), v_scnt:uint())
79 | ft:append_text(string.format(" [%s]", ptype))
80 | end
81 |
82 | subtree:add(f_scnt, v_scnt)
83 | local payload = subtree:add(f_payload, buf(26))
84 | if bit32.btest(v_flag, 4) then -- sack
85 | t_seq:append_text(" [TRP]")
86 | local sack_tbl,sack_scnt,sack_delayed = buf(26,1),buf(27,1),buf(28,2)
87 | payload:add(f_sack_tbl, sack_tbl)
88 | payload:add(f_sack_scnt, sack_scnt)
89 | payload:add(f_sack_delayed, sack_delayed)
90 | local i, max_i = 0, buf:len() - 8
91 | for i=30,max_i,8 do
92 | payload:add(f_sack_bitmap, buf(i,8)):append_text(string.format(" [%u]", (i-30)/8))
93 | end
94 | elseif bit32.btest(v_flag, 16) then -- data
95 | payload:append_text(string.format(" [Len %u]", buf:len()-26))
96 | end
97 | end
98 |
99 |
100 | local dissector_table = DissectorTable.get("udp.port")
101 | dissector_table:add(9090, suft_p)
102 | dissector_table:add(9008, suft_p)
103 | dissector_table:add(5001, suft_p)
104 |
--------------------------------------------------------------------------------