├── .gitignore
├── .gitmodules
├── CMakeLists.txt
├── LICENSE
├── Makefile
├── README.md
├── cfrp.c
├── client.c
├── include
├── cbuff.h
├── cfrp.h
├── clib.h
├── clist.h
├── cmap.h
├── config.def.h
├── cqueue.h
└── logger.h
├── server.c
└── src
├── cbuff.c
├── cfrp.c
├── clib.c
├── clist.c
├── cmap.c
├── cqueue.c
└── logger.c
/.gitignore:
--------------------------------------------------------------------------------
1 | object
2 | bin
3 | cmake-build-debug
4 | .idea
5 | .vscode
6 | config.h
7 | test.c
8 | **/*.bak
9 | build
10 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "cargparser"]
2 | path = cargparser
3 | url = git@github.com:editso/cargparser.git
4 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.17)
2 | project(cfrp)
3 | include_directories(include)
4 |
5 | file(GLOB SOURCES src/*.c)
6 |
7 | add_executable(server server.c ${SOURCES})
8 |
9 | add_executable(client client.c ${SOURCES})
10 |
11 | add_executable(cfrp cfrp.c ${SOURCES})
12 |
13 | add_executable(test test.c ${SOURCES})
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 |
2 | # 头文件目录
3 | INCLUDE_PATH := include cargparser/include
4 | # 源文件目录
5 | SOURCE_PATH := src cargparser/src
6 | # 编译生成的目录
7 | BUILD_PATH := build
8 | # 可执行文件
9 | BIN := server client cfrp
10 |
11 | # 所有源文件
12 | ALL_INCLUDE := $(foreach file,$(INCLUDE_PATH),-I$(file))
13 | ALL_SOURCES := $(foreach file, $(SOURCE_PATH), $(wildcard $(file)/*.c))
14 | ALL_OBJ := $(foreach file, $(ALL_SOURCES), $(BUILD_PATH)/obj/$(file).o)
15 |
16 | # 命令
17 | CC := gcc $(ALL_INCLUDE) -std=c99
18 |
19 | all: build
20 |
21 | $(ALL_OBJ) : $(BUILD_PATH)/obj/%.o : %
22 | $(CC) -c $^ -o $@
23 |
24 | % : mkpath $(ALL_OBJ) %.c config.h
25 | $(CC) $(ALL_OBJ) $@.c -o $(BUILD_PATH)/bin/$@
26 |
27 | %.run: %.c mkpath $(ALL_OBJ)
28 | $(CC) $(ALL_OBJ) $< -o $(BUILD_PATH)/bin/$(notdir $@)
29 |
30 | .PHONY: build
31 | build: config.h $(BIN)
32 | @echo Build success!
33 | @echo build path: $(BUILD_PATH)/bin
34 |
35 | .PHONY: mkpath
36 | mkpath:
37 | @mkdir -p $(patsubst %, $(BUILD_PATH)/obj/%,$(SOURCE_PATH)) $(BUILD_PATH)/bin
38 |
39 | .PHONY:clean
40 | clean:
41 | @rm -rfv ./$(BUILD_PATH)
42 |
43 | config.h:
44 | cp include/config.def.h config.h
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 端口映射工具 cfrp
2 | 由c语言编写,代码实现非常简单并且支持多连接
3 |
4 |
5 | ## 配置
6 | 执行: `make config.h` 并修改映射参数
7 |
8 |
9 | ## 使用
10 | 执行: `make clean build`
11 | 先启动服务端在启动客户端最后进行访问
12 |
13 | # 该项目已被 [Fuso](https://github.com/editso/fuso) 替代
14 |
15 |
--------------------------------------------------------------------------------
/cfrp.c:
--------------------------------------------------------------------------------
1 | //
2 | // Created by zy on 2020/11/30.
3 | //
4 | #include
5 | #include "cfrp.h"
6 | #include "cargparser.h"
7 | #include "config.h"
8 | #include "string.h"
9 |
10 |
11 | extern void default_cmd(cargparser_args *args);
12 |
13 | extern void server_cmd(cargparser_args *args);
14 |
15 | extern void client_cmd(cargparser_args *args);
16 |
17 | int main(int argc, char **argv){
18 | cargparser_args args;
19 | struct option options[] = {
20 | {.name = "port", .keyword = {"-p","--port"}, .description = "端口号", .require = 1, .defaults="8080"},
21 | {.name = "host", .keyword = {"-h","--host"}, .description = "主机地址", .require = 1, .defaults="0.0.0.0"},
22 | {.name = "mapping-port", .keyword = {"-mp","--mapping-port"}, .description = "映射端口", .require = 1, .defaults=(void *)8080},
23 | {.name = "mapping-host", .keyword = {"-mh","--mapping-host"}, .description = "映射主机", .require = 1, .defaults="0.0.0.0"},
24 | };
25 | cargparser sub[] = {
26 | {"server", 0, 0, 0, 0, server_cmd, "cfrp server"},
27 | {"client", 0, 0, 0, 0, client_cmd, "cfrp client"},
28 | };
29 | cargparser parser = {argv[0], options, len(options), sub, len(sub), default_cmd, "cfrp proxy"};
30 | parse_main(&parser, &args, argc, argv);
31 | cargparser_call(&args);
32 | return 0;
33 | }
34 |
35 |
36 | extern void default_cmd(cargparser_args *args){
37 | printf(":port\n");
38 | char *port = get_argument(args, "port", 0);
39 | printf("port: s\n", port);
40 | }
41 |
42 |
43 | extern void server_cmd(cargparser_args *args){
44 | char *port = get_argument(args, "port", "8080");
45 | printf("port: %s\n", port);
46 | }
47 |
48 | extern void client_cmd(cargparser_args *args){
49 | printf("client\n");
50 | }
51 |
52 |
--------------------------------------------------------------------------------
/client.c:
--------------------------------------------------------------------------------
1 | #include "cfrp.h"
2 | #include "config.h"
3 |
4 |
5 | int main(){
6 | cfrp *frp = make_cfrp(client_mapping, CLIENT);
7 | cfrp_run(frp);
8 | return 0;
9 | }
10 |
--------------------------------------------------------------------------------
/include/cbuff.h:
--------------------------------------------------------------------------------
1 | #ifndef __CBUFF_H__
2 | #define __CBUFF_H__
3 |
4 |
5 | typedef struct{
6 | /**
7 | * 长度
8 | */
9 | int length;
10 | /**
11 | * 容量
12 | */
13 | unsigned int _capatity;
14 | char* _buf;
15 | }cbuff;
16 |
17 |
18 | extern cbuff* make_buff(unsigned int capatity);
19 |
20 | extern cbuff* init_buff(cbuff* buff, int capatity);
21 |
22 | extern int buff_append(cbuff* buff, char chr);
23 |
24 | extern int buff_appends(cbuff* buff, void* ptr, unsigned int size);
25 |
26 | extern char buff_get(cbuff* buff, int index);
27 |
28 | extern char* buff_cpy(cbuff* buff);
29 |
30 | extern void* buff_sub(cbuff* buff, void* dest, int begin, int end);
31 |
32 | extern int buff_recycle(cbuff* buff);
33 |
34 | #endif
--------------------------------------------------------------------------------
/include/cfrp.h:
--------------------------------------------------------------------------------
1 | #ifndef __CFRP_H__
2 | #define __CFRP_H__
3 | #include "cmap.h"
4 | #include "cqueue.h"
5 |
6 |
7 | /**
8 | * mask pos
9 | */
10 | #define MASK_1 1
11 | #define MASK_2 2
12 | #define MASK_3 3
13 |
14 | /**
15 | * state
16 | */
17 | #define GMASK1(m) m >> 30u
18 | /**
19 | * token
20 | */
21 | #define GMASK2(m) m << 2u >> 26u
22 | /**
23 | * data length
24 | */
25 | #define GMASK3(m) m & ~(~0u << 24u)
26 |
27 |
28 | #define EPOLL_SIZE 10
29 |
30 | /**
31 | * 转发消息一次性最大可发送的大小
32 | */
33 | #define CFRP_BUFF_SIZE 1024 * 1024 * 4
34 |
35 |
36 | /**
37 | * 错误
38 | */
39 | #define CFRP_ERR -1
40 | /**
41 | * 成功
42 | */
43 | #define CFRP_SUCC 1
44 |
45 | /**
46 | * 映射数量
47 | */
48 | #define MAPPER_SIZE 10
49 |
50 | /**
51 | * 等待
52 | */
53 | #define CFRP_WAIT 1
54 |
55 | /**
56 | * 断开
57 | */
58 | #define CFRP_DISCONNECT 2
59 | /**
60 | * 停止
61 | */
62 | #define CFRP_STOP 3
63 | /**
64 | * 连接
65 | */
66 | #define CFRP_CONN 4
67 | /**
68 | * 关闭映射
69 | */
70 | #define CFRP_DISMAPPER 5
71 |
72 |
73 | typedef enum{
74 | SERVER,
75 | CLIENT
76 | }c_cfrp;
77 |
78 | enum{
79 | CFRP_MESSAGE = 0x01,
80 | CFRP_POINT = 0x02,
81 | CFRP_CLOSE = 0x03
82 | };
83 |
84 | /**
85 | * 数据包信息
86 | */
87 | typedef struct{
88 | /**
89 | * 11000000 00000000 00000000 00000000
90 | * 0x00: 关闭连接
91 | * 0x01: 常规发送
92 | * 0x02: 断点续传
93 | * 0x03: 预留
94 | * 00111111 00000000 00000000 00000000
95 | * 校验信息长度
96 | * 00000000 11111111 11111111 11111111
97 | * 本次传输数据总长度
98 | */
99 | unsigned int mask;
100 | }cfrp_head;
101 |
102 | /**
103 | * 主机地址信息
104 | */
105 | typedef struct{
106 | /**
107 | * 端口号
108 | */
109 | int port;
110 | /**
111 | * 地址
112 | */
113 | char* addr;
114 | } c_peer;
115 |
116 |
117 | /**
118 | * cfrp token
119 | */
120 | typedef struct{
121 | /**
122 | * 长度
123 | */
124 | unsigned int len;
125 | /**
126 | * token信息
127 | */
128 | char *token;
129 | }cfrp_token;
130 |
131 | /**
132 | * 当socket 连接成功时包含的信息
133 | */
134 | typedef struct
135 | {
136 | int sfd;
137 | cfrp_token tok;
138 | c_peer peer;
139 | } c_sock;
140 |
141 |
142 | /**
143 | * 在传输过程中, 由于网络原因客户端发过来的数据不会一次性被接收全
144 | * 该结构体就是为了保证网络原因然数据不会出现错误
145 | * 与 cfrp_recv 配和
146 | * 数据接收状态
147 | */
148 | typedef struct{
149 | /**
150 | * 操作数
151 | * 1: 已经获得请求头
152 | * 2: 已经获得请求token
153 | */
154 | int op;
155 | /**
156 | * 请求头信息
157 | */
158 | cfrp_head head;
159 | /**
160 | * 请求附带的token信息
161 | */
162 | cfrp_token tok;
163 | }cfrp_state;
164 |
165 |
166 | /**
167 | * 映射信息
168 | */
169 | typedef struct{
170 | /**
171 | * epoll
172 | * */
173 | int efd;
174 | /**
175 | * 主机信息
176 | */
177 | c_peer peers[2];
178 | /**
179 | * 0: 映射端
180 | * 1: 连接端
181 | * 2: 服务端
182 | */
183 | c_sock sock[3];
184 | /**
185 | * server or client
186 | */
187 | c_cfrp type;
188 | /**
189 | * 所有映射信息
190 | */
191 | cmap mappings;
192 | /**
193 | * 由于网络原因,可能接收到的数据会出现不完整
194 | */
195 | cqueue cache;
196 | /**
197 | * 当前所在状态
198 | */
199 | cfrp_state state;
200 | }cfrp;
201 |
202 |
203 | /**
204 | * 由于网络原因客户端发送来过的数据可能是分段的
205 | * 使用该方法,会一直等待满足大小时才会返回数据
206 | */
207 | extern int cfrp_recv(cfrp* frp, int fd, char* buff, int size);
208 |
209 | /**
210 | * 创建一个token
211 | */
212 | extern cfrp_token* make_cfrp_token(cfrp_token* tok, unsigned int len, char* token);
213 |
214 | /**
215 | * 设置非阻塞IO
216 | */
217 | extern int setnoblocking(int fd);
218 |
219 | /**
220 | * 创建一个cfrp
221 | * @param peers
222 | * 0: 监听地址
223 | * 1: 转发地址
224 | * @param type 表示cfrp类型
225 | */
226 | extern cfrp* make_cfrp(c_peer peers[], c_cfrp type);
227 |
228 | /**
229 | * 启动服务
230 | */
231 | extern int cfrp_run(cfrp*);
232 | /**
233 | * 停止服务
234 | */
235 | extern int cfrp_stop(cfrp*);
236 |
237 | /**
238 | * 创建一个 tcp服务端
239 | */
240 | extern int make_tcp(c_peer *peer, c_sock *sock);
241 |
242 | /**
243 | * 创建一个tcp连接端
244 | */
245 | extern int make_connect(c_peer *peer, c_sock *sock);
246 |
247 | /**
248 | * 请求头信息
249 | */
250 | extern int cfrp_mask(int *_mask, unsigned int n, unsigned int b);
251 |
252 | /**
253 | * 生成一个token
254 | */
255 | extern int cfrp_gentok(char* dest, unsigned int len);
256 | #endif
--------------------------------------------------------------------------------
/include/clib.h:
--------------------------------------------------------------------------------
1 | #ifndef __CLIB_H__
2 | #define __CLIB_H__
3 |
4 | /**
5 | * 将数据设置 \0
6 | */
7 | extern void cbzero(void *s, unsigned long int size);
8 |
9 | #endif
--------------------------------------------------------------------------------
/include/clist.h:
--------------------------------------------------------------------------------
1 | #ifndef __CLIST_H__
2 | #define __CLIST_H__
3 |
4 |
5 | typedef struct _node{
6 | void* el;
7 | struct _node* prev;
8 | struct _node* next;
9 | }cnode;
10 |
11 | typedef struct{
12 | int size;
13 | cnode* head;
14 | cnode* tail;
15 | }clist;
16 |
17 | extern clist* make_list();
18 |
19 | extern int list_add(clist* list, void* el);
20 |
21 | extern void* list_remove(clist* list, int index);
22 |
23 | extern void* list_get(clist* list, int index);
24 |
25 | extern void* list_set(clist* list, int index, void* el);
26 |
27 | extern int list_insert(clist* list, int index, void* el);
28 |
29 | #endif
--------------------------------------------------------------------------------
/include/cmap.h:
--------------------------------------------------------------------------------
1 | #ifndef __CMAP_H__
2 | #define __CMAP_H__
3 | #include "clist.h"
4 |
5 | typedef struct{
6 | // map大小
7 | int size;
8 | // 容量
9 | int capacity;
10 | // 最大质数
11 | int _prime;
12 | // 元素
13 | void **_elems;
14 | }cmap;
15 |
16 |
17 | typedef struct{
18 | void* key;
19 | void* value;
20 | }cmap_elem;
21 |
22 |
23 | extern int map_init(cmap* map, int capacity);
24 |
25 | extern cmap* make_map(int capacity);
26 |
27 | /**
28 | * 添加
29 | */
30 | extern int map_put(cmap* map, void* key, void* value);
31 |
32 | /**
33 | * 删除
34 | */
35 | extern void *map_remove(cmap *map, void* key);
36 |
37 | /**
38 | * 获取
39 | */
40 | extern void *map_get(cmap *map, void* key);
41 |
42 |
43 | /**
44 | * 清空所有数据
45 | */
46 | extern void *map_clear(cmap *map);
47 |
48 | /**
49 | * 获取map所有key
50 | */
51 | extern int map_keys(cmap* map, clist* list);
52 |
53 | #endif
--------------------------------------------------------------------------------
/include/config.def.h:
--------------------------------------------------------------------------------
1 | #define BIND_ADDR "0.0.0.0"
2 | #define LOCAL_ADDR "127.0.0.1"
3 |
4 | /**
5 | * 服务端映射信息
6 | */
7 | c_peer server_mapping[] = {
8 | {8080, BIND_ADDR}, // 映射连接地址
9 | {8888, BIND_ADDR} // 实际访问地址
10 | };
11 |
12 | /**
13 | * 客户端映射信息
14 | */
15 | c_peer client_mapping[] = {
16 | {8080, BIND_ADDR}, // 服务连接地址
17 | {22, LOCAL_ADDR}, // 映射端口
18 | };
--------------------------------------------------------------------------------
/include/cqueue.h:
--------------------------------------------------------------------------------
1 | #ifndef __CQUEUE_H__
2 | #define __CQUEUE_H__
3 |
4 | /**
5 | * 队列
6 | */
7 | typedef struct{
8 | int size;
9 | int capacity;
10 | int _lp;
11 | int _cp;
12 | /**
13 | * 元素回收回调
14 | */
15 | int (*_recycle)(void *elem);
16 | void** _elems;
17 | }cqueue;
18 |
19 |
20 | /**
21 | * 创建一个cqueue
22 | */
23 | cqueue* make_queue(int size, int (*recycle)(void* el));
24 |
25 | /**
26 | * 向队列中添加一个元素
27 | */
28 | int queue_push(cqueue* queue, void* elem);
29 |
30 | /**
31 | * 弹出一个元素
32 | */
33 | void* queue_pop(cqueue* queue);
34 |
35 | /**
36 | * 是否是空的队列
37 | */
38 | int queue_empty(cqueue* queue);
39 |
40 |
41 | #endif
--------------------------------------------------------------------------------
/include/logger.h:
--------------------------------------------------------------------------------
1 | /*
2 | * @Author: your name
3 | * @Date: 1970-01-01 08:00:00
4 | * @LastEditTime: 2021-01-29 10:31:22
5 | * @LastEditors: Please set LastEditors
6 | * @Description: In User Settings Edit
7 | * @FilePath: /cfrp/include/logger.h
8 | */
9 | #ifndef __LOGGER_H__
10 | #define __LOGGER_H__
11 | #include
12 |
13 | enum{
14 | DEBUG,
15 | INFO,
16 | WARN,
17 | ERROR
18 | };
19 |
20 |
21 |
22 | // error
23 | #define LOG_ERROR(message, ...) log_out(message, ERROR, __FILE__, __func__, __LINE__, ##__VA_ARGS__)
24 |
25 | // info
26 | #define LOG_INFO(message, ...) log_out(message, INFO, __FILE__, __func__, __LINE__, ##__VA_ARGS__)
27 |
28 | // debug
29 | #define LOG_DEBUG(message, ...) log_out(message, DEBUG, __FILE__, __func__, __LINE__, ##__VA_ARGS__)
30 |
31 | // warning
32 | #define LOG_WARN(message, ...) log_out(message, WARN, __FILE__, __func__, __LINE__, ##__VA_ARGS__)
33 |
34 | extern void log_out(const char* message, const int level, const char *file,const char *func, const int line, ...);
35 |
36 | #endif
--------------------------------------------------------------------------------
/server.c:
--------------------------------------------------------------------------------
1 | #include "cfrp.h"
2 | #include "config.h"
3 |
4 | int main(){
5 | cfrp *frp = make_cfrp(server_mapping, SERVER);
6 | cfrp_run(frp);
7 | return 0;
8 | }
9 |
--------------------------------------------------------------------------------
/src/cbuff.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #include "cbuff.h"
5 | #include "clib.h"
6 |
7 | /**
8 | * 扩大容量
9 | */
10 | extern int buff_increase(cbuff* buff, int size);
11 |
12 |
13 | extern int buff_increase(cbuff* buff, int size){
14 | if(! buff || buff->length >= size) return 0;
15 | buff->_buf = realloc(buff->_buf, size);
16 | buff->_capatity = size;
17 | }
18 |
19 | extern cbuff* make_buff(unsigned int capatity){
20 | cbuff* buff = calloc(1, sizeof(cbuff));
21 | buff->_capatity = capatity <= 0 ? 1 : capatity;
22 | buff->_buf = calloc(1, sizeof(char) * buff->_capatity);
23 | buff->length = 0;
24 | }
25 |
26 | extern cbuff* init_buff(cbuff* buff, int capatity){
27 | if(! buff) return buff;
28 | cbzero(buff, sizeof(cbuff));
29 | buff->_capatity = capatity <= 0 ? 1 : capatity;
30 | buff->_buf = calloc(1, sizeof(char) * buff->_capatity);
31 | }
32 |
33 |
34 | extern int buff_append(cbuff* buff, char chr){
35 | return buff_appends(buff, &chr, sizeof(chr));
36 | }
37 |
38 | extern int buff_appends(cbuff* buff, void* ptr, unsigned int size){
39 | if(buff->length >= buff->_capatity){
40 | buff_increase(buff, buff->_capatity * 2);
41 | }
42 | memcpy(buff->_buf + buff->length, ptr, size);
43 | buff->length += size;
44 | }
45 |
46 | extern char buff_get(cbuff* buff, int index){
47 | if(! buff || buff->length <= index) return '\0';
48 | return buff->_buf[index];
49 | }
50 |
51 | extern void* buff_sub(cbuff* buff, void* dest, int begin, int end){
52 | if( ! buff || ! dest || buff->length < end || end < begin)
53 | return dest;
54 | memcpy(dest, buff->_buf + begin, end);
55 | return dest;
56 | }
57 |
58 | extern char* buff_cpy(cbuff* buff){
59 | if(! buff || buff->length <= 0) return (void *)0;
60 | char* tmp = calloc(1, sizeof(char) * buff->length);
61 | memcpy(tmp, buff->_buf, sizeof(char) * buff->length);
62 | return tmp;
63 | }
64 |
65 |
66 | extern int buff_recycle(cbuff* buff){
67 | free(buff->_buf);
68 | }
--------------------------------------------------------------------------------
/src/cfrp.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 |
12 | #include "cfrp.h"
13 | #include "logger.h"
14 | #include "cbuff.h"
15 | #include "clib.h"
16 |
17 | static const char __BASE_LATTER__[] = {
18 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
19 | 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
20 | 'u', 'v', 'w', 'x', 'y', 'z'
21 | };
22 |
23 | /**
24 | * 创建cfrp
25 | */
26 | extern cfrp* mmake_cfrp();
27 |
28 | /**
29 | * cfrp连接端
30 | */
31 | extern cfrp* make_cfrp_client(c_peer peers[]);
32 | /**
33 | * cfrp服务端
34 | */
35 | extern cfrp* make_cfrp_server(c_peer peers[]);
36 | /**
37 | * 多路复用
38 | */
39 | extern int make_epoll();
40 | /**
41 | * 启动服务端
42 | */
43 | extern int run_server(cfrp* frp);
44 | /**
45 | * 启动客户端
46 | */
47 | extern int run_client(cfrp* frp);
48 | /**
49 | * 监听socket
50 | */
51 | extern int cfrp_listen(cfrp* frp, int sfd, int op, int events, void* data);
52 | /**
53 | * 允许一个连接
54 | */
55 | extern int cfrp_accept(int fd, c_sock* sock);
56 |
57 | /**
58 | * 关闭
59 | */
60 | extern int cfrp_close(cfrp* frp, cfrp_token *tok);
61 |
62 |
63 | /**
64 | * 转发接收到的信息
65 | */
66 | extern int cfrp_recv_forward(cfrp* frp);
67 |
68 | /**
69 | * 转发发送的信息
70 | */
71 | extern int cfrp_send_forward(cfrp* frp, cfrp_token* tok);
72 |
73 | /**
74 | * 注册监听
75 | */
76 | extern cfrp_token* cfrp_register(cfrp* frp, c_sock* sock);
77 | /**
78 | * 取消注册
79 | */
80 | extern char* cfrp_unregister(cfrp* frp, c_sock* sock);
81 |
82 | extern void cfrp_clear_mappers(cfrp* frp);
83 |
84 |
85 | /**
86 | * 主机地址转换为网络地址
87 | */
88 | #define SOCK_ADDR_IN(peer) \
89 | {\
90 | .sin_family = AF_INET,\
91 | .sin_port = htons(peer->port),\
92 | .sin_addr = {.s_addr = inet_addr(peer->addr)}\
93 | }
94 |
95 |
96 | /**
97 | * 主机地址信息
98 | */
99 | #define SOCK_PEER(__addr, peer)\
100 | peer.port = ntohs((__addr)->sin_port);\
101 | peer.addr = inet_ntoa((__addr)->sin_addr);\
102 |
103 |
104 | /**
105 | * sockaddr_in to sockaddr
106 | *
107 | */
108 | #define SOCKADDR(addr) (struct sockaddr*)addr
109 |
110 | /**
111 | * epoll_event data
112 | */
113 | typedef struct{
114 | int sfd;
115 | void *ptr;
116 | }cfrp_epoll_data;
117 |
118 |
119 | /**
120 | * epoll 水平触发可读事件
121 | */
122 | #define CFRP_EPOLL_EVENT EPOLLET|EPOLLIN
123 |
124 | #define __DEF_EPOLL_EVENT__(__vname, __events, __data) \
125 | struct epoll_event __vname;\
126 | __vname.events = __events;\
127 | __vname.data.ptr = __data;
128 |
129 | #define __DEF_EPOLL_WAIT__(__vname, efd, __events,__max, __timeout) \
130 | if(efd == -1) break;\
131 | int __vname = epoll_wait(efd, __events, __max, __timeout);
132 |
133 | /**
134 | * 向epoll中注册一个事件
135 | */
136 | #define EPOLL_ADD(__frp, __sfd, __data) cfrp_listen(__frp, __sfd, EPOLL_CTL_ADD, CFRP_EPOLL_EVENT, __data)
137 | /**
138 | * 重新注册
139 | */
140 | #define EPOLL_MOD(__frp, __sfd, __ev) epoll_ctl(__frp->efd, EPOLL_CTL_MOD, __sfd, __ev)
141 | /**
142 | * 删除事件
143 | */
144 | #define EPOLL_DEL(__frp, __sfd, __ev) epoll_ctl(__frp->efd, EPOLL_CTL_DEL, __sfd, __ev)
145 |
146 | /**
147 | * 监听
148 | */
149 | #define LISTEN\
150 | for(;;)
151 |
152 | /**
153 | * 循环
154 | */
155 | #define LOOP\
156 | for(;;)
157 |
158 | /**
159 | * 处理epoll 事件
160 | */
161 | #define HANDLER_EPOLL_EVENT(count, ev, data, __events) \
162 | ev = __events[0];\
163 | data = ev.data.ptr;\
164 | for (int i = 0; i < count; ev = __events[++i], data = ev.data.ptr)
165 |
166 | /**
167 | * 对于服务端这是访问端
168 | * 对于连接端这是被访问端
169 | */
170 | #define CFRP_RFD(frp) (frp->sock + 1)->sfd
171 |
172 | /**
173 | * 对于服务端这是映射连接端
174 | * 对于连接端这是连接到服务端
175 | */
176 | #define CFRP_LFD(frp) frp->sock->sfd
177 |
178 | /**
179 | * 设置cfrp转发头mask
180 | */
181 | #define HEAD_MASK(__head, v, p) cfrp_mask(&(__head)->mask, v, p)
182 |
183 |
184 | /**
185 | * 设置非阻塞IO
186 | */
187 | extern int setnoblocking(int fd){
188 | int flag;
189 | if((flag = fcntl(fd, F_GETFL, 0)) < 0){
190 | return CFRP_ERR;
191 | }
192 | if(fcntl(fd, F_SETFL, flag | O_NONBLOCK) < 0){
193 | return CFRP_ERR;
194 | }
195 | return CFRP_SUCC;
196 | }
197 |
198 |
199 | extern int cfrp_mask(int *_mask, unsigned int n, unsigned int b){
200 | if(! _mask) return 0;
201 | unsigned int m = *_mask;
202 | if(m < 0) m = 0;
203 | if(b == MASK_1){
204 | // 11000000 00000000 00000000 00000000
205 | *_mask = (0 << 31 | n > 3 || n == 3 ? 3 << 30 : n << 30) | (m & ~(~0 << 30));
206 | }else if(b == MASK_2){
207 | // 00111111 00000000 00000000 000000000
208 | *_mask = (n > ~(~0 << 6) ? ~(~0 << 6) : n) << 24 | GMASK1(m) << 30 | GMASK3(m);
209 | }else if (b == MASK_3)
210 | {
211 | // 00000000 11111111 11111111 11111111
212 | *_mask = ~(0 << 8) << 24 & m | ( n > ~(~0 << 24) ? ~(~0 << 24): n );
213 | }else{
214 | return 0;
215 | }
216 | return 1;
217 | }
218 |
219 |
220 | extern cfrp* mmake_cfrp(){
221 | cfrp* frp = (cfrp*)malloc(sizeof(cfrp));
222 | cbzero(frp, sizeof(cfrp));
223 | map_init(&frp->mappings, 27);
224 | cbzero(&frp->cache, sizeof(cqueue));
225 | frp->cache.capacity = 5;
226 | frp->cache._elems = calloc(frp->cache.capacity, sizeof(void *));
227 | frp->state.op = 0;
228 | return frp;
229 | }
230 |
231 |
232 | extern int make_epoll(){
233 | int efd = epoll_create(EPOLL_SIZE);
234 | if(efd < 0) return CFRP_ERR;
235 | return efd;
236 | }
237 |
238 | /**
239 | * server
240 | */
241 | extern cfrp* make_cfrp_server(c_peer peers[]){
242 | cfrp* frp = mmake_cfrp();
243 | memcpy(frp->peers, peers, sizeof(c_peer) * 2);
244 | if( make_tcp(peers, frp->sock) == CFRP_ERR ||
245 | make_tcp((peers + 1), frp->sock + 1) == CFRP_ERR ){
246 | perror("cfrp make error");
247 | exit(1);
248 | }
249 | if( setnoblocking(CFRP_LFD(frp)) == CFRP_ERR ||
250 | setnoblocking(CFRP_RFD(frp)) == CFRP_ERR ){
251 | perror("cfrp set noblocking error");
252 | exit(1);
253 | }
254 | if ( (frp->efd = make_epoll()) == CFRP_ERR){
255 | perror("cfrp epoll error");
256 | exit(0);
257 | }
258 | if(EPOLL_ADD(frp, CFRP_LFD(frp), NULL) < 0 ||
259 | EPOLL_ADD(frp, CFRP_RFD(frp), NULL) < 0){
260 | perror("epoll error");
261 | exit(1);
262 | }
263 | return frp;
264 | }
265 |
266 | /**
267 | * client
268 | */
269 | extern cfrp* make_cfrp_client(c_peer peers[]){
270 | cfrp* frp = mmake_cfrp();
271 | memcpy(frp->peers, peers, sizeof(c_peer) * 2);
272 | if( make_connect(peers, frp->sock) == CFRP_ERR ||
273 | setnoblocking(CFRP_LFD(frp)) == CFRP_ERR ||
274 | (frp->efd = make_epoll()) == CFRP_ERR){
275 | perror("cfrp make error");
276 | exit(1);
277 | }
278 | if(EPOLL_ADD(frp, CFRP_LFD(frp), NULL) < 0){
279 | perror("epoll error");
280 | exit(1);
281 | }
282 | return frp;
283 | }
284 |
285 | /**
286 | * 创建一个cfrp
287 | * @param peers
288 | * 0: 监听地址
289 | * 1: 转发地址
290 | * @param type 表示cfrp类型
291 | */
292 | extern cfrp* make_cfrp(c_peer peers[], c_cfrp type){
293 | cfrp* frp;
294 | if(type == SERVER)
295 | frp = make_cfrp_server(peers);
296 | else
297 | frp = make_cfrp_client(peers);
298 | frp->type = type;
299 | return frp;
300 | }
301 |
302 |
303 | extern int run_server(cfrp* frp){
304 | int rfd = CFRP_RFD(frp), lfd = CFRP_LFD(frp), mfd = -1, cfd = -1;
305 | struct epoll_event events[5], ev;
306 | cfrp_epoll_data* data;
307 | c_sock sock;
308 | cfrp_token* tok;
309 | LOG_INFO("server started !\nMapping: [%s:%d]:%d->[%s:%d]:%d",
310 | frp->sock[1].peer.addr,
311 | frp->sock[1].peer.port,
312 | frp->sock[1].sfd,
313 | frp->sock->peer.addr,
314 | frp->sock->peer.port,
315 | frp->sock->sfd);
316 | LISTEN{
317 | __DEF_EPOLL_WAIT__(c, frp->efd, events, 5, -1);
318 | mfd = frp->sock[2].sfd;
319 | cbzero(&sock, sizeof(c_sock));
320 | HANDLER_EPOLL_EVENT(c, ev, data, events){
321 | cfd = data->sfd;
322 | tok = data->ptr;
323 | if(cfd == rfd || cfd == lfd){
324 | if( cfrp_accept(cfd, &sock) == CFRP_ERR ||
325 | setnoblocking(sock.sfd) == CFRP_ERR){
326 | perror("cfrp accept error");
327 | continue;
328 | }
329 | tok = cfrp_register(frp, &sock);
330 | if(cfd == rfd && mfd <= 0 || cfd == lfd && mfd > 0){
331 | /**
332 | * 被映射端还没有连接或者被映射端已经被占用, 拒绝连接
333 | */
334 | cfrp_close(frp, tok);
335 | continue;
336 | }else if(cfd == lfd){
337 | /**
338 | * 被映射端连接,
339 | */
340 | LOG_INFO("client connect: %d", sock.sfd);
341 | memcpy(frp->sock + 2, &sock, sizeof(c_sock));
342 | }else{
343 | /**
344 | * 注册监听并生产一个唯一标识
345 | */
346 | LOG_INFO("register mapping");
347 | }
348 | }else{
349 | int s = CFRP_CONN;
350 | if(mfd == cfd){
351 | LOG_INFO("recv forward");
352 | s = cfrp_recv_forward(frp);
353 | }else{
354 | LOG_INFO("send forward");
355 | s = cfrp_send_forward(frp, tok);
356 | }
357 | if(s == CFRP_DISCONNECT || s == CFRP_STOP){
358 | cfrp_close(frp, tok);
359 | continue;
360 | }
361 | }
362 | EPOLL_MOD(frp, cfd, &ev);
363 | }
364 | }
365 | return 1;
366 | }
367 |
368 |
369 | /**
370 | * 启动客户端
371 | */
372 | extern int run_client(cfrp* frp){
373 | struct epoll_event events[10], ev;
374 | cfrp_epoll_data *data;
375 | cfrp_token* tok;
376 | int cfd = -1, lfd = -1;
377 | LISTEN{
378 | __DEF_EPOLL_WAIT__(c, frp->efd, events, 5, -1);
379 | lfd = CFRP_LFD(frp);
380 | HANDLER_EPOLL_EVENT(c, ev, data, events){
381 | cfd = data->sfd;
382 | tok = data->ptr;
383 | int s;
384 | if(cfd == lfd){
385 | LOG_INFO("recv server message");
386 | /**
387 | * 服务端传来了数据需要将数据解析然后转发的目标地址
388 | */
389 | s = cfrp_recv_forward(frp);
390 | }else{
391 | /**
392 | * 映射端传来了数据, 打包发送给服务端
393 | */
394 | s = cfrp_send_forward(frp, tok);
395 | }
396 |
397 | if( s == CFRP_STOP ){
398 | cfrp_stop(frp);
399 | }else if(s == CFRP_DISCONNECT || s == CFRP_DISMAPPER){
400 | cfrp_close(frp, tok);
401 | }else{
402 | EPOLL_MOD(frp, cfd, &ev);
403 | }
404 | }
405 | }
406 | return 1;
407 | }
408 |
409 | /**
410 | * 启动服务
411 | */
412 | extern int cfrp_run(cfrp* frp){
413 | int pid = vfork();
414 | if(pid < 0){
415 | printf("fork child process err");
416 | exit(1);
417 | }else if (pid == 0){
418 | if(frp->type == SERVER){
419 | run_server(frp);
420 | }else{
421 | run_client(frp);
422 | }
423 | exit(0);
424 | }
425 | return 1;
426 | }
427 |
428 |
429 | /**
430 | * 停止服务
431 | */
432 | extern int cfrp_stop(cfrp* frp){
433 | if(frp->type == CLIENT){
434 | cfrp_clear_mappers(frp);
435 | close(frp->sock->sfd);
436 | }
437 | frp->efd = -1;
438 | LOG_INFO("cfrp stop, code: %d, message: %s", errno, strerror(errno));
439 | return 1;
440 | }
441 |
442 | /**
443 | * 创建一个 tcp服务端
444 | */
445 | extern int make_tcp(c_peer *peer, c_sock *sock){
446 | int fd = -1;
447 | int val = 1;
448 | struct sockaddr_in addr = SOCK_ADDR_IN(peer);
449 | if( (fd= socket(AF_INET, SOCK_STREAM, 0)) < 0 ||
450 | setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(int)) < 0 ||
451 | bind(fd, SOCKADDR(&addr), sizeof(struct sockaddr_in)) < 0 ||
452 | listen(fd, 10) < 0 ){
453 | perror("make tcp error");
454 | return CFRP_ERR;
455 | }
456 | sock->sfd = fd;
457 | sock->peer.addr = peer->addr;
458 | sock->peer.port = peer->port;
459 | return CFRP_SUCC;
460 | }
461 |
462 | /**
463 | * 创建一个tcp连接端
464 | */
465 | extern int make_connect(c_peer* peer, c_sock *sock){
466 | if(! peer) return CFRP_ERR;
467 | int fd = -1;
468 | struct sockaddr_in addr = SOCK_ADDR_IN(peer);
469 | if( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ||
470 | connect(fd, SOCKADDR(&addr), sizeof(struct sockaddr)) < 0 ){
471 | return CFRP_ERR;
472 | }
473 | sock->sfd = fd;
474 | sock->peer.addr = peer->addr;
475 | sock->peer.port = peer->port;
476 | LOG_INFO("connected: [%s:%d], fd: %d", peer->addr, peer->port, fd);
477 | return fd;
478 | }
479 |
480 | extern int cfrp_listen(cfrp* frp, int sfd, int op, int events, void* _data){
481 | cfrp_epoll_data *data = malloc(sizeof(cfrp_epoll_data));
482 | data->sfd = sfd;
483 | data->ptr = _data;
484 | __DEF_EPOLL_EVENT__(ev, events, data);
485 | if(epoll_ctl(frp->efd, op, sfd, &ev) < 0 )
486 | return CFRP_ERR;
487 | return CFRP_SUCC;
488 | }
489 |
490 | extern int cfrp_accept(int fd, c_sock* sock){
491 | cbzero(sock, sizeof(c_sock));
492 | int afd = -1;
493 | struct sockaddr_in addr;
494 | socklen_t len = sizeof(struct sockaddr_in);
495 | if((afd = accept(fd, SOCKADDR(&addr), &len)) < 0)
496 | return CFRP_ERR;
497 | SOCK_PEER(&addr, sock->peer);
498 | sock->sfd = afd;
499 | return CFRP_SUCC;
500 | }
501 |
502 |
503 | extern int cfrp_recv(cfrp* frp, int fd, char* buff, int size){
504 | if(size <= 0) return CFRP_ERR;
505 | char mbuff[size];
506 | cbuff* mcache = queue_pop(&frp->cache);
507 | if(! mcache)
508 | mcache = make_buff(size);
509 | int l = recv(fd, mbuff, size - mcache->length, 0);
510 | if(l == -1 && errno == EAGAIN){
511 | return CFRP_WAIT;
512 | }else if(l == 0 && errno == EAGAIN || l == 0){
513 | return CFRP_ERR;
514 | }
515 | buff_appends(mcache, mbuff, l);
516 | LOG_INFO("total: %d, current: %d, sub: %d", size, l, size - mcache->length);
517 | if(mcache->length != size){
518 | queue_push(&frp->cache, mcache);
519 | return CFRP_WAIT;
520 | }
521 | buff_sub(mcache, buff, 0, size);
522 | // 回收内存
523 | buff_recycle(mcache);
524 | free(mcache);
525 | return size;
526 | }
527 |
528 | /**
529 | * 转发接收到的信息
530 | */
531 | extern int cfrp_recv_forward(cfrp* frp){
532 | cfrp_state* state = &frp->state;
533 | cfrp_head *head = &frp->state.head;
534 | cfrp_token *tok = &state->tok;
535 | int sfd, l, hl, cl, *st, r, sl;
536 | sfd = frp->type == SERVER ? frp->sock[2].sfd : frp->sock->sfd;
537 | char buff[CFRP_BUFF_SIZE];
538 | hl = sizeof(cfrp_head), cl = hl, st = &frp->state.op;
539 | LOOP{
540 | if(*st == 0){
541 | cl = hl;
542 | cbzero(head, hl);
543 | free(tok->token);
544 | cbzero(tok, sizeof(cfrp_token));
545 | }
546 | r = CFRP_SUCC;
547 | cbzero(buff, CFRP_BUFF_SIZE);
548 | if(*st == 1){
549 | cl = GMASK2(head->mask);
550 | }else if(*st == 2){
551 | cl = GMASK3(head->mask);
552 | }
553 | if((l = cfrp_recv(frp, sfd, buff, cl)) == CFRP_ERR){
554 | r = CFRP_STOP;
555 | break;
556 | }else if (l == CFRP_WAIT){
557 | break;
558 | }
559 | LOG_DEBUG("recv size: expected: %d, current: %d, p: %d", cl, l, *st);
560 | if(*st == 0){
561 | memcpy(head, buff, cl);
562 | if(GMASK1(head->mask) == 0x00){
563 | LOG_DEBUG("header error");
564 | r = CFRP_STOP;
565 | break;
566 | }
567 | (*st)++;
568 | }else if(*st == 1){
569 | tok->len = cl;
570 | tok->token = calloc(cl, sizeof(char));
571 | memcpy(tok->token, buff, cl);
572 | LOG_DEBUG("token: %s, length: %d", tok->token, cl);
573 | if(GMASK1(head->mask) == CFRP_CLOSE){
574 | cfrp_close(frp, &frp->state.tok);
575 | *st = 0;
576 | break;
577 | }
578 | (*st)++;
579 | }else{
580 | c_sock* sock = map_get(&frp->mappings, tok->token);
581 | /**
582 | * 判断是客户端还是服务端, 如果是客户端并且没有对应的映射信息那么创建一个新的
583 | */
584 | if(frp->type == CLIENT && !sock){
585 | sock = calloc(1, sizeof(c_sock));
586 | if( make_connect(frp->peers + 1, sock) != CFRP_ERR &&
587 | setnoblocking(sock->sfd) != CFRP_ERR){
588 | // 与服务端 token 同步
589 | make_cfrp_token(&sock->tok, tok->len, tok->token);
590 | cfrp_register(frp, sock);
591 | }else{
592 | free(sock);
593 | sock = (void*)0;
594 | }
595 | }
596 | LOG_DEBUG("forward: [%s:%d], fd: %d", sock->peer.addr, sock->peer.port, sock->sfd);
597 | if(!sock || (sl = send(sock->sfd, buff, l, 0)) < 0){
598 | r = CFRP_DISMAPPER;
599 | break;
600 | }
601 | LOG_DEBUG("send: total: %d, current: %d", l, sl);
602 | *st = 0;
603 | }
604 | }
605 | return r;
606 | }
607 |
608 |
609 | extern int cfrp_send_forward(cfrp* frp, cfrp_token* tok){
610 | cfrp_head head;
611 | c_sock* sock = map_get(&frp->mappings, tok->token);
612 | char buff[CFRP_BUFF_SIZE];
613 | int hs, bs, sfd, tfd, l, r, sl, total;
614 | hs = sizeof(cfrp_head); sfd = sock->sfd; bs = sizeof(buff);
615 | tfd = frp->type == SERVER ? frp->sock[2].sfd : frp->sock->sfd;
616 | LOOP{
617 | r = CFRP_SUCC;
618 | cbzero(&head, hs);
619 | cbzero(buff, bs);
620 | l = recv(sfd, buff, bs, 0);
621 | if( l == -1 && errno == EAGAIN){
622 | r = CFRP_WAIT;
623 | break;
624 | }else if(l == 0 && errno == EAGAIN){
625 | r = CFRP_DISCONNECT;
626 | break;
627 | }
628 | HEAD_MASK(&head, 0x01, MASK_1);
629 | HEAD_MASK(&head, tok->len, MASK_2);
630 | HEAD_MASK(&head, l, MASK_3);
631 | total = l + hs + tok->len;
632 | char sbuff[total];
633 | memcpy(sbuff, &head, hs);
634 | memcpy(sbuff + hs, tok->token, tok->len);
635 | memcpy(sbuff + hs + tok->len, buff, l);
636 | LOG_DEBUG("forward size: head: %d, token: %d, body: %d, total: %d", hs, tok->len, l, total);
637 | if((sl = send(tfd, sbuff, total, 0)) < 0){
638 | r = CFRP_DISCONNECT;
639 | break;
640 | }
641 | LOG_DEBUG("send: total: %d, current: %d", total, sl);
642 | }
643 | if(r == CFRP_SUCC)
644 | LOG_INFO("forward success");
645 | else
646 | LOG_ERROR("forward error, code: %d, message: %s", errno, strerror(errno));
647 | return r;
648 | }
649 |
650 |
651 | extern int cfrp_gentok(char* dest, unsigned int max){
652 | max = max < 10 ? 10: max;
653 | char buff[max], chr;
654 | int i = 0;
655 | // srand((unsigned)time((void *)0));
656 | for(; i < max; i++){
657 | if(rand() % 2){
658 | chr = __BASE_LATTER__[rand() % 26];
659 | chr = rand() % 2 ? chr - 32 : chr;
660 | buff[i] = chr;
661 | }else{
662 | buff[i] = chr = rand() % 9 + '0';
663 | }
664 | }
665 | cbzero(dest, max);
666 | memcpy(dest, buff, i);
667 | return CFRP_SUCC;
668 | }
669 |
670 |
671 | extern cfrp_token* cfrp_register(cfrp* frp, c_sock* sock){
672 | c_sock* msock = malloc(sizeof(c_sock));
673 | memcpy(msock, sock, sizeof(c_sock));
674 | if(frp->type == SERVER){
675 | char token[18];
676 | srand((unsigned)time((void *)0));
677 | do{
678 | cfrp_gentok(token, 18);
679 | printf("token: %s\n", token);
680 | } while (map_get(&frp->mappings, token));
681 | make_cfrp_token(&msock->tok, 18u, token);
682 | }
683 | map_put(&frp->mappings, msock->tok.token, msock);
684 | EPOLL_ADD(frp, sock->sfd, &msock->tok);
685 | return &msock->tok;
686 | }
687 |
688 |
689 | extern int cfrp_close(cfrp* frp, cfrp_token* tok){
690 | if(! tok) return 0;
691 | c_sock *sock = map_remove(&frp->mappings, tok->token);
692 | if(! sock) return 0;
693 | int r = CFRP_SUCC;
694 | LOG_DEBUG("close connect: fd: %d", sock->sfd);
695 | if(frp->sock[2].sfd == sock->sfd || frp->sock->sfd == sock->sfd){
696 | cfrp_clear_mappers(frp);
697 | if(frp->type == SERVER)
698 | cbzero(frp->sock + 2, sizeof(c_sock));
699 | else if (frp->type == CLIENT)
700 | cbzero(frp->sock, sizeof(c_sock));
701 | }else if(frp->type == SERVER){
702 | // 服务端通知连接端关闭
703 | cbuff buff;
704 | init_buff(&buff, sizeof(cfrp_head) + tok->len);
705 | cfrp_head head;
706 | HEAD_MASK(&head, CFRP_CLOSE, MASK_1);
707 | HEAD_MASK(&head, tok->len, MASK_2);
708 | buff_appends(&buff, &head, sizeof(cfrp_head));
709 | buff_appends(&buff, tok->token, tok->len);
710 | send(frp->sock[2].sfd, buff._buf, buff.length, 0);
711 | buff_recycle(&buff);
712 | }
713 | EPOLL_DEL(frp, sock->sfd, NULL);
714 | if(shutdown(sock->sfd, SHUT_RDWR) < 0 || close(sock->sfd))
715 | r = CFRP_ERR;
716 | free(sock->tok.token);
717 | free(sock);
718 | return r;
719 | }
720 |
721 | extern void cfrp_clear_mappers(cfrp* frp){
722 | LOG_DEBUG("clear mappings");
723 | clist list;
724 | cbzero(&list, sizeof(clist));
725 | map_keys(&frp->mappings, &list);
726 | c_sock *sock;
727 | for(int i = 0; i < list.size; i++){
728 | sock = map_remove(&frp->mappings, list_get(&list, i));
729 | if(! sock &&
730 | sock->sfd == CFRP_RFD(frp) ||
731 | sock->sfd == CFRP_LFD(frp) ||
732 | sock->sfd == frp->sock[2].sfd) continue;
733 | EPOLL_DEL(frp, sock->sfd, NULL);
734 | shutdown(sock->sfd, SHUT_RDWR);
735 | close(sock->sfd);
736 | free(sock->tok.token);
737 | free(sock);
738 | }
739 | }
740 |
741 |
742 | extern cfrp_token* make_cfrp_token(cfrp_token* tok, unsigned int len, char* token){
743 | if(! tok) tok = calloc(1, sizeof(cfrp_token));
744 | tok->len = len;
745 | tok->token = calloc(len, sizeof(char));
746 | memcpy(tok->token, token, len);
747 | return tok;
748 | }
--------------------------------------------------------------------------------
/src/clib.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "clib.h"
4 |
5 | extern void cbzero(void *s, unsigned long int size){
6 | memset(s, '\0', size);
7 | }
--------------------------------------------------------------------------------
/src/clist.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #include "clist.h"
5 | #include "clib.h"
6 |
7 |
8 | extern cnode* make_node(void* el);
9 |
10 | extern cnode* get_node(clist* list, int index);
11 |
12 | extern cnode* get_node(clist* list, int index){
13 | if(index < 0 || index >= list->size) return (void *)0;
14 | int i = 0;
15 | for(cnode* node = list->head; node ; node = node->next, i++){
16 | if(i == index) return node;
17 | }
18 | return (void *)0;
19 | }
20 |
21 | extern cnode* make_node(void* el){
22 | cnode* node = malloc(sizeof(cnode));
23 | cbzero(node, sizeof(cnode));
24 | node->el = el;
25 | return node;
26 | }
27 |
28 | extern clist* make_list(){
29 | clist* list = malloc(sizeof(clist));
30 | cbzero(list, sizeof(clist));
31 | return list;
32 | }
33 |
34 | extern int list_add(clist* list, void* el){
35 | if(! el) return 0;
36 | cnode* node = make_node(el);
37 | // 如果头为空说明是第一次插入,直接插入到头
38 | if(! list->head){
39 | list->head = node;
40 | }else{
41 | // 否则直接添加到尾
42 | list->tail->next = node;
43 | node->prev = list->tail;
44 | }
45 | // 更新尾
46 | list->tail = node;
47 | list->size++;
48 | return 1;
49 | }
50 |
51 |
52 | extern void* list_remove(clist* list, int index){
53 | cnode* node = get_node(list, index);
54 | if(! node )
55 | return (void*)0;
56 | // 被删除的上一个
57 | cnode* prev = node->prev;
58 | // 如果有
59 | if(prev){
60 | prev->next = node->next;
61 | }else{
62 | // 没有说明是头直接更新
63 | prev = list->head = node->next;
64 | }
65 | // 更新被删除的下一个,如果有
66 | if(prev->next){
67 | prev->next->prev = prev;
68 | }
69 | // 如果删除的的是尾,更新尾巴
70 | if(list->tail == node)
71 | list->tail = prev->next;
72 | void* el = node->el;
73 | list->size--;
74 | // 释放空间
75 | free(node);
76 | return el;
77 | }
78 |
79 |
80 | extern void* list_get(clist* list, int index){
81 | cnode* node = get_node(list, index);
82 | return node ? node->el : (void *)0;
83 | }
84 |
85 | extern void* list_set(clist* list, int index, void* el){
86 | cnode* node = get_node(list, index);
87 | if(! node )
88 | return (void *)0;
89 | void* _el = node->el;
90 | node->el = el;
91 | return _el;
92 | }
93 |
94 |
95 | extern int list_insert(clist* list, int index, void* el){
96 | cnode* node = get_node(list, index);
97 | // 如果没有直接插入到尾部
98 | if(! node){
99 | return list_add(list, el);
100 | }else{
101 | // 否则进行插入
102 | cnode* inode = make_node(el);
103 | // 更新node的上一个元素对应的下一个指向
104 | if(node->prev){
105 | node->prev->next = inode;
106 | }else{
107 | // 不如果node->prev没有,则说明是头直接进行更新
108 | list->head = inode;
109 | }
110 | inode->next = node;
111 | node->prev = inode;
112 | list->size++;
113 | }
114 | return 1;
115 | }
--------------------------------------------------------------------------------
/src/cmap.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "cmap.h"
6 | #include "clib.h"
7 |
8 |
9 | extern int get_max_prime(int num);
10 |
11 | extern unsigned int map_hash(cmap* map, void* key);
12 |
13 | extern int map_hash_fun(cmap* map, void *key);
14 |
15 | extern cmap_elem* make_map_elem(void* key, void* value);
16 |
17 | extern cmap_elem* make_map_elem(void* key, void* value){
18 | cmap_elem *el = malloc(sizeof(cmap_elem));
19 | el->key = key;
20 | el->value = value;
21 | return el;
22 | }
23 |
24 |
25 | unsigned int map_hash(cmap* map, void* key){
26 | char *s = (char *)key;
27 | unsigned int val = 0;
28 | while (*s != '\0')
29 | val += (val << 4) + *s++;
30 | return val;
31 | }
32 |
33 | int map_hash_fun(cmap* map, void* key){
34 | return map_hash(map, key) % map->_prime;
35 | }
36 |
37 |
38 | extern int get_max_prime(int num){
39 | for (int i = num; i > 2; --i) {
40 | for (int j = 2; j < i && i % j != 0; ++j) {
41 | if (j == i - 1)
42 | return i;
43 | }
44 | }
45 | return 2;
46 | }
47 |
48 | extern cmap* make_map(int capacity){
49 | capacity = capacity < 2 ? 2 : capacity;
50 | cmap* map = malloc(sizeof(cmap));
51 | map_init(map, capacity);
52 | return map;
53 | }
54 |
55 |
56 | extern int map_init(cmap* map, int capacity){
57 | if(! map)return -1;
58 | cbzero(map, sizeof(cmap));
59 | map->capacity = capacity;
60 | map->_elems = malloc( sizeof(clist) * capacity);
61 | map->_prime = get_max_prime(capacity);
62 | cbzero(map->_elems, sizeof(sizeof(clist) * capacity));
63 | }
64 |
65 | /**
66 | * 添加
67 | */
68 | extern int map_put(cmap* map, void* key, void* value){
69 | int index = map_hash_fun(map, key);
70 | unsigned long hash = map_hash(map, key);
71 | clist *list = map->_elems[index];
72 | if(!list) list = map->_elems[index] = make_list();
73 | cmap_elem *tmp;
74 | for( cnode *node = list->head; node; node = node->next ){
75 | tmp = node->el;
76 | if(map_hash(map, tmp->key) == hash){
77 | tmp->value = value;
78 | return 1;
79 | }
80 | }
81 | if(! list_add(list, make_map_elem(key, value))) return -1;
82 | map->size++;
83 | return 1;
84 | }
85 |
86 |
87 | /**
88 | * 删除
89 | */
90 | extern void *map_remove(cmap *map, void* key){
91 | if(! key) return (void*)0;
92 | unsigned int hash = map_hash(map, key);
93 | clist* list = map->_elems[ map_hash_fun(map, key) ];
94 | if( ! list) return (void*)0;
95 | cmap_elem* el;
96 | for(cnode *node = list->head; node ; node = node->next){
97 | el = node->el;
98 | if(map_hash(map, el->key) == hash){
99 | if(node->prev){
100 | node->prev->next = node->next;
101 | }else{
102 | list->head = node->next;
103 | }
104 | if(node->next){
105 | node->next->prev = node->prev;
106 | }
107 | void* value = el->value;
108 | free(el);
109 | list->size--;
110 | map->size--;
111 | return value;
112 | }
113 | }
114 | return (void *)0;
115 | }
116 |
117 |
118 | /**
119 | * 获取
120 | */
121 | extern void *map_get(cmap *map, void* key){
122 | if(! key) return (void*) 0;
123 | unsigned int hash = map_hash(map, key);
124 | clist *list = map->_elems[ map_hash_fun(map, key) ];
125 | if( ! list) return (void *) 0;
126 | cmap_elem *el;
127 | for(cnode *node = list->head; node; node = node->next){
128 | el = node->el;
129 | if(map_hash(map, el->key) == hash){
130 | return el->value;
131 | }
132 | }
133 | return (void*)0;
134 | }
135 |
136 |
137 | extern int map_keys(cmap* map, clist* list){
138 | if(! list) return 0;
139 | clist* tmp = (void*)0;
140 | cmap_elem *el;
141 | for(int i = 0; i < map->capacity; i++){
142 | tmp = map->_elems[i];
143 | if(! tmp) continue;
144 | for(cnode *node = tmp->head; node; node = node->next){
145 | el = node->el;
146 | list_add(list, el->key);
147 | }
148 | }
149 | return 1;
150 | }
--------------------------------------------------------------------------------
/src/cqueue.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "cqueue.h"
4 | #include "clib.h"
5 |
6 | /**
7 | * 创建一个固定容量的 queue
8 | */
9 | cqueue* make_queue(int size, int (*recycle)(void* el)){
10 | cqueue* queue = malloc(sizeof(cqueue));
11 | cbzero(queue, sizeof(cqueue));
12 | queue->capacity = size;
13 | queue->_elems = malloc(sizeof(void *) * size);
14 | queue->_recycle = recycle;
15 | return queue;
16 | }
17 |
18 | /**
19 | * 向队列中添加一个元素
20 | */
21 | int queue_push(cqueue* cqueue, void* elem){
22 | if(cqueue->size >= cqueue->capacity){
23 | void* el = queue_pop(cqueue);
24 | if(el && cqueue->_recycle){
25 | cqueue->_recycle(el);
26 | }
27 | cqueue->_elems[cqueue->_lp] = elem;
28 | }else{
29 | cqueue->_elems[cqueue->_lp++] = elem;
30 | }
31 | if(cqueue->_lp >= cqueue->capacity)
32 | cqueue->_lp = 0;
33 | cqueue->size++;
34 | return 1;
35 | }
36 |
37 | /**
38 | * 弹出一个元素
39 | */
40 | void* queue_pop(cqueue* cqueue){
41 | if(cqueue->size <= 0)
42 | return (void*) 0;
43 | int index = cqueue->_cp;
44 | if(++cqueue->_cp >= cqueue->capacity){
45 | cqueue->_cp = 0; // 重置指针
46 | }
47 | cqueue->size--;
48 | return cqueue->_elems[index];
49 | }
50 |
51 | /**
52 | * 是否是空的队列
53 | */
54 | int queue_empty(cqueue* queue){
55 | return queue->size <= 0;
56 | }
57 |
--------------------------------------------------------------------------------
/src/logger.c:
--------------------------------------------------------------------------------
1 | #include "logger.h"
2 | #include "stdio.h"
3 |
4 | /**
5 | * 简单输出...
6 | */
7 | extern void log_out(const char* message, const int level, const char *file,const char *func, const int line, ...){
8 | va_list arg;
9 | va_start(arg, line);
10 | char buff[1024];
11 | vsnprintf(buff, sizeof(buff), message, arg);
12 | va_end(arg);
13 | printf("%s:%d[%s]: %s\n", file, line, func, buff);
14 | }
--------------------------------------------------------------------------------