├── .gitignore
├── LICENSE
├── README.md
├── assets
└── fcatalog.conf
├── catalog1
├── Makefile
├── catalog1.c
├── catalog1.h
└── test_catalog1.c
├── fcatalog
├── README.md
├── fcatalog
│ ├── __init__.py
│ ├── catalog1.py
│ ├── funcs_db.py
│ ├── proto
│ │ ├── __init__.py
│ │ ├── frame_endpoint.py
│ │ ├── msg_endpoint.py
│ │ └── serializer.py
│ ├── server
│ │ ├── __init__.py
│ │ ├── fcatalog_logic.py
│ │ └── fcatalog_proto.py
│ ├── server_conf.py
│ └── tests
│ │ ├── __init__.py
│ │ ├── asyncio_util.py
│ │ ├── conftest.py
│ │ ├── proto
│ │ ├── __init__.py
│ │ ├── test_frame_endpoint.py
│ │ ├── test_msg_from_frame.py
│ │ └── test_serializer.py
│ │ ├── psign.py
│ │ ├── server
│ │ ├── __init__.py
│ │ ├── test_fcatalog_logic.py
│ │ └── test_fcatalog_proto.py
│ │ ├── test_catalog1.py
│ │ └── test_funcs_db.py
├── setup.cfg
└── setup.py
├── fcatalog_server
├── get_deps
├── ideas.txt
├── install
├── requirements.txt
└── uninstall
/.gitignore:
--------------------------------------------------------------------------------
1 | *.swp
2 | *.swo
3 | *.db
4 | *.pyc
5 | *.~*
6 | bin/
7 | /dep
8 | *.egg-info/
9 |
10 | build/
11 | dist/
12 |
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 | The FCatalog Server
2 | ===================
3 |
4 | FCatalog is the Functions Catalog. It allows to save large amount of different
5 | binary blobs, and find similarities quickly between them and a given new binary
6 | blob.
7 | FCatalog server works together with a python client that runs with IDA
8 | pro.
9 |
10 | This was written to help binary reversers find similar functions, however it
11 | might be useful for other purposes as well.
12 |
13 | The server is written using Python3 with Asyncio. Sqlite3 is used for
14 | persistency. The core catalog1 function is written in C, for speed.
15 |
16 | You can find the [fcatalog_client repository here](https://github.com/xorpd/fcatalog_client).
17 | Visit the [fcatalog website](http://fcatalog.xorpd.net) for the full story.
18 |
19 | Requirements
20 | ------------
21 |
22 | - The server will only run on Linux. Tested on Ubuntu 14.04
23 | - Python >= 3.4
24 | - gcc
25 |
26 | Installation
27 | ------------
28 |
29 | When you have internet connection, run:
30 |
31 | ./get_deps
32 |
33 | This will fetch all the needed dependencies from the internet. Now just copy
34 | everything and put it on a disk.
35 |
36 | On an offline setting, run:
37 |
38 | sudo ./install
39 |
40 | This should install the fcatalog server. You can uninstall using:
41 |
42 | sudo ./uninstall
43 |
44 |
45 | Using the server
46 | ----------------
47 |
48 | To start the server run:
49 |
50 | sudo start fcatalog
51 |
52 | To stop the server run:
53 |
54 | sudo stop fcatalog
55 |
56 |
57 | The server will start by default on 127.0.0.1:1337
58 |
59 | Tests
60 | -----
61 |
62 | Install pytest:
63 |
64 | pip install pytest
65 |
66 | and run:
67 |
68 | py.test
69 |
70 |
71 | Website
72 | -------
73 |
74 | If you like this, you might like other stuff at http://www.xorpd.net
75 |
--------------------------------------------------------------------------------
/assets/fcatalog.conf:
--------------------------------------------------------------------------------
1 | description "FCatalog Server"
2 | author "xorpd@xorpd.net"
3 |
4 | start on runlevel [2345]
5 | stop on runlevel [!2345]
6 |
7 | respawn
8 |
9 | script
10 | # Can be used for debug:
11 | # See: http://askubuntu.com/questions/36200/how-to-debug-upstart-scripts
12 | # exec 2>> /var/log/fcatalog_err.log
13 | # set -x
14 |
15 | # Start the fcatalog_server:
16 | exec sudo -u ufcatalog /home/ufcatalog/ufcatalog_env/bin/python \
17 | /home/ufcatalog/bin/fcatalog_server 0.0.0.0 1337
18 | end script
19 |
--------------------------------------------------------------------------------
/catalog1/Makefile:
--------------------------------------------------------------------------------
1 |
2 | CC := gcc
3 | CFLAGS := -std=c99
4 |
5 | # Path of the so lib after installation:
6 | LIB_PATH := /usr/local/lib/libcatalog1.so
7 |
8 | # The full path to the directory containing the makefile:
9 | mkfile_dir := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
10 |
11 | # Build everything:
12 | all: libcatalog1 test_catalog1
13 |
14 |
15 | # Install the lib libcatalog1.so
16 | install:
17 | cp ./bin/libcatalog1.so $(LIB_PATH)
18 |
19 | # Uninstall the lib libcatalog1.so from /usr/lib
20 | uninstall:
21 | rm -f $(LIB_PATH)
22 |
23 | clean:
24 | rm -rf ./bin
25 |
26 | libcatalog1: bin/libcatalog1.so
27 |
28 | bin/libcatalog1.so: catalog1.c | bin
29 | $(CC) -shared -Wl,-soname,libcatalog1.so \
30 | -o $@ -fPIC $< $(CFLAGS) -O3
31 |
32 | test_catalog1: bin/test_catalog1
33 |
34 | bin:
35 | mkdir -p ./bin
36 |
37 | bin/test_catalog1: test_catalog1.c bin/libcatalog1.so | bin
38 | $(CC) $< -o $@ -Lbin -lcatalog1 $(CFLAGS)
39 |
40 | .PHONY: test_catalog1 libcatalog1 clean uninstall install all
41 |
--------------------------------------------------------------------------------
/catalog1/catalog1.c:
--------------------------------------------------------------------------------
1 | #define WORD_SIZE 32 // 32 bits
2 | #define MAX_WORD 0xffffffff // Maximum size of a dword.
3 | #define BYTE_SIZE 8 // Amount of bits in a byte.
4 |
5 | #define NUM_ITERS 4 // Amount of iterations per permutation.
6 |
7 | // There are 128 RAND_DWORDS. Don't change the amount of random dwords here.
8 |
9 | unsigned int RAND_DWORDS[] = {1445200656, 3877429363, 1060188777, 4260769784, 1438562000, 2836098482, 1986405151, 4230168452, 380326093, 2859127666, 1134102609, 788546250, 3705417527, 1779868252, 1958737986, 4046915967, 1614805928, 4160312724, 3682325739, 534901034, 2287240917, 2677201636, 71025852, 1171752314, 47956297, 2265969327, 2865804126, 1364027301, 2267528752, 1998395705, 576397983, 636085149, 3876141063, 1131266725, 3949079092, 1674557074, 2566739348, 3782985982, 2164386649, 550438955, 2491039847, 2409394861, 3757073140, 3509849961, 3972853470, 1377009785, 2164834118, 820549672, 2867309379, 1454756115, 94270429, 2974978638, 2915205038, 1887247447, 3641720023, 4292314015, 702694146, 1808155309, 95993403, 1529688311, 2883286160, 1410658736, 3225014055, 1903093988, 2049895643, 476880516, 3241604078, 3709326844, 2531992854, 265580822, 2920230147, 4294230868, 408106067, 3683123785, 1782150222, 3876124798, 3400886112, 1837386661, 664033147, 3948403539, 3572529266, 4084780068, 691101764, 1191456665, 3559651142, 709364116, 3999544719, 189208547, 3851247656, 69124994, 1685591380, 1312437435, 2316872331, 1466758250, 1979107610, 2611873442, 80372344, 1251839752, 2716578101, 176193185, 2142192370, 1179562050, 1290470544, 1957198791, 1435943450, 2989992875, 3703466909, 1302678442, 3343948619, 3762772165, 1438266632, 1761719790, 3668101852, 1283600006, 671544087, 1665876818, 3645433092, 3760380605, 3802664867, 1635015896, 1060356828, 1666255066, 2953295653, 2827859377, 386702151, 3372348076, 4248620909, 2259505262};
10 |
11 |
12 | // Amount of rand dwords - 1:
13 | #define NUM_DWORDS_MASK 0x7f
14 |
15 | unsigned int ror(unsigned int x, unsigned int i) {
16 | // Rotate right a dword x by i bits.
17 | return (x >> i) | (x << (WORD_SIZE - i));
18 | }
19 |
20 |
21 | unsigned int perm(unsigned int num, unsigned int x) {
22 | // Permutation from dword to dword.
23 | // num is the permutation number. x is the input.
24 | unsigned int ror_index;
25 | for(unsigned int i=0; i of the signature of data.
47 | // len is the length of the data.
48 | // The result is inside , as an array of dwords.
49 |
50 | // We need at least 4 bytes to generate a signature.
51 | // We return -1 (error) if we don't have at least 4 bytes.
52 | if(len < 4) {
53 | return -1;
54 | }
55 | unsigned int y; // Current integer value of 4 consecutive bytes.
56 | unsigned int py; // Permutation over y.
57 | unsigned int min_py; // Minimum py ever found.
58 |
59 | for(unsigned int permi=0; permi py) {
75 | min_py = py;
76 | }
77 | }
78 | // Save minimum perm value found to memory:
79 | result[permi] = min_py;
80 | }
81 | // Everything went well.
82 | // Result should be stored at
83 | return 0;
84 | }
85 |
86 |
--------------------------------------------------------------------------------
/catalog1/catalog1.h:
--------------------------------------------------------------------------------
1 | // Sign data of length len.
2 | // Put the resulting signature inside the array result. Calculate num_perms
3 | // permutations.
4 | int sign(
5 | unsigned char* data,
6 | unsigned int len,
7 | unsigned int *result,
8 | unsigned int num_perms);
9 |
--------------------------------------------------------------------------------
/catalog1/test_catalog1.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "catalog1.h"
4 |
5 | #define NUM_PERMS 16
6 |
7 | int print_dword_array(unsigned int* arr,unsigned int len) {
8 | // Print an array of dwords
9 | unsigned int i;
10 | for(unsigned int i=0; i 0) {
99 | printf("A similarity was found between letters1 and digits2\n");
100 | return -1;
101 | }
102 |
103 | return 0;
104 | }
105 |
106 |
107 |
108 | int main() {
109 | int res = 0;
110 |
111 | res |= test_simple_sign();
112 | res |= test_short_input();
113 | res |= test_sign_similarity();
114 |
115 | if(0 == res) {
116 | printf("\n===========================\n");
117 | printf("All tests passed successfuly!\n");
118 | printf("===========================\n");
119 | } else {
120 | printf("\n@@@@@@@@@@@@@@@@@@@@@@@@\n");
121 | printf("Some tests have failed!\n");
122 | printf("@@@@@@@@@@@@@@@@@@@@@@@@\n");
123 | return -1;
124 | }
125 |
126 | return 0;
127 | }
128 |
--------------------------------------------------------------------------------
/fcatalog/README.md:
--------------------------------------------------------------------------------
1 | FCatalog python library
2 | =======================
3 |
4 | A basic library that implements the server logic of the fcatalog server.
5 | It uses asyncio for communication and sqlite3 python bindings for db.
6 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xorpd/fcatalog_server/c86a08e76d84055a5ea5020fc25aec66e33e10e1/fcatalog/fcatalog/__init__.py
--------------------------------------------------------------------------------
/fcatalog/fcatalog/catalog1.py:
--------------------------------------------------------------------------------
1 | # The catalog1 sensitive hashing algorithm.
2 | # By xorpd.
3 |
4 | class Catalog1Error(Exception): pass
5 |
6 | WORD_SIZE = 32 # 32 bits.
7 | MAX_WORD = (1 << WORD_SIZE) - 1
8 |
9 | BYTE_SIZE = 8 # 8 bits.
10 |
11 |
12 | RAND_DWORDS = \
13 | [1445200656, 3877429363, 1060188777, 4260769784, 1438562000, 2836098482, 1986405151, 4230168452, 380326093, 2859127666, 1134102609, 788546250, 3705417527, 1779868252, 1958737986, 4046915967, 1614805928, 4160312724, 3682325739, 534901034, 2287240917, 2677201636, 71025852, 1171752314, 47956297, 2265969327, 2865804126, 1364027301, 2267528752, 1998395705, 576397983, 636085149, 3876141063, 1131266725, 3949079092, 1674557074, 2566739348, 3782985982, 2164386649, 550438955, 2491039847, 2409394861, 3757073140, 3509849961, 3972853470, 1377009785, 2164834118, 820549672, 2867309379, 1454756115, 94270429, 2974978638, 2915205038, 1887247447, 3641720023, 4292314015, 702694146, 1808155309, 95993403, 1529688311, 2883286160, 1410658736, 3225014055, 1903093988, 2049895643, 476880516, 3241604078, 3709326844, 2531992854, 265580822, 2920230147, 4294230868, 408106067, 3683123785, 1782150222, 3876124798, 3400886112, 1837386661, 664033147, 3948403539, 3572529266, 4084780068, 691101764, 1191456665, 3559651142, 709364116, 3999544719, 189208547, 3851247656, 69124994, 1685591380, 1312437435, 2316872331, 1466758250, 1979107610, 2611873442, 80372344, 1251839752, 2716578101, 176193185, 2142192370, 1179562050, 1290470544, 1957198791, 1435943450, 2989992875, 3703466909, 1302678442, 3343948619, 3762772165, 1438266632, 1761719790, 3668101852, 1283600006, 671544087, 1665876818, 3645433092, 3760380605, 3802664867, 1635015896, 1060356828, 1666255066, 2953295653, 2827859377, 386702151, 3372348076, 4248620909, 2259505262]
14 |
15 |
16 | def ror(x,i):
17 | """
18 | Rotate right x by i locations.
19 | x is a dword
20 | """
21 | # Make sure that i is in range:
22 | return ((x >> i) | (x << (WORD_SIZE - i))) & MAX_WORD
23 |
24 | NUM_ITERS = 4
25 | def perm(num,x):
26 | """
27 | A permutation from dwords to dwords.
28 | Implementation here is pretty arbitrary, and could be changed a bit if
29 | needed.
30 |
31 | num is the number of permutation (This could generate many different
32 | permutation functions)
33 | x is the input dword.
34 | """
35 | for i in range(NUM_ITERS):
36 | x += RAND_DWORDS[(i + num + x) % len(RAND_DWORDS)]
37 | x &= MAX_WORD
38 | ror_index = (x ^ RAND_DWORDS[(i + num + 1) % len(RAND_DWORDS)]) % \
39 | WORD_SIZE
40 | x = ror(x,ror_index)
41 | x ^= RAND_DWORDS[(i + num + x) % len(RAND_DWORDS)]
42 | ror_index = (x ^ RAND_DWORDS[(i + num + 1) % len(RAND_DWORDS)]) % \
43 | WORD_SIZE
44 | x = ror(x,ror_index)
45 | assert (x <= MAX_WORD) and (x >= 0)
46 | return x
47 |
48 | def bytes_to_num(data):
49 | """
50 | Convert a string to a number
51 | """
52 | return int.from_bytes(bytes=data,byteorder='big')
53 |
54 |
55 | def slow_sign(data,num_perms):
56 | """
57 | Sign over data.
58 | Use num_perms permutations. (The more you have, the more sensitive is the
59 | comparison later).
60 | """
61 | nbytes = WORD_SIZE // BYTE_SIZE
62 | if len(data) < nbytes:
63 | raise Catalog1Error('data must be at least of size {} bytes.'\
64 | .format(nbytes))
65 |
66 | res_sign = []
67 |
68 | for p in range(num_perms):
69 | num_iters = len(data) - nbytes + 1
70 | cur_sign = min([perm(p,bytes_to_num(data[i:i+nbytes])) for i in \
71 | range(num_iters)])
72 | res_sign.append(cur_sign)
73 |
74 | return res_sign
75 |
76 |
77 | ########################################
78 | ########################################
79 |
80 | import hashlib
81 |
82 | def strong_hash(data):
83 | """
84 | Perform strong cryptographic hash.
85 | """
86 | m = hashlib.sha256()
87 | m.update(data)
88 | return m.digest()
89 |
90 | ########################################
91 | ########################################
92 |
93 | # Binding the C library to python:
94 | import ctypes
95 | from ctypes import cdll
96 |
97 | CATALOG1_LIB = 'libcatalog1.so'
98 |
99 | # A class for calling the sign function from libcatalog1.
100 | class Catalog1Sign:
101 | def __init__(self,lib_name=CATALOG1_LIB):
102 | # Get the catalog1 sign function:
103 | self._catalog1_lib = cdll.LoadLibrary(lib_name)
104 | self._csign = self._catalog1_lib.sign
105 | # Return value is an integer:
106 | self._csign.restype = ctypes.c_int32
107 |
108 |
109 | def sign(self,data,num_perms):
110 | """
111 | Sign data using permutations.
112 | """
113 | if len(data) < 4:
114 | raise Catalog1Error('data must be at least of size 4 bytes.')
115 |
116 | arr_perms = ctypes.c_uint32 * num_perms
117 | # Initialize array for return value:
118 | s = arr_perms()
119 | res = self._csign(data,len(data),s,num_perms)
120 |
121 | if res != 0:
122 | raise Catalog1Error(\
123 | 'Error number: {} when calling sign()'.format(res))
124 |
125 | return list(s)
126 |
127 |
128 | # Initialize one instance for this module:
129 | c1s = Catalog1Sign(CATALOG1_LIB)
130 |
131 | def sign(data,num_perms):
132 | """
133 | Sign over data.
134 | Calls the sign function from libcatalog1.so
135 | """
136 | return c1s.sign(data,num_perms)
137 |
138 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/funcs_db.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | import os
3 | import collections
4 |
5 | from fcatalog.catalog1 import sign,strong_hash
6 |
7 |
8 | # Commit after this amount of functions inserted into the DB:
9 | FUNCTION_BATCH = 0x800
10 |
11 | class FuncsDBError(Exception):
12 | pass
13 |
14 |
15 | DBSimilar = collections.namedtuple('DBSimilar',\
16 | ['func_hash','func_name','func_comment','func_sig','func_grade'])
17 |
18 |
19 | class FuncsDB:
20 | def __init__(self,db_path,num_hashes):
21 | # Keep as members:
22 | self._db_path = db_path
23 | self._num_hashes = num_hashes
24 |
25 | # Inserted functions waiting to be commited:
26 | self._funcs_pending = 0
27 |
28 | # Check if the db has existed before:
29 | db_existed = False
30 | if os.path.isfile(db_path):
31 | db_existed = True
32 |
33 | # Open a connection to the database.
34 | self._conn = sqlite3.connect(self._db_path,isolation_level=None)
35 | self._is_open = True
36 |
37 | # If the database file did not exist, we create an empty database:
38 | if not db_existed:
39 | self._build_empty_db()
40 |
41 | # Begin transaction for inserts:
42 | c = self._conn.cursor()
43 | c.execute('BEGIN TRANSACTION')
44 |
45 |
46 | def _check_is_open(self):
47 | """
48 | Make sure that this FuncsDB instance is open.
49 | """
50 | if not self._is_open:
51 | raise FuncsDBError('FuncsDB instance is closed')
52 |
53 |
54 | def close(self):
55 | """
56 | Commit and Close the connection to the database.
57 | """
58 | self._check_is_open()
59 | # Set state to be closed:
60 | self._is_open = False
61 |
62 | c = self._conn.cursor()
63 | try:
64 | c.execute('COMMIT')
65 | except sqlite3.Error as e:
66 | c.execute('ROLLBACK')
67 | self._conn.close()
68 |
69 |
70 | def commit_funcs(self):
71 | """
72 | Commit pending functions into the db, and prepare the next transaction.
73 | """
74 | self._check_is_open()
75 | c = self._conn.cursor()
76 | try:
77 | # Zero the amount of pending functions:
78 | self._funcs_pending = 0
79 | c.execute('COMMIT')
80 | except sqlite3.Error:
81 | c.execute('ROLLBACK')
82 |
83 | # Begin the next transaction:
84 | c.execute('BEGIN TRANSACTION')
85 |
86 |
87 | def _build_empty_db(self):
88 | """
89 | Build an initial empty database.
90 | Create tables and indices.
91 | """
92 | self._check_is_open()
93 | c = self._conn.cursor()
94 | cmd_tbl = \
95 | """CREATE TABLE funcs(
96 | func_hash BLOB PRIMARY KEY,
97 | func_name TEXT NOT NULL,
98 | func_comment TEXT NOT NULL"""
99 |
100 | for i in range(self._num_hashes):
101 | cmd_tbl += ',\n'
102 | cmd_tbl += 'c' + str(i+1) + ' INTEGER NOT NULL'
103 |
104 | cmd_tbl += ');'
105 |
106 | # Create the funcs table:
107 | c.execute(cmd_tbl)
108 |
109 | # Add index for each of the 'c{num}' columns:
110 | for i in range(self._num_hashes):
111 | cname = 'c' + str(i+1)
112 | cmd_index = 'CREATE INDEX idx_' + cname + ' ON ' + \
113 | 'funcs(' + cname + ');'
114 | c.execute(cmd_index)
115 |
116 | self._conn.commit()
117 |
118 |
119 | def add_function(self,func_name,func_data,func_comment):
120 | """
121 | Add a (Reversed) function to the database.
122 | """
123 | self._check_is_open()
124 | c = self._conn.cursor()
125 | try:
126 |
127 | s = sign(func_data,self._num_hashes)
128 | func_hash = strong_hash(func_data)
129 |
130 |
131 | cmd_insert = \
132 | """INSERT OR REPLACE into funcs
133 | (func_hash,func_name,func_comment"""
134 |
135 | for i in range(self._num_hashes):
136 | cmd_insert += ',c' + str(i+1) + ' '
137 |
138 | cmd_insert += ') values (?,?,?' + (',?' * self._num_hashes) + ');'
139 |
140 | c.execute(cmd_insert,[\
141 | sqlite3.Binary(func_hash),func_name,func_comment] + s)
142 |
143 | # Commit functions inserted to the db if _funcs_pending is large
144 | # enough:
145 | if self._funcs_pending > FUNCTION_BATCH:
146 | self.commit_funcs()
147 |
148 | except sqlite3.Error:
149 | # Give up previous transaction, and start a new one.
150 | c.execute('ROLLBACK')
151 | c.execute('BEGIN TRANSACTION')
152 |
153 |
154 | def get_similars(self,func_data,num_similars):
155 | """
156 | Get a list of at most num_similars similar functions to a given
157 | function. The list will be ordered by similarity. The first element is
158 | the most similar one.
159 | """
160 | self._check_is_open()
161 | c = self._conn.cursor()
162 | try:
163 | # A list to keep results:
164 | res_list = []
165 |
166 | s = sign(func_data,self._num_hashes)
167 | func_hash = strong_hash(func_data)
168 |
169 |
170 | # Get all potential candidates for similarity:
171 | lselects = ['SELECT * FROM funcs WHERE c' + str(i+1) + '=?' \
172 | for i in range(self._num_hashes)]
173 | # Also search for exact match (Using strong hash):
174 | sel_hash = 'SELECT * FROM funcs WHERE func_hash=?'
175 | lselects.append(sel_hash)
176 | selects = "\nUNION\n".join(lselects)
177 |
178 | # Find best matching rows
179 | matching = 'SELECT func_hash,func_name,func_comment,'
180 |
181 | sig_vals = ",".join(['c' + str(i+1) for i in range(self._num_hashes)])
182 | matching += sig_vals
183 |
184 | # Make an expression (c1=sig[0]) + (c2=sig[1]) + ...
185 | # Which will be the grade of every row (The amount of matches of the
186 | # signature).
187 | sig_sum = ' + '.join(\
188 | ['(c' + str(i+1) + '=?)' for i in range(self._num_hashes)])
189 | matching += ',(' + sig_sum + ') AS grade '
190 |
191 | matching += 'FROM (' + selects + ') '
192 |
193 | # Find the num_similars rows with highest grade:
194 | matching += 'ORDER BY grade DESC LIMIT ?'
195 |
196 | c.execute(matching,s + s + [func_hash,num_similars])
197 |
198 | for res in c.fetchall():
199 | res_hash,res_name,res_comment = res[:3]
200 | # We don't want to include the last superficial column grade, this
201 | # is why we have -1 here:
202 | res_sig = list(res[3:-1])
203 | # The function's grade:
204 | grade = res[-1]
205 | sres = DBSimilar(\
206 | func_hash=res_hash,\
207 | func_name=res_name,\
208 | func_comment=res_comment,\
209 | func_sig=res_sig,\
210 | func_grade=grade)
211 |
212 | # If we have exact match (Using strong hash), we move the result to
213 | # the beginning of res_list. Otherwise, we just append to the end.
214 | # The exact match will always be at the beginning.
215 | if res_hash == func_hash:
216 | res_list.insert(0,sres)
217 | else:
218 | res_list.append(sres)
219 |
220 | return res_list
221 |
222 | except sqlite3.Error:
223 | # Give up previous transaction, and start a new one.
224 | c.execute('ROLLBACK')
225 | c.execute('BEGIN TRANSACTION')
226 |
227 |
228 |
229 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/proto/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xorpd/fcatalog_server/c86a08e76d84055a5ea5020fc25aec66e33e10e1/fcatalog/fcatalog/proto/__init__.py
--------------------------------------------------------------------------------
/fcatalog/fcatalog/proto/frame_endpoint.py:
--------------------------------------------------------------------------------
1 | import struct
2 | import asyncio
3 |
4 | # Generic class for FrameEndpoint.
5 | # A method to send frames over a streaming protocol.
6 |
7 | class FrameEndpoint:
8 | @asyncio.coroutine
9 | def send(self,data_frame:bytes):
10 | """Send a frame"""
11 | raise NotImplementedError()
12 |
13 | @asyncio.coroutine
14 | def recv(self):
15 | """Receive a frame"""
16 | raise NotImplementedError()
17 |
18 | @asyncio.coroutine
19 | def close(self):
20 | """Close the connection"""
21 | raise NotImplementedError()
22 |
23 |
24 | ################################################
25 | ################################################
26 |
27 |
28 | # Default Maximum length for a string being sent: 1 mb.
29 | MAX_FRAME_LEN = 2**20
30 |
31 | # Amount of bytes of length prefix:
32 | SIZE_PREFIX_LEN = 4
33 |
34 | class TCPFrameEndpoint(FrameEndpoint):
35 | def __init__(self,reader,writer,max_frame_len=MAX_FRAME_LEN):
36 | # Max length of one frame:
37 | self._max_frame_len = max_frame_len
38 |
39 | # Keep reader and writer:
40 | # Those are asyncio TCP Stream Reader and Writer.
41 | self._reader = reader
42 | self._writer = writer
43 |
44 | # Set connection state to be open:
45 | self._is_open = True
46 |
47 |
48 | @asyncio.coroutine
49 | def send(self,data_frame:bytes):
50 | """
51 | Send a frame
52 | (Send data as a length prefixed frame)
53 | """
54 | # Encode the length of the data as an unsigned int (4 bytes):
55 | blen = struct.pack('I',len(data_frame))
56 | # Write the length prefix and the data:
57 | self._writer.write(blen + data_frame)
58 | # Try to flush underlying buffer:
59 | # See https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamWriter.drain
60 | yield from self._writer.drain()
61 |
62 |
63 | @asyncio.coroutine
64 | def recv(self):
65 | """
66 | Receive a frame:
67 | Receive prefixed string data.
68 | return value of None means that the remote host has closed the
69 | connection (Or some read error has occured).
70 | """
71 |
72 | try:
73 | # Read the length prefix (4 bytes):
74 | blen = yield from self._reader.readexactly(SIZE_PREFIX_LEN)
75 | # Unpack 4 bytes into an integer:
76 | len_data = struct.unpack('I',blen)[0]
77 |
78 | # If the message length is too big, we close the connection.
79 | if len_data > self._max_frame_len:
80 | yield from self.close()
81 | return None
82 |
83 | # Read the message itself (We already know the length):
84 | # Will read exactly len_data:
85 | bmsg = yield from self._reader.readexactly(len_data)
86 |
87 | return bmsg
88 |
89 | except asyncio.IncompleteReadError:
90 | # Reached end of stream. (Remote peer disconnected).
91 | yield from self.close()
92 | # We return None:
93 | return None
94 |
95 |
96 | @asyncio.coroutine
97 | def close(self):
98 | """Close the connection"""
99 | # We call _writer.close() at most once:
100 | if self._is_open:
101 | self._writer.close()
102 | # Mark connection as closed:
103 | self._is_open = False
104 |
105 |
106 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/proto/msg_endpoint.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | from .serializer import DeserializeError,SerializeError
3 |
4 |
5 | class MsgEndpoint:
6 | @asyncio.coroutine
7 | def send(self,msg):
8 | """Send a message"""
9 | raise NotImplementedError()
10 |
11 | @asyncio.coroutine
12 | def recv(self):
13 | """Receive a message"""
14 | raise NotImplementedError()
15 |
16 | @asyncio.coroutine
17 | def close(self):
18 | """Close the connection"""
19 | raise NotImplementedError()
20 |
21 |
22 |
23 | class MsgFromFrame(MsgEndpoint):
24 | def __init__(self,serializer,frame_endpoint):
25 | # Keep serializer:
26 | self.serializer = serializer
27 |
28 | # Keep frame_endpoint:
29 | self._frame_endpoint = frame_endpoint
30 |
31 |
32 | @asyncio.coroutine
33 | def recv(self):
34 | """
35 | receive a message from the other side.
36 | Return None if connection should be considered closed.
37 | """
38 | # Get a frame from the frame_endpoint:
39 | frame = ( yield from self._frame_endpoint.recv() )
40 |
41 | # Check if the remote host has closed the connection:
42 | if frame is None:
43 | return None
44 |
45 | try:
46 | # Deserialize the frame into a message:
47 | msg_inst = self.serializer.deserialize_msg(frame)
48 | except DeserializeError:
49 | # If we have an error reading the frame, we consider the
50 | # connection as closed:
51 | return None
52 |
53 | return msg_inst
54 |
55 |
56 | @asyncio.coroutine
57 | def send(self,msg):
58 | """
59 | Send a message msg to the other side.
60 | """
61 | frame = self.serializer.serialize_msg(msg)
62 | return ( yield from self._frame_endpoint.send(frame) )
63 |
64 |
65 | @asyncio.coroutine
66 | def close(self):
67 | """
68 | Close the connection
69 | """
70 | # Close the connection:
71 | yield from self._frame_endpoint.close()
72 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/proto/serializer.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import struct
3 | import bidict
4 |
5 | class SerializerError(Exception): pass
6 | class SerializeError(SerializerError): pass
7 | class DeserializeError(SerializerError): pass
8 |
9 | class MsgError(SerializerError): pass
10 |
11 |
12 | # A message instance:
13 | class Msg:
14 | def __init__(self,serializer,msg_type,afields):
15 | # Keep a link to the serializer:
16 | self._serializer = serializer
17 | # Keep the msg_type:
18 | self._msg_type = msg_type
19 | # Set of allowed fields:
20 | self._afields = set(afields)
21 |
22 | # Values of fields:
23 | self._fields = {}
24 |
25 | @property
26 | def msg_name(self):
27 | """
28 | Get the message name of the Msg.
29 | """
30 | return self._serializer.msg_type_to_msg_name(self._msg_type)
31 |
32 | @property
33 | def msg_type(self):
34 | """
35 | Get the message type of the Msg
36 | """
37 | return self._msg_type
38 |
39 |
40 | def _check_field_exists(self,field):
41 | """
42 | Make sure that a field exists.
43 | """
44 | if field not in self._afields:
45 | raise MsgError('Msg {} does not have field {}.'.format(\
46 | self.msg_name,field))
47 |
48 | def set_field(self,field,value):
49 | """
50 | Set a message field (If exists):
51 | """
52 | self._check_field_exists(field)
53 | self._fields[field] = value
54 |
55 | def get_field(self,field):
56 | """
57 | Get a message field (If exists):
58 | """
59 | self._check_field_exists(field)
60 | return self._fields[field]
61 |
62 | #######################################################
63 |
64 |
65 | class MsgDef:
66 | # The allowed fields of the message:
67 | afields = []
68 |
69 | def __init__(self,serializer):
70 | # Keep serializer:
71 | self._serializer = serializer
72 |
73 | def serialize(self,msg_inst) -> bytes:
74 | """
75 | Serialize a msg_inst into bytes.
76 | """
77 | raise NotImplementedError()
78 |
79 | def deserialize(self,msg_data:bytes):
80 | """
81 | Deserialize data bytes into a msg_inst.
82 | """
83 | raise NotImplementedError()
84 |
85 | def get_msg(self):
86 | """
87 | Get an empty message of the type of this message.
88 | """
89 | # Get this class name:
90 | class_name = type(self).__name__
91 | return self._serializer.get_msg(class_name)
92 |
93 |
94 | ##################################################################
95 |
96 | class ProtoDef:
97 | outgoing_msgs = {}
98 | incoming_msgs = {}
99 |
100 |
101 | ##################################################################
102 |
103 |
104 | def unpack_msg_type(data:bytes):
105 | """
106 | Get the msg type from the data.
107 | Return the message type and the remaining data as a tuple.
108 | """
109 |
110 | if len(data) < 4:
111 | raise DeserializeError('Data is too short. len(data) ='
112 | '{}'.format(len(data)))
113 |
114 | msg_type = struct.unpack("I",data[0:4])[0]
115 | msg_data = data[4:]
116 | return msg_type,msg_data
117 |
118 |
119 | def pack_msg_type(msg_type,msg_data:bytes):
120 | """
121 | Given the msg type and the message data, build a full message (Made of
122 | bytes).
123 | """
124 | msg_type_data = struct.pack("I",msg_type)
125 | data = msg_type_data + msg_data
126 | return data
127 |
128 | ###################################################################
129 |
130 | def dicts_agree(dc1,dc2):
131 | """
132 | Check if two dictionaries agree on the intersection of their domains.
133 | """
134 | dom1 = set(dc1.keys())
135 | dom2 = set(dc2.keys())
136 |
137 | # Domain intersection:
138 | int_dom = dom1.intersection(dom2)
139 |
140 | # Make sure that the two dicts agree on all of their common domain:
141 | for k in int_dom:
142 | if dc1[k] != dc2[k]:
143 | return False
144 |
145 | return True
146 |
147 |
148 |
149 | class Serializer:
150 | def __init__(self,proto_def):
151 | # Calculate intersection between keys of outgoing messages and incoming
152 | # messages:
153 | if not \
154 | dicts_agree(proto_def.incoming_msgs,proto_def.outgoing_msgs):
155 | raise SerializerError('Incompatible definitions of '
156 | 'incoming and outgoing msgs: {}')
157 |
158 | self._in_keys = proto_def.incoming_msgs.keys()
159 | self._out_keys = proto_def.outgoing_msgs.keys()
160 |
161 | # Collect a dictionary of all the messages:
162 | all_msgs = {}
163 | all_msgs.update(proto_def.incoming_msgs)
164 | all_msgs.update(proto_def.outgoing_msgs)
165 |
166 |
167 | # Dict between msg_type and MsgDef instance:
168 | self._proto_def = dict()
169 | # Bidirectional dict between msg type and msg name:
170 | self._b_msg_type_name = bidict.bidict()
171 | for msg_type, msg_def in all_msgs.items():
172 | # Initialize msg_def with serializer=self
173 | msg_def_inst = msg_def(self)
174 | self._proto_def[msg_type] = msg_def_inst
175 | # Assign the msg_def's instance name:
176 | self._b_msg_type_name[msg_type] = type(msg_def_inst).__name__
177 |
178 | def msg_type_to_msg_name(self,msg_type):
179 | """
180 | Convert message type (Integer) to message name (string).
181 | """
182 | return self._b_msg_type_name[msg_type:]
183 |
184 | def msg_name_to_msg_type(self,msg_name):
185 | """
186 | Convert message name (string) to message type (Integer).
187 | """
188 | return self._b_msg_type_name[:msg_name]
189 |
190 |
191 | def serialize_msg(self,msg_inst):
192 | """
193 | Serialize a message instance to bytes.
194 | """
195 | try:
196 | # Get the relevant msg_def instance:
197 | msg_type = msg_inst.msg_type
198 | # Check if we are willing to send this kind of message:
199 | if msg_type not in self._out_keys:
200 | raise SerializeError('Message {} is not of type outgoing!'.\
201 | format(msg_type))
202 | msg_def = self._proto_def[msg_type]
203 | msg_data = msg_def.serialize(msg_inst)
204 | return pack_msg_type(msg_type,msg_data)
205 | except SerializeError as e:
206 | msg_name = self.msg_type_to_msg_name(msg_type)
207 | raise SerializeError('Failed serializing msg {}.'.\
208 | format(msg_name)) from e
209 |
210 |
211 | def deserialize_msg(self,data):
212 | """
213 | Deserialize data bytes to a message instance.
214 | """
215 | try:
216 | msg_type, msg_data = unpack_msg_type(data)
217 | if msg_type not in self._proto_def:
218 | raise DeserializeError('Invalid message type {}.'.\
219 | format(msg_type))
220 |
221 | # Check if we are willing to receive this message type:
222 | if msg_type not in self._in_keys:
223 | raise DeserializeError('Message {} is not of type incoming!'.\
224 | format(msg_type))
225 |
226 |
227 | msg_def = self._proto_def[msg_type]
228 | msg_inst = msg_def.deserialize(msg_data)
229 | return msg_inst
230 | except DeserializeError as e:
231 | raise DeserializeError('Failed deserializing msg:\n {}'.\
232 | format(msg_data)) from e
233 |
234 |
235 | def get_msg(self,msg_name):
236 | """
237 | Get an empty message of name msg_name
238 | """
239 | msg_type = self.msg_name_to_msg_type(msg_name)
240 | msg_def = self._proto_def[msg_type]
241 |
242 | # Build an empty message of the correct type:
243 | msg_inst = Msg(self,msg_type,msg_def.afields)
244 | return msg_inst
245 |
246 |
247 | #####################################################
248 | #####################################################
249 |
250 |
251 | def s_string(s:str) -> bytes:
252 | """
253 | Serialize a python string into a length prefixed serialized bytes string
254 | ('UTF-8')
255 | """
256 | s_bytes = s.encode('UTF-8')
257 | res = struct.pack('I',len(s_bytes))
258 | res += s_bytes
259 | return res
260 |
261 |
262 | def d_string(data:bytes) -> str:
263 | """
264 | Parse a length prefixed string from data.
265 | Returns: Next location (to keep parsing), The resulting string.
266 | """
267 | if len(data) < 4:
268 | raise DeserializeError('data is too short to contain a string.')
269 |
270 | s_len = struct.unpack('I',data[0:4])[0]
271 |
272 | if len(data) < 4 + s_len:
273 | raise DeserializeError('Invalid length prefix')
274 |
275 | try:
276 | return 4+s_len,data[4:4+s_len].decode('UTF-8','strict')
277 | except UnicodeDecodeError:
278 | raise DeserializeError('Invalid utf-8 string.')
279 |
280 |
281 | def s_blob(b:bytes) -> bytes:
282 | """
283 | Serialize a python bytes object into a length prefixed serialized bytes.
284 | """
285 | res = struct.pack('I',len(b))
286 | res += b
287 | return res
288 |
289 | def d_blob(data:bytes) -> bytes:
290 | """
291 | Deserialize data bytes to a python bytes object.
292 | """
293 | if len(data) < 4:
294 | raise DeserializeError('data is too short to contain a blob.')
295 |
296 | b_len = struct.unpack('I',data[0:4])[0]
297 |
298 | if len(data) < 4 + b_len:
299 | raise DeserializeError('Invalid length prefix')
300 |
301 | return 4+b_len,data[4:4+b_len]
302 |
303 |
304 | def s_uint32(x:int) -> bytes:
305 | """
306 | Serializer an integer to bytes
307 | """
308 | return struct.pack('I',x)
309 |
310 |
311 | def d_uint32(data:bytes) -> int:
312 | """
313 | Deserialize an integer from the data bytes.
314 | Returns next location and resulting integer.
315 | """
316 | if len(data) < 4:
317 | raise DeserializeError('data is too short to contain a uint32.')
318 |
319 | return 4,struct.unpack('I',data[0:4])[0]
320 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/server/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xorpd/fcatalog_server/c86a08e76d84055a5ea5020fc25aec66e33e10e1/fcatalog/fcatalog/server/__init__.py
--------------------------------------------------------------------------------
/fcatalog/fcatalog/server/fcatalog_logic.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | import os
4 | import string
5 |
6 | from fcatalog.proto.msg_endpoint import MsgEndpoint
7 | from fcatalog.server.fcatalog_proto import cser_serializer,FSimilar
8 | from fcatalog.funcs_db import FuncsDB
9 |
10 | class ServerLogicError(Exception): pass
11 |
12 |
13 | # Set up logger:
14 | logger = logging.getLogger(__name__)
15 |
16 | def is_good_db_name(db_name):
17 | """
18 | Check if a db_name is valid. We have to be careful of directory traversal
19 | here.
20 | """
21 | good_chars = string.ascii_letters + string.digits + "_"
22 | for c in db_name:
23 | if c not in good_chars:
24 | return False
25 |
26 | return True
27 |
28 |
29 | class FCatalogServerLogic:
30 | def __init__(self,db_base_path,num_hashes,msg_endpoint):
31 | # Keep database base path:
32 | self._db_base_path = db_base_path
33 | # Keep amount of hashes:
34 | self._num_hashes = num_hashes
35 | # Message endpoint:
36 | self._msg_endpoint = msg_endpoint
37 |
38 | # Initially Functions Database interface is None:
39 | self._fdb = None
40 |
41 | @asyncio.coroutine
42 | def client_handler(self):
43 | """
44 | Main logic of the catalog1 server, for one client.
45 | Communication with the client is done through the msg_endpoint class
46 | instance.
47 | """
48 | logger.debug('New connection {}'.format(id(self._msg_endpoint)))
49 | msg_inst = ( yield from self._msg_endpoint.recv() )
50 |
51 | if msg_inst is None:
52 | # Remote peer has disconnected or sent invalid data. We disconnect.
53 | return
54 |
55 | if msg_inst.msg_name != 'ChooseDB':
56 | # If the first message is not ChooseDB, we disconnect.
57 | logger.debug('Connection {} has {} as first message.'
58 | ' Closing connection.'.\
59 | format(msg_inst.msg_name, id(self._msg_endpoint)))
60 | return
61 |
62 | # Database name:
63 | db_name = msg_inst.get_field('db_name')
64 |
65 | # Validate database name:
66 | if not is_good_db_name(db_name):
67 | logger.info('Invalid db name {} was chosen at connection {}'.\
68 | format(db_name,id(self._msg_endpoint)))
69 | # Disconnect the client:
70 | return
71 |
72 | # Conclude database path:
73 | db_path = os.path.join(self._db_base_path,db_name)
74 |
75 | logger.debug('db_path = {} at connection {}'.\
76 | format(db_path,id(self._msg_endpoint)))
77 |
78 | # Build a Functions DB interface:
79 | self._fdb = FuncsDB(db_path,self._num_hashes)
80 | try:
81 | msg_inst = ( yield from self._msg_endpoint.recv() )
82 | while msg_inst is not None:
83 | if msg_inst.msg_name == 'ChooseDB':
84 | # We can't have two ChooseDB messages in a connection. We
85 | # close the connection:
86 | return
87 | elif msg_inst.msg_name == 'AddFunction':
88 | yield from self._handle_add_function(msg_inst)
89 | elif msg_inst.msg_name == 'RequestSimilars':
90 | yield from self._handle_request_similars(msg_inst)
91 | else:
92 | # This should never happen:
93 | raise ServerLogicError('Unknown message name {}'.\
94 | format(msg_inst.msg_name))
95 |
96 | # Receive the next message:
97 | msg_inst = ( yield from self._msg_endpoint.recv() )
98 |
99 | logger.debug('Received a None message on connection {}'.\
100 | format(id(self._msg_endpoint)))
101 |
102 | finally:
103 | # We make sure to eventually close the fdb interface (To commit all
104 | # changes that might be pending).
105 | self._fdb.close()
106 |
107 |
108 | @asyncio.coroutine
109 | def _handle_add_function(self,msg_inst):
110 | """
111 | Handle an AddFunction message.
112 | """
113 | func_name = msg_inst.get_field('func_name')
114 | func_comment = msg_inst.get_field('func_comment')
115 | func_data = msg_inst.get_field('func_data')
116 |
117 | logger.debug('AddFunction: func_name={}'
118 | ' func_comment={}'
119 | ' func_data={} on connection {}'.\
120 | format(func_name,func_comment,func_data,\
121 | id(self._msg_endpoint)))
122 |
123 | # Add function to database:
124 | self._fdb.add_function(func_name,func_data,func_comment)
125 |
126 |
127 | @asyncio.coroutine
128 | def _handle_request_similars(self,msg_inst):
129 | """
130 | Handle a RequestSimilars message.
131 | """
132 | func_data = msg_inst.get_field('func_data')
133 | num_similars = msg_inst.get_field('num_similars')
134 |
135 | logger.debug('GetSimilars: func_data={}'
136 | ' num_similars={} on connection {}'.\
137 | format(func_data,num_similars,\
138 | id(self._msg_endpoint)))
139 |
140 | # Get a list of similar functions from the db:
141 | sims = self._fdb.get_similars(func_data,num_similars)
142 |
143 | # We convert the sims we have received from the db to another format:
144 | res_sims = []
145 | for s in sims:
146 | fs = FSimilar(name=s.func_name,\
147 | comment=s.func_comment,\
148 | sim_grade=s.func_grade)
149 | res_sims.append(fs)
150 |
151 | # Build a ResponseSimilars message:
152 | resp_msg = cser_serializer.get_msg('ResponseSimilars')
153 | resp_msg.set_field('similars',res_sims)
154 |
155 | # Send back the Response similars message:
156 | yield from self._msg_endpoint.send(resp_msg)
157 |
158 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/server/fcatalog_proto.py:
--------------------------------------------------------------------------------
1 | import collections
2 | from fcatalog.proto.serializer import s_string,d_string,\
3 | s_blob,d_blob,s_uint32,d_uint32,\
4 | Serializer,ProtoDef,MsgDef
5 |
6 |
7 | # A similar function struct
8 | FSimilar = collections.namedtuple('FSimilar',\
9 | ['name','comment','sim_grade'])
10 |
11 | class ChooseDB(MsgDef):
12 | afields = ['db_name']
13 | def serialize(self,msg_inst) -> bytes:
14 | """
15 | Serialize a msg_inst into bytes.
16 | """
17 | return s_string(msg_inst.get_field('db_name'))
18 |
19 | def deserialize(self,msg_data:bytes):
20 | """
21 | Deserialize data bytes into a msg_inst.
22 | """
23 | msg_inst = self.get_msg()
24 | nextl,db_name = d_string(msg_data)
25 | msg_inst.set_field('db_name',db_name)
26 | return msg_inst
27 |
28 |
29 | class AddFunction(MsgDef):
30 | afields = ['func_name','func_comment','func_data']
31 | def serialize(self,msg_inst) -> bytes:
32 | """
33 | Serialize a msg_inst into bytes.
34 | """
35 | resl = []
36 | resl.append(s_string(msg_inst.get_field('func_name')))
37 | resl.append(s_string(msg_inst.get_field('func_comment')))
38 | resl.append(s_blob(msg_inst.get_field('func_data')))
39 | return b''.join(resl)
40 |
41 | def deserialize(self,msg_data:bytes):
42 | """
43 | Deserialize data bytes into a msg_inst.
44 | """
45 | nl,func_name = d_string(msg_data)
46 | msg_data = msg_data[nl:]
47 | nl,func_comment = d_string(msg_data)
48 | msg_data = msg_data[nl:]
49 | nl,func_data = d_blob(msg_data)
50 |
51 | msg_inst = self.get_msg()
52 | msg_inst.set_field('func_name',func_name)
53 | msg_inst.set_field('func_comment',func_comment)
54 | msg_inst.set_field('func_data',func_data)
55 | return msg_inst
56 |
57 |
58 | class RequestSimilars(MsgDef):
59 | afields = ['func_data','num_similars']
60 | def serialize(self,msg_inst) -> bytes:
61 | """
62 | Serialize a msg_inst into bytes.
63 | """
64 | resl = []
65 | resl.append(s_blob(msg_inst.get_field('func_data')))
66 | resl.append(s_uint32(msg_inst.get_field('num_similars')))
67 | return b''.join(resl)
68 |
69 | def deserialize(self,msg_data:bytes):
70 | """
71 | Deserialize data bytes into a msg_inst.
72 | """
73 | nl,func_data = d_blob(msg_data)
74 | msg_data = msg_data[nl:]
75 | nl,num_similars = d_uint32(msg_data)
76 |
77 | msg_inst = self.get_msg()
78 | msg_inst.set_field('func_data',func_data)
79 | msg_inst.set_field('num_similars',num_similars)
80 | return msg_inst
81 |
82 |
83 | class ResponseSimilars(MsgDef):
84 | afields = ['similars']
85 | def serialize(self,msg_inst) -> bytes:
86 | """
87 | Serialize a msg_inst into bytes.
88 | """
89 | sims = msg_inst.get_field('similars')
90 | resl = []
91 | resl.append(s_uint32(len(sims)))
92 |
93 | for sim in sims:
94 | resl.append(s_string(sim.name))
95 | resl.append(s_string(sim.comment))
96 | resl.append(s_uint32(sim.sim_grade))
97 |
98 | return b''.join(resl)
99 |
100 |
101 | def deserialize(self,msg_data:bytes):
102 | """
103 | Deserialize data bytes into a msg_inst.
104 | """
105 | # Read the amount of similars:
106 | nl,num_sims = d_uint32(msg_data)
107 | msg_data = msg_data[nl:]
108 |
109 | sims = []
110 | for _ in range(num_sims):
111 | nl,sim_name = d_string(msg_data)
112 | msg_data = msg_data[nl:]
113 | nl,sim_comment = d_string(msg_data)
114 | msg_data = msg_data[nl:]
115 | nl,sim_grade = d_uint32(msg_data)
116 | msg_data = msg_data[nl:]
117 |
118 | sims.append(FSimilar(\
119 | name=sim_name,\
120 | comment=sim_comment,\
121 | sim_grade=sim_grade\
122 | ))
123 |
124 | msg_inst = self.get_msg()
125 | msg_inst.set_field('similars',sims)
126 | return msg_inst
127 |
128 |
129 | class FCatalogProtoDef(ProtoDef):
130 | incoming_msgs = {\
131 | 0:ChooseDB,\
132 | 1:AddFunction,\
133 | 2:RequestSimilars}
134 | outgoing_msgs = {3:ResponseSimilars}
135 |
136 |
137 |
138 | cser_serializer = Serializer(FCatalogProtoDef)
139 |
140 | ###############################################################
141 | ###############################################################
142 |
143 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/server_conf.py:
--------------------------------------------------------------------------------
1 | # Base path for databases:
2 | DB_BASE_PATH = '/var/lib/fcatalog/'
3 |
4 | # Amount of hashes for signature:
5 | NUM_HASHES = 16
6 |
7 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xorpd/fcatalog_server/c86a08e76d84055a5ea5020fc25aec66e33e10e1/fcatalog/fcatalog/tests/__init__.py
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/asyncio_util.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | from fcatalog.proto.frame_endpoint import FrameEndpoint
3 |
4 | # Timeout in seconds for an asynchronous test:
5 | ASYNC_TEST_TIMEOUT = 1
6 |
7 | class ExceptAsyncTestTimeout(Exception): pass
8 |
9 | def run_timeout(cor,loop,timeout=ASYNC_TEST_TIMEOUT):
10 | """
11 | Run a given coroutine with timeout.
12 | """
13 | task_with_timeout = asyncio.wait_for(cor,timeout,loop=loop)
14 | try:
15 | return loop.run_until_complete(task_with_timeout)
16 | except asyncio.futures.TimeoutError:
17 | # Timeout:
18 | raise ExceptAsyncTestTimeout()
19 |
20 |
21 | class MockFrameEndpoint(FrameEndpoint):
22 | def __init__(self,frame_reader,frame_writer,uid=None,log_list=None):
23 | # Keep frame reader and writer:
24 | self._frame_reader = frame_reader
25 | self._frame_writer = frame_writer
26 |
27 | # Keep unique id: (For debugging)
28 | self._uid = uid
29 | # Keep log list: (For debugging)
30 | self._log_list = log_list
31 |
32 | @asyncio.coroutine
33 | def send(self,data_frame:bytes):
34 | """Send a frame"""
35 | yield from self._frame_writer(data_frame)
36 |
37 | @asyncio.coroutine
38 | def recv(self) -> bytes:
39 | """Receive a frame"""
40 | return (yield from self._frame_reader())
41 |
42 | @asyncio.coroutine
43 | def close(self):
44 | """Close the connection"""
45 | yield from self._frame_writer(None)
46 | if self._log_list is not None:
47 | # Write None. The other side will interpret this as closing the
48 | # connection:
49 | # Append 'stop' callback to the log list:
50 | self._log_list.append(('stop',self._uid))
51 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import pytest
3 | import os
4 | import tempfile
5 | import shutil
6 |
7 |
8 |
9 | @pytest.fixture(scope='function')
10 | def tmpdir(request):
11 | """
12 | A fixture to create a temporary directory.
13 | Deletes the directory automatically after use.
14 | """
15 | tmpdir = tempfile.mkdtemp()
16 | def fin():
17 | """Finalizer for tmpdir"""
18 | # Remove the temporary directory:
19 | shutil.rmtree(tmpdir)
20 | request.addfinalizer(fin)
21 | return tmpdir
22 |
23 |
24 | @pytest.fixture(scope='module')
25 | def asyncio_debug_mode():
26 | """
27 | Set debug mode for asyncio
28 | """
29 | os.environ['PYTHONASYNCIODEBUG'] = '1'
30 |
31 |
32 | @pytest.fixture(scope='function')
33 | def tloop(request,asyncio_debug_mode):
34 | """
35 | Obtain a test loop. We want each test case to have its own loop.
36 | """
37 | # Create a new test loop:
38 | tloop = asyncio.new_event_loop()
39 | asyncio.set_event_loop(tloop)
40 |
41 | def teardown():
42 | # Close the test loop:
43 | tloop.close()
44 |
45 | request.addfinalizer(teardown)
46 | return tloop
47 |
48 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/proto/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xorpd/fcatalog_server/c86a08e76d84055a5ea5020fc25aec66e33e10e1/fcatalog/fcatalog/tests/proto/__init__.py
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/proto/test_frame_endpoint.py:
--------------------------------------------------------------------------------
1 | import struct
2 | import asyncio
3 | import pytest
4 |
5 | from fcatalog.proto.frame_endpoint import TCPFrameEndpoint
6 | from fcatalog.tests.asyncio_util import run_timeout
7 |
8 |
9 | def test_frame_endpoint_tcp_adapter_basic(tloop):
10 | """
11 | Test basic tcp interaction using the TCPFrameEndpoint interface.
12 | """
13 | # List of results:
14 | res = []
15 |
16 | addr,port = 'localhost',8767
17 |
18 | @asyncio.coroutine
19 | def server_handler(reader,writer):
20 | """Echo server"""
21 |
22 | tfe = TCPFrameEndpoint(reader,writer)
23 |
24 | # Read a frame:
25 | frame = yield from tfe.recv()
26 | # Send the frame back to client:
27 | yield from tfe.send(frame)
28 |
29 | @asyncio.coroutine
30 | def client():
31 | CLIENT_MESS = b'This is a mess'
32 | reader, writer = yield from \
33 | asyncio.open_connection(host=addr,port=port)
34 | tfe = TCPFrameEndpoint(reader,writer)
35 | yield from tfe.send(CLIENT_MESS)
36 | frame = yield from tfe.recv()
37 | assert frame == CLIENT_MESS
38 | # Append True to list of results:
39 | res.append(True)
40 |
41 | # Close client:
42 | yield from tfe.close()
43 |
44 |
45 | # Start server:
46 | start_server = asyncio.start_server(server_handler,host=addr,port=port,reuse_address=True)
47 | server_task = run_timeout(start_server,tloop)
48 |
49 | # Start client:
50 | run_timeout(client(),tloop)
51 |
52 | # Close server:
53 | server_task.close()
54 | # Wait until server is closed:
55 | run_timeout(server_task.wait_closed(),loop=tloop)
56 |
57 | assert res == [True]
58 |
59 |
60 | def test_tcp_adapter_frame_struct(tloop):
61 | """
62 | Test send/recv of length prefixed frames over TCP with the
63 | TCPFrameEndpoint.
64 | """
65 | # List of results:
66 | res = []
67 |
68 | addr,port = 'localhost',8767
69 |
70 | @asyncio.coroutine
71 | def server_handler(reader,writer):
72 | """Echo server"""
73 |
74 | tfe = TCPFrameEndpoint(reader,writer)
75 |
76 | # Read a frame:
77 | frame = yield from tfe.recv()
78 | assert frame == b'abc'
79 |
80 | # Read a frame:
81 | frame = yield from tfe.recv()
82 | assert frame == b''
83 |
84 | # Read a frame:
85 | frame = yield from tfe.recv()
86 | assert frame == b'abcd'
87 |
88 | # Read a frame:
89 | frame = yield from tfe.recv()
90 | assert frame == b'abcd'
91 |
92 | res.append('sending_frame')
93 | # Write a frame:
94 | yield from tfe.send(b'1234')
95 |
96 | # Last frame was cut in the middle (The connection was closed),
97 | # therefore we expect to get a None here:
98 | frame = yield from tfe.recv()
99 | assert frame is None
100 |
101 | res.append('got_none')
102 |
103 | @asyncio.coroutine
104 | def client():
105 | reader, writer = yield from \
106 | asyncio.open_connection(host=addr,port=port)
107 |
108 | # Write b'abc':
109 | writer.write(b'\x03\x00\x00\x00abc')
110 | yield from writer.drain()
111 |
112 | # Write empty frame:
113 | writer.write(b'\x00\x00\x00\x00')
114 | yield from writer.drain()
115 |
116 | # Write b'abcd':
117 | writer.write(b'\x04\x00\x00\x00abcd')
118 | yield from writer.drain()
119 |
120 | # Write b'abcd' in two parts:
121 | writer.write(b'\x04\x00\x00')
122 | yield from writer.drain()
123 | writer.write(b'\x00abcd')
124 | yield from writer.drain()
125 |
126 | # Read a frame from the server:
127 | len_prefix = yield from reader.readexactly(4)
128 | msg_len = struct.unpack('I',len_prefix)[0]
129 | frame = yield from reader.readexactly(msg_len)
130 | assert frame == b'1234'
131 |
132 | # Send half a frame:
133 | writer.write(b'\x00\x00\x00')
134 | yield from writer.drain()
135 |
136 | # Append True to list of results:
137 | res.append('client_close')
138 |
139 | # Close client:
140 | writer.close()
141 |
142 |
143 | # Start server:
144 | start_server = asyncio.start_server(server_handler,host=addr,port=port,reuse_address=True)
145 | server_task = run_timeout(start_server,tloop)
146 |
147 | # Start client:
148 | run_timeout(client(),tloop)
149 |
150 | # Close server:
151 | server_task.close()
152 | # Wait until server is closed:
153 | run_timeout(server_task.wait_closed(),loop=tloop)
154 |
155 | assert res == ['sending_frame','client_close','got_none']
156 |
157 |
158 | def test_tcp_adapter_max_frame_len(tloop):
159 | """
160 | Test send/recv of length prefixed frames over TCP with the
161 | TCPFrameEndpoint.
162 | """
163 | # List of results:
164 | res = []
165 |
166 | addr,port = 'localhost',8767
167 |
168 | @asyncio.coroutine
169 | def server_handler(reader,writer):
170 | """Echo server"""
171 |
172 | tfe = TCPFrameEndpoint(reader,writer,max_frame_len=4)
173 |
174 | # Read a frame:
175 | frame = yield from tfe.recv()
176 | assert frame == b'abc'
177 |
178 | # Read a frame:
179 | frame = yield from tfe.recv()
180 | assert frame == b''
181 |
182 | # Read a frame. The frame should be too large for the chosen
183 | # max_frame_len=4, so we expect to get None here:
184 | frame = yield from tfe.recv()
185 | assert frame == None
186 |
187 | res.append('got_none')
188 |
189 | @asyncio.coroutine
190 | def client():
191 | reader, writer = yield from \
192 | asyncio.open_connection(host=addr,port=port)
193 |
194 | # Write b'abc':
195 | writer.write(b'\x03\x00\x00\x00abc')
196 | yield from writer.drain()
197 |
198 | # Write empty frame:
199 | writer.write(b'\x00\x00\x00\x00')
200 | yield from writer.drain()
201 |
202 | res.append('send_large_frame')
203 |
204 | # Write b'abcdef', which is too large for our chosen max_frame_len=4:
205 | writer.write(b'\x06\x00\x00\x00abcdef')
206 | yield from writer.drain()
207 |
208 | # We expect the server to disconnect us:
209 | with pytest.raises(asyncio.IncompleteReadError):
210 | yield from reader.readexactly(4)
211 |
212 | res.append('got_disconnected')
213 |
214 | # Close client:
215 | writer.close()
216 |
217 | # Start server:
218 | start_server = asyncio.start_server(server_handler,host=addr,port=port,reuse_address=True)
219 | server_task = run_timeout(start_server,tloop)
220 |
221 | # Start client:
222 | run_timeout(client(),tloop)
223 |
224 | # Close server:
225 | server_task.close()
226 | # Wait until server is closed:
227 | run_timeout(server_task.wait_closed(),loop=tloop)
228 |
229 | assert res == ['send_large_frame','got_none','got_disconnected']
230 |
231 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/proto/test_msg_from_frame.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import asyncio
3 | import struct
4 |
5 | from fcatalog.proto.serializer import Serializer,MsgDef,ProtoDef
6 | from fcatalog.proto.msg_endpoint import MsgFromFrame
7 |
8 | from fcatalog.tests.asyncio_util import run_timeout,MockFrameEndpoint
9 |
10 | ####################################################################
11 | # A dummy protocol messages definition:
12 |
13 | class Mess1(MsgDef):
14 | afields = ['a_int','b_str']
15 |
16 | def serialize(self,msg_inst):
17 | """
18 | Serialize a msg_inst to data bytes.
19 | """
20 | msg_data = b''
21 |
22 | # Write the integer as a dword.
23 | a_int = msg_inst.get_field('a_int')
24 | if not isinstance(a_int,int):
25 | raise SerializeError('a_int is not an integer!')
26 | # Assert the a_int is a dword:
27 | if not (0 <= a_int <= 0xffffffff):
28 | raise SerializeError('a_int is not a dword!')
29 |
30 |
31 | msg_data += struct.pack('I',a_int)
32 |
33 | b_str = msg_inst.get_field('b_str')
34 | b_str_bytes = b_str.encode('UTF-8')
35 | # Write the length of b_str as a dword:
36 | msg_data += struct.pack('I',len(b_str_bytes))
37 | # Write b_str:
38 | msg_data += b_str_bytes
39 |
40 | return msg_data
41 |
42 |
43 | def deserialize(self,msg_data):
44 | """
45 | Deserialize msg_data to msg_inst.
46 | """
47 | msg_inst = self.get_msg()
48 |
49 | a_int = struct.unpack('I',msg_data[0:4])[0]
50 | msg_inst.set_field('a_int',a_int)
51 | msg_data = msg_data[4:]
52 | b_str_len = struct.unpack('I',msg_data[0:4])[0]
53 | msg_data = msg_data[4:]
54 |
55 | if len(msg_data) != b_str_len:
56 | raise DeserializeError('b_str length is invalid!')
57 |
58 | b_str = msg_data.decode('UTF-8')
59 | msg_inst.set_field('b_str',b_str)
60 |
61 | return msg_inst
62 |
63 |
64 | class Mess2(MsgDef):
65 | afields = ['c_int']
66 |
67 | def serialize(self,msg_inst):
68 | """
69 | Serialize a msg_inst to data bytes.
70 | """
71 | msg_data = b''
72 |
73 | # Write the integer as a dword.
74 | c_int = msg_inst.get_field('c_int')
75 | if not isinstance(c_int,int):
76 | raise SerializeError('c_int is not an integer!')
77 | # Assert the a_int is a dword:
78 | if not (0 <= c_int <= 0xffffffff):
79 | raise SerializeError('c_int is not a dword!')
80 |
81 | msg_data += struct.pack('I',c_int)
82 |
83 | return msg_data
84 |
85 |
86 | def deserialize(self,msg_data):
87 | """
88 | Deserialize msg_data to msg_inst.
89 | """
90 | msg_inst = self.get_msg()
91 |
92 | c_int = struct.unpack('I',msg_data[0:4])[0]
93 | msg_inst.set_field('c_int',c_int)
94 | return msg_inst
95 |
96 |
97 | class MyProtoDef(ProtoDef):
98 | incoming_msgs = {0:Mess1, 1:Mess2}
99 | outgoing_msgs = {0:Mess1, 1:Mess2}
100 |
101 |
102 |
103 |
104 | ########################################################################
105 |
106 |
107 | def test_msg_from_frame_passing():
108 | """
109 | Test passing messages using msg_from_frame over a frame_endpoint.
110 | """
111 | my_loop = asyncio.new_event_loop()
112 | asyncio.set_event_loop(None)
113 |
114 | # Build a serializer:
115 | ser = Serializer(MyProtoDef)
116 |
117 | # Messages from player 1 to player 2
118 | q12 = asyncio.Queue(loop=my_loop)
119 |
120 | # Messages from player 2 to player 1
121 | q21 = asyncio.Queue(loop=my_loop)
122 |
123 | # mff1 = MsgFromFrame(msg_mapper,q21.get,q12.put)
124 | mff1 = MsgFromFrame(ser,MockFrameEndpoint(q21.get,q12.put))
125 | # mff2 = MsgFromFrame(msg_mapper,q12.get,q21.put)
126 | mff2 = MsgFromFrame(ser,MockFrameEndpoint(q12.get,q21.put))
127 |
128 | # A future that marks the end of transaction
129 | # between player1 and player2:
130 | transac_fin = asyncio.Future(loop=my_loop)
131 |
132 | @asyncio.coroutine
133 | def player1():
134 | # Send mess1 to player 2:
135 | mess1 = mff1.serializer.get_msg('Mess1')
136 | mess1.set_field('a_int',1)
137 | mess1.set_field('b_str','hello')
138 |
139 | yield from mff1.send(mess1)
140 |
141 | # Expect to receive mess2 from player 2:
142 | mess2 = yield from mff1.recv()
143 | assert mess2.msg_name == 'Mess2'
144 | assert mess2.get_field('c_int') == 2
145 |
146 | # Send mess3 to player 1:
147 | mess1 = mff1.serializer.get_msg('Mess1')
148 | mess1.set_field('a_int',8)
149 | mess1.set_field('b_str','The string')
150 | yield from mff1.send(mess1)
151 |
152 |
153 | @asyncio.coroutine
154 | def player2():
155 | # Expect to receive mess1 from player 1:
156 | mess1 = yield from mff2.recv()
157 | assert mess1.msg_name == 'Mess1'
158 | assert mess1.get_field('a_int') == 1
159 | assert mess1.get_field('b_str') == 'hello'
160 |
161 | # Send mess2 to player 1:
162 | mess2 = mff2.serializer.get_msg('Mess2')
163 | mess2.set_field('c_int',2)
164 | yield from mff2.send(mess2)
165 |
166 | # Expect to receive mess1 from player 1:
167 | mess1 = yield from mff2.recv()
168 | assert mess1.msg_name == 'Mess1'
169 | assert mess1.get_field('a_int') == 8
170 | assert mess1.get_field('b_str') == 'The string'
171 |
172 | transac_fin.set_result(True)
173 |
174 |
175 | asyncio.async(player1(),loop=my_loop)
176 | asyncio.async(player2(),loop=my_loop)
177 |
178 | run_timeout(transac_fin,loop=my_loop)
179 |
180 |
181 | def test_recv_invalid_msg():
182 | """
183 | Test receival of invalid message.
184 | """
185 | my_loop = asyncio.new_event_loop()
186 | asyncio.set_event_loop(None)
187 |
188 | ser = Serializer(MyProtoDef)
189 |
190 | class BadFrameEndpoint:
191 | @asyncio.coroutine
192 | def send(self,data_frame:bytes):
193 | """Send a frame"""
194 | return
195 |
196 | @asyncio.coroutine
197 | def recv(self) -> bytes:
198 | """Receive a frame"""
199 | return b'Invalid Message data'
200 |
201 | @asyncio.coroutine
202 | def close(self):
203 | """Close the connection"""
204 | return
205 |
206 | @asyncio.coroutine
207 | def my_cor():
208 | frame_endpoint = BadFrameEndpoint()
209 | mff = MsgFromFrame(ser,frame_endpoint)
210 |
211 | # We expect to get None (Which means the connection is considered to be
212 | # close) if the message is invalid.
213 |
214 | assert (yield from mff.recv()) is None
215 |
216 | run_timeout(my_cor(),loop=my_loop)
217 |
218 |
219 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/proto/test_serializer.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import struct
3 | from fcatalog.proto.serializer import \
4 | Msg, MsgDef,ProtoDef, Serializer,\
5 | SerializeError,DeserializeError,\
6 | pack_msg_type,unpack_msg_type,\
7 | s_string,d_string,\
8 | s_blob,d_blob,s_uint32,d_uint32
9 |
10 |
11 | def test_serializer_helpers():
12 | """
13 | Generally check the validity of the serializer helpers:
14 | """
15 | my_str = 'Hello world!'
16 | my_blob = b'This is a blob'
17 | my_uint32 = 345235
18 |
19 |
20 | data = s_string(my_str) + s_blob(my_blob) + s_uint32(my_uint32)
21 |
22 | nextl,my_str_2 = d_string(data)
23 | data = data[nextl:]
24 | nextl,my_blob_2 = d_blob(data)
25 | data = data[nextl:]
26 | nextl,my_uint32_2 = d_uint32(data)
27 | data = data[nextl:]
28 | assert len(data) == 0
29 |
30 |
31 | def test_serializer_helpers_errors():
32 | """
33 | Check some errors that might occur from serializer helpers.
34 | """
35 |
36 | short_datas = [b'',b'f',b'4g',b'132']
37 | # The following should raise an exception:
38 | for data in short_datas:
39 | with pytest.raises(DeserializeError):
40 | d_string(data)
41 |
42 | with pytest.raises(DeserializeError):
43 | d_blob(data)
44 |
45 | with pytest.raises(DeserializeError):
46 | d_uint32(data)
47 |
48 | # The length prefix here is too long. We expect an exception:
49 | bad_prefix = b'123444'
50 | with pytest.raises(DeserializeError):
51 | d_string(bad_prefix)
52 | with pytest.raises(DeserializeError):
53 | d_string(bad_prefix)
54 |
55 | # UTF-8 decoding error:
56 | # See https://docs.python.org/3/howto/unicode.html
57 | bad_utf8 = b'\x04\x00\x00\x00\x80abc'
58 | with pytest.raises(DeserializeError) as excinfo:
59 | d_string(bad_utf8)
60 | assert 'utf-8' in str(excinfo.value)
61 |
62 | def test_msg_pack_unpack():
63 | """
64 | Make sure pack_msg_type and unpack_msg_type work correctly.
65 | """
66 | data = pack_msg_type(6,b'abcdefg')
67 | msg_type, msg_data = unpack_msg_type(data)
68 | assert msg_type == 6
69 | assert msg_data == b'abcdefg'
70 |
71 |
72 | def test_msg_pack_unpack_error():
73 | """
74 | Check handling of errors with pack_msg_type and unpack_msg_type
75 | """
76 | # We can't unpack data that is too short:
77 | with pytest.raises(DeserializeError):
78 | unpack_msg_type(b'12')
79 | with pytest.raises(DeserializeError):
80 | unpack_msg_type(b'123')
81 |
82 | # This one doesn't raise an exception:
83 | unpack_msg_type(b'1234')
84 | with pytest.raises(DeserializeError):
85 | unpack_msg_type(b'123')
86 |
87 | ##################################################################
88 |
89 | class DummyMsg(MsgDef):
90 | afields = ['a_int','b_str']
91 |
92 | def serialize(self,msg_inst):
93 | """
94 | Serialize a msg_inst to data bytes.
95 | """
96 | msg_data = b''
97 |
98 | # Write the integer as a dword.
99 | a_int = msg_inst.get_field('a_int')
100 | if not isinstance(a_int,int):
101 | raise SerializeError('a_int is not an integer!')
102 | # Assert the a_int is a dword:
103 | if not (0 <= a_int <= 0xffffffff):
104 | raise SerializeError('a_int is not a dword!')
105 |
106 |
107 | msg_data += struct.pack('I',a_int)
108 |
109 | b_str = msg_inst.get_field('b_str')
110 | b_str_bytes = b_str.encode('UTF-8')
111 | # Write the length of b_str as a dword:
112 | msg_data += struct.pack('I',len(b_str_bytes))
113 | # Write b_str:
114 | msg_data += b_str_bytes
115 |
116 | return msg_data
117 |
118 |
119 | def deserialize(self,msg_data):
120 | """
121 | Deserialize msg_data to msg_inst.
122 | """
123 | msg_inst = self.get_msg()
124 |
125 | a_int = struct.unpack('I',msg_data[0:4])[0]
126 | msg_inst.set_field('a_int',a_int)
127 | msg_data = msg_data[4:]
128 | b_str_len = struct.unpack('I',msg_data[0:4])[0]
129 | msg_data = msg_data[4:]
130 |
131 | if len(msg_data) != b_str_len:
132 | raise DeserializeError('b_str length is invalid!')
133 |
134 | b_str = msg_data.decode('UTF-8')
135 | msg_inst.set_field('b_str',b_str)
136 |
137 | return msg_inst
138 |
139 |
140 | class OtherMsg(MsgDef):
141 | afields = ['c_int']
142 |
143 | def serialize(self,msg_inst):
144 | """
145 | Serialize a msg_inst to data bytes.
146 | """
147 | msg_data = b''
148 |
149 | # Write the integer as a dword.
150 | c_int = msg_inst.get_field('c_int')
151 | if not isinstance(c_int,int):
152 | raise SerializeError('c_int is not an integer!')
153 | # Assert the a_int is a dword:
154 | if not (0 <= c_int <= 0xffffffff):
155 | raise SerializeError('c_int is not a dword!')
156 |
157 | msg_data += struct.pack('I',c_int)
158 |
159 | return msg_data
160 |
161 |
162 | def deserialize(self,msg_data):
163 | """
164 | Deserialize msg_data to msg_inst.
165 | """
166 | msg_inst = self.get_msg()
167 |
168 | c_int = struct.unpack('I',msg_data[0:4])[0]
169 | msg_inst.set_field('c_int',c_int)
170 | return msg_inst
171 |
172 | class MyProtoDef(ProtoDef):
173 | incoming_msgs ={ 0:DummyMsg,1:OtherMsg }
174 | outgoing_msgs ={ 0:DummyMsg,1:OtherMsg }
175 |
176 |
177 | dummy_ser = Serializer(MyProtoDef)
178 |
179 |
180 | def test_serialize_deserialize():
181 | """
182 | Serialize and deserialize a simple message, and make sure everything is
183 | correct.
184 | """
185 | # Serialize and deserialize DummyMsg instance:
186 | msg_dummy = dummy_ser.get_msg('DummyMsg')
187 | msg_dummy.set_field('a_int',5)
188 | msg_dummy.set_field('b_str','hello world')
189 | data = dummy_ser.serialize_msg(msg_dummy)
190 | msg_dummy2 = dummy_ser.deserialize_msg(data)
191 | # Verify that the deserialization is correct:
192 | assert msg_dummy.get_field('a_int') == msg_dummy2.get_field('a_int')
193 | assert msg_dummy.get_field('b_str') == msg_dummy2.get_field('b_str')
194 | data2 = dummy_ser.serialize_msg(msg_dummy2)
195 | assert data == data2
196 |
197 | # Serialize and Deserialize OtherMsg instance:
198 | other_msg = dummy_ser.get_msg('OtherMsg')
199 | other_msg.set_field('c_int',8)
200 | data = dummy_ser.serialize_msg(other_msg)
201 | other_msg2 = dummy_ser.deserialize_msg(data)
202 | assert other_msg.get_field('c_int') == other_msg2.get_field('c_int')
203 | data2 = dummy_ser.serialize_msg(other_msg2)
204 | assert data == data2
205 |
206 |
207 | def test_serialize_deserialize_error():
208 | """
209 | Check some serialize and deserialize errors.
210 | """
211 | other_msg = dummy_ser.get_msg('OtherMsg')
212 | # I put bytes into c_int, instead of an integer:
213 | other_msg.set_field('c_int',b'asklfjalskjfkalsjdf')
214 | # We expect a SerializeError here:
215 | with pytest.raises(SerializeError):
216 | dummy_ser.serialize_msg(other_msg)
217 |
218 | # We shouldn't be able to deserialize this data:
219 | rand_data = b'askldfjlk3490f3490fsdfsdfkj'
220 | with pytest.raises(DeserializeError):
221 | dummy_ser.deserialize_msg(rand_data)
222 |
223 |
224 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/psign.py:
--------------------------------------------------------------------------------
1 | # Profiling code for the sign function.
2 |
3 | import os
4 | import random
5 | from ..catalog1 import sign,strong_hash
6 | from ..funcs_db import FuncsDB
7 |
8 | DB_PATH = '/tmp/my_test_db.db'
9 | NUM_HASHES = 16
10 |
11 | def rand_bytes(n):
12 | """
13 | Get n random bytes.
14 | """
15 | return bytes(random.getrandbits(8) for i in range(n))
16 |
17 | def go():
18 | # Pick an initial seed, for determinisim.
19 | random.seed(a='A seed for determinism of this test.')
20 |
21 | # Delete a current db if existent:
22 | try:
23 | os.remove(DB_PATH)
24 | except FileNotFoundError:
25 | pass
26 |
27 | # Build db:
28 | print('Building db...')
29 | fdb = FuncsDB(DB_PATH,NUM_HASHES)
30 |
31 | num_funcs = 640
32 | func_size = 0x200
33 | func_name_len = 0x20
34 |
35 |
36 | print('Inserts...')
37 | # Add some functions:
38 | for i in range(num_funcs):
39 | # Generate function data:
40 | func_data = rand_bytes(func_size)
41 | # Calculate signature:
42 | # s = sign(func_data,16)
43 | # Add the function to the DB:
44 | fdb.add_function('name',func_data,'comment')
45 |
46 | fdb.commit_funcs()
47 |
48 | print('Queries...')
49 | # Perform some queries:
50 | for i in range(10):
51 | func_data = rand_bytes(func_size)
52 | fdb.get_similars(func_data,5)
53 |
54 | fdb.close()
55 |
56 | print('done!')
57 |
58 |
59 | if __name__ == '__main__':
60 | go()
61 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/server/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xorpd/fcatalog_server/c86a08e76d84055a5ea5020fc25aec66e33e10e1/fcatalog/fcatalog/tests/server/__init__.py
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/server/test_fcatalog_logic.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import os
3 |
4 | from fcatalog.proto.msg_endpoint import MsgFromFrame
5 | from fcatalog.tests.asyncio_util import run_timeout,MockFrameEndpoint
6 |
7 | from fcatalog.server.fcatalog_logic import FCatalogServerLogic
8 |
9 |
10 | from fcatalog.server.fcatalog_proto import cser_serializer,\
11 | ChooseDB,AddFunction,RequestSimilars,ResponseSimilars,\
12 | FSimilar
13 |
14 | from fcatalog.proto.serializer import Serializer,ProtoDef
15 |
16 |
17 | # A protocol definition for a catalog1 client:
18 | class CatalogClientProtoDef(ProtoDef):
19 | incoming_msgs = {3:ResponseSimilars}
20 | outgoing_msgs = {\
21 | 0:ChooseDB,\
22 | 1:AddFunction,\
23 | 2:RequestSimilars}
24 |
25 | # Build a client serializer:
26 | client_ser = Serializer(CatalogClientProtoDef)
27 |
28 | # Amount of hashes to be used:
29 | NUM_HASHES = 16
30 |
31 | def test_basic_catalog1_logic(tmpdir):
32 | my_loop = asyncio.new_event_loop()
33 | asyncio.set_event_loop(None)
34 |
35 | # Messages from player 1 to player 2
36 | q12 = asyncio.Queue(loop=my_loop)
37 |
38 | # Messages from player 2 to player 1
39 | q21 = asyncio.Queue(loop=my_loop)
40 |
41 | mff1 = MsgFromFrame(cser_serializer,MockFrameEndpoint(q21.get,q12.put))
42 | mff2 = MsgFromFrame(client_ser,MockFrameEndpoint(q12.get,q21.put))
43 |
44 |
45 | # A future that marks the end of transaction
46 | # between player1 and player2:
47 | transac_fin = asyncio.Future(loop=my_loop)
48 | sl = FCatalogServerLogic(tmpdir,NUM_HASHES,mff1)
49 |
50 | server_task1 = asyncio.async(sl.client_handler(),loop=my_loop)
51 |
52 | @asyncio.coroutine
53 | def client_cor1():
54 | msg_inst = client_ser.get_msg('ChooseDB')
55 | msg_inst.set_field('db_name','my_db')
56 | yield from mff2.send(msg_inst)
57 |
58 | msg_inst = client_ser.get_msg('RequestSimilars')
59 | msg_inst.set_field('func_data',b'function data example')
60 | msg_inst.set_field('num_similars',0)
61 | yield from mff2.send(msg_inst)
62 |
63 | msg_inst = yield from mff2.recv()
64 | assert msg_inst.msg_name == 'ResponseSimilars'
65 | assert msg_inst.get_field('similars') == []
66 |
67 | # Add three functions:
68 | msg_inst = client_ser.get_msg('AddFunction')
69 | msg_inst.set_field('func_name','name1')
70 | msg_inst.set_field('func_comment','comment1')
71 | msg_inst.set_field('func_data',b'This is the function1 data')
72 | yield from mff2.send(msg_inst)
73 |
74 | msg_inst = client_ser.get_msg('AddFunction')
75 | msg_inst.set_field('func_name','name2')
76 | msg_inst.set_field('func_comment','comment2')
77 | msg_inst.set_field('func_data',b'This is the function2 data')
78 | yield from mff2.send(msg_inst)
79 |
80 | msg_inst = client_ser.get_msg('AddFunction')
81 | msg_inst.set_field('func_name','name3')
82 | msg_inst.set_field('func_comment','comment3')
83 | msg_inst.set_field('func_data',b'02938459238459283458932452345')
84 | yield from mff2.send(msg_inst)
85 |
86 |
87 | # Request similars:
88 | msg_inst = client_ser.get_msg('RequestSimilars')
89 | msg_inst.set_field('func_data',b'This is the function2 data')
90 | msg_inst.set_field('num_similars',3)
91 | yield from mff2.send(msg_inst)
92 |
93 | msg_inst = yield from mff2.recv()
94 | assert msg_inst.msg_name == 'ResponseSimilars'
95 | sims = msg_inst.get_field('similars')
96 | assert len(sims) == 2
97 |
98 | assert sims[0].name == 'name2'
99 | assert sims[0].comment == 'comment2'
100 | assert sims[0].sim_grade == NUM_HASHES
101 |
102 | assert sims[1].name == 'name1'
103 | assert sims[1].comment == 'comment1'
104 | assert sims[1].sim_grade < NUM_HASHES
105 |
106 |
107 | # Close the connection with the server:
108 | yield from mff2.close()
109 | # Wait for the server coroutine to finish:
110 | yield from asyncio.wait_for(server_task1,timeout=None,loop=my_loop)
111 | # Mark as finished:
112 | transac_fin.set_result(True)
113 |
114 |
115 | asyncio.async(client_cor1(),loop=my_loop)
116 | run_timeout(transac_fin,loop=my_loop,timeout=3.0)
117 |
118 | # We check persistance by logging in with another user:
119 |
120 | # Messages from player 1 to player 2
121 | q12 = asyncio.Queue(loop=my_loop)
122 | # Messages from player 2 to player 1
123 | q21 = asyncio.Queue(loop=my_loop)
124 | mff1 = MsgFromFrame(cser_serializer,MockFrameEndpoint(q21.get,q12.put))
125 | mff2 = MsgFromFrame(client_ser,MockFrameEndpoint(q12.get,q21.put))
126 |
127 |
128 | # A future that marks the end of transaction
129 | # between player1 and player2:
130 | sl = FCatalogServerLogic(tmpdir,NUM_HASHES,mff1)
131 | transac_fin = asyncio.Future(loop=my_loop)
132 | server_task2 = asyncio.async(sl.client_handler(),loop=my_loop)
133 |
134 | @asyncio.coroutine
135 | def client_cor2():
136 | # Choose a database:
137 | msg_inst = client_ser.get_msg('ChooseDB')
138 | msg_inst.set_field('db_name','my_db')
139 | yield from mff2.send(msg_inst)
140 |
141 | # Request similars:
142 | msg_inst = client_ser.get_msg('RequestSimilars')
143 | msg_inst.set_field('func_data',b'This is the function2 data')
144 | msg_inst.set_field('num_similars',3)
145 | yield from mff2.send(msg_inst)
146 |
147 | msg_inst = yield from mff2.recv()
148 | assert msg_inst.msg_name == 'ResponseSimilars'
149 | sims = msg_inst.get_field('similars')
150 | assert len(sims) == 2
151 |
152 | assert sims[0].name == 'name2'
153 | assert sims[0].comment == 'comment2'
154 | assert sims[0].sim_grade == NUM_HASHES
155 |
156 | assert sims[1].name == 'name1'
157 | assert sims[1].comment == 'comment1'
158 | assert sims[1].sim_grade < NUM_HASHES
159 |
160 |
161 | # Close the connection with the server:
162 | yield from mff2.close()
163 | # Wait for the server coroutine to finish:
164 | yield from asyncio.wait_for(server_task2,timeout=None,loop=my_loop)
165 | # Mark as finished:
166 | transac_fin.set_result(True)
167 |
168 |
169 | asyncio.async(client_cor2(),loop=my_loop)
170 | run_timeout(transac_fin,loop=my_loop,timeout=3.0)
171 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/server/test_fcatalog_proto.py:
--------------------------------------------------------------------------------
1 | from fcatalog.server.fcatalog_proto import \
2 | ChooseDB,AddFunction,RequestSimilars,ResponseSimilars,\
3 | FSimilar
4 |
5 | from fcatalog.proto.serializer import Serializer,ProtoDef
6 |
7 |
8 | # Create a full catalog1 protocol definition:
9 |
10 | class FullCatalog1ProtoDef(ProtoDef):
11 | incoming_msgs = {\
12 | 0:ChooseDB,\
13 | 1:AddFunction,\
14 | 2:RequestSimilars,\
15 | 3:ResponseSimilars}
16 | outgoing_msgs = {\
17 | 0:ChooseDB,\
18 | 1:AddFunction,\
19 | 2:RequestSimilars,\
20 | 3:ResponseSimilars}
21 |
22 | ser = Serializer(FullCatalog1ProtoDef)
23 |
24 |
25 | def test_choose_db_msg():
26 | """
27 | Verify serialization/deserialization of ChooseDB message.
28 | """
29 | msg_inst = ser.get_msg('ChooseDB')
30 | msg_inst.set_field('db_name','my_database')
31 | msg_data = ser.serialize_msg(msg_inst)
32 | msg_data2 = ser.serialize_msg(ser.deserialize_msg(msg_data))
33 | assert msg_data == msg_data2
34 |
35 |
36 | def test_add_function_msg():
37 | """
38 | Verify serialization/deserialization of AddFunction message.
39 | """
40 | msg_inst = ser.get_msg('AddFunction')
41 | msg_inst.set_field('func_name','function name')
42 | msg_inst.set_field('func_comment','comment')
43 | msg_inst.set_field('func_data',b'This is the data')
44 |
45 | msg_data = ser.serialize_msg(msg_inst)
46 | msg_data2 = ser.serialize_msg(ser.deserialize_msg(msg_data))
47 | assert msg_data == msg_data2
48 |
49 |
50 | def test_request_similars_msg():
51 | """
52 | Verify serialization/deserialization of RequestSimilars message.
53 | """
54 | msg_inst = ser.get_msg('RequestSimilars')
55 | msg_inst.set_field('func_data',b'Function data example')
56 | msg_inst.set_field('num_similars',8)
57 |
58 | msg_data = ser.serialize_msg(msg_inst)
59 | msg_data2 = ser.serialize_msg(ser.deserialize_msg(msg_data))
60 | assert msg_data == msg_data2
61 |
62 |
63 | def test_response_similars_msg():
64 | """
65 | Verify serialization/deserialization of Response message.
66 | """
67 | msg_inst = ser.get_msg('ResponseSimilars')
68 | sims = []
69 | sims.append(FSimilar(\
70 | name='name1',\
71 | comment='comment1',\
72 | sim_grade=5))
73 |
74 | sims.append(FSimilar(\
75 | name='name2',\
76 | comment='comment2',\
77 | sim_grade=8))
78 | msg_inst.set_field('similars',sims)
79 |
80 | msg_data = ser.serialize_msg(msg_inst)
81 | msg_data2 = ser.serialize_msg(ser.deserialize_msg(msg_data))
82 | assert msg_data == msg_data2
83 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/test_catalog1.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from fcatalog.catalog1 import slow_sign,sign,strong_hash,Catalog1Error
4 |
5 | def isdword(x):
6 | """
7 | Check if x is a dword.
8 | An integer between 0 and 2**32 - 1, inclusive.
9 | """
10 | if not isinstance(x,int):
11 | return False
12 |
13 | if x < 0:
14 | return False
15 |
16 | if x > 2**32:
17 | return False
18 |
19 | return True
20 |
21 |
22 | def test_sign_basic():
23 | """
24 | Sign some strings.
25 | """
26 | res = sign(b'afdasdklfjaskljdfaklsjdf',num_perms=16)
27 | assert len(res) == 16
28 | for x in res:
29 | assert isdword(x)
30 |
31 | res = \
32 | sign(b'3kl4jfklsdjfklasjf8934j9sjdf9adfkalsdjflkasjdflkasdf',num_perms=20)
33 | assert len(res) == 20
34 | for x in res:
35 | assert isdword(x)
36 |
37 | res = sign(b'4095809348529384523904582390485092384509283',num_perms=32)
38 | assert len(res) == 32
39 | for x in res:
40 | assert isdword(x)
41 |
42 |
43 | def test_sign_long_data():
44 | """
45 | Sign long data
46 | """
47 | res = sign((b'asdfklasjdf') * 40,num_perms=20)
48 | assert len(res) == 20
49 | for x in res:
50 | assert isdword(x)
51 |
52 |
53 | def test_sign_deterministic():
54 | """
55 | Make sure that signing the same data results in the same result
56 | """
57 | res1 = sign(b'3kl4jfklsdjfklasjf8934j9sjdf9adfkalsdjflkasjdflkasdf',\
58 | num_perms=20)
59 | res2 = sign(b'3kl4jfklsdjfklasjf8934j9sjdf9adfkalsdjflkasjdflkasdf',\
60 | num_perms=20)
61 | assert res1 == res2
62 |
63 |
64 | ###########################################
65 | ###########################################
66 |
67 |
68 | def calc_sim(sgn1,sgn2):
69 | """
70 | Calculate the similarity between two signatures of the same size.
71 | """
72 | total = 0
73 | assert len(sgn1) == len(sgn2)
74 |
75 | for i in range(len(sgn1)):
76 | if sgn1[i] == sgn2[i]:
77 | total += 1
78 |
79 | return total
80 |
81 |
82 | def test_sign_similars():
83 | """
84 | Sign similar strings and expect similar signatures.
85 | Sign very different strings and expect zero similarity.
86 | """
87 | s1 = sign(b'hello world he2llo world',16)
88 | s2 = sign(b'hello world he1llo world',16)
89 | assert calc_sim(s1,s2) > 6
90 |
91 | s1 = sign(b'akjdflkasjflkasjlfkasjdflkjaslkdfjaslkjfsaklfdjaslkjdfsf',16)
92 | s2 = sign(b'4039582903850923850928345982309589023845823458230945',16)
93 | assert calc_sim(s1,s2) == 0
94 |
95 |
96 | ############################################
97 | ############################################
98 |
99 | def test_basic_strong_hash():
100 | """
101 | Make sure that strong_hash function works.
102 | """
103 | # Basic invocation:
104 | res = strong_hash(b'adfklasjdflkajsdflkajsdf')
105 | assert isinstance(res,bytes)
106 |
107 | # Consistency:
108 | res1 = strong_hash(b'34908523904kf9034fk9032kf903f4k')
109 | res2 = strong_hash(b'34908523904kf9034fk9032kf903f4k')
110 | assert res1 == res2
111 |
112 | # Different results for different input:
113 | res1 = strong_hash(b'34908523904kf9034fk9032kf903f4ka')
114 | res2 = strong_hash(b'34908523904kf9034fk9032kf903f4kb')
115 | assert res1 != res2
116 | # But length is always the same:
117 | assert len(res1) == len(res2)
118 |
119 | ##############################################
120 | ##############################################
121 |
122 | def test_slow_matches_fast():
123 | """
124 | Make sure that the two implementations of catalog1 (The python and the C
125 | one) match.
126 | """
127 | datas = []
128 | datas.append(b'klsfjsalkdfjlksajfdlksaj340985390485ksldjflksdflksdjf')
129 | datas.append(b'abc' * 205)
130 | datas.append(b'349085092384590903485309485' * 300)
131 | data = b'kslajflksajfaiosueroiqwuroiqwer9034851283904lkfjsalkfasdfsf'
132 |
133 | for data in datas:
134 | assert slow_sign(data,4) == sign(data,4)
135 |
136 |
137 |
138 | def test_short_input():
139 | """
140 | See what happens if sign or slow_sign are given a too short input (below 4
141 | bytes).
142 | """
143 | # Should raise an error:
144 | with pytest.raises(Catalog1Error):
145 | sign(b'123',16)
146 |
147 | # Should raise an error:
148 | with pytest.raises(Catalog1Error):
149 | slow_sign(b'123',16)
150 |
151 | # Will not raise an error:
152 | sign(b'1234',16)
153 | slow_sign(b'1234',16)
154 |
155 |
--------------------------------------------------------------------------------
/fcatalog/fcatalog/tests/test_funcs_db.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import pytest
3 | import sqlite3
4 | import random
5 | import string
6 | import os
7 |
8 | from fcatalog.funcs_db import FuncsDB
9 | from fcatalog.catalog1 import sign,strong_hash
10 |
11 |
12 | # Num hashes used for testing purposes:
13 | NUM_HASHES = 16
14 |
15 |
16 | class DebugFuncsDB(FuncsDB):
17 | def count(self):
18 | """
19 | Count the amount of lines inside the funcs table.
20 | """
21 | c = self._conn.cursor()
22 |
23 | cmd_count = "SELECT COUNT(*) from funcs"
24 | c.execute(cmd_count)
25 | res = c.fetchone()[0]
26 |
27 | return res
28 |
29 |
30 | @pytest.fixture(scope='function')
31 | def fdb_mem(request):
32 | """
33 | Create a FuncsDB instance in memory.
34 | """
35 | # Build database in memory. Should be quicker.
36 | fdb = DebugFuncsDB(':memory:',NUM_HASHES)
37 |
38 | def fin():
39 | """Finalizer for fdb"""
40 | # Make sure to close fdb.
41 | fdb.close()
42 |
43 | request.addfinalizer(fin)
44 | return fdb
45 |
46 |
47 |
48 | @pytest.fixture(scope='function')
49 | def fdb(request,tmpdir):
50 | """
51 | Create a FuncsDB instance on disk.
52 | """
53 | # tmpdir = tempfile.mkdtemp()
54 | db_path = os.path.join(tmpdir,'my_temp_db.db')
55 | # Build database in memory. Should be quicker.
56 | fdb = DebugFuncsDB(db_path,NUM_HASHES)
57 |
58 | def fin():
59 | """Finalizer for fdb"""
60 | # Make sure to close fdb.
61 | fdb.close()
62 | # Remove temporary directory:
63 | # shutil.rmtree(tmpdir)
64 |
65 | request.addfinalizer(fin)
66 | return fdb
67 |
68 |
69 | def test_funcs_db_basic(fdb_mem):
70 | """
71 | Create a new database using FuncsDB.
72 | """
73 | pass
74 |
75 |
76 | def test_add_function(fdb_mem):
77 | """
78 | Try to add a 'reversed' new function into the database.
79 | """
80 | # No functions at the beginning:
81 | assert fdb_mem.count() == 0
82 | # Add one function:
83 | fdb_mem.add_function('func_name1',b'func_data1','func_comment1')
84 | assert fdb_mem.count() == 1
85 | # Add another function:
86 | fdb_mem.add_function('func_name2',b'func_data2','func_comment2')
87 | assert fdb_mem.count() == 2
88 | # Add a function with func_data that already exists. Should replace the
89 | # earlier func_data2 record (Instead of adding a new row).
90 | fdb_mem.add_function('func_name3',b'func_data2','func_comment3')
91 | assert fdb_mem.count() == 2
92 |
93 |
94 | def test_get_similars_basic(fdb_mem):
95 | """
96 | Try to run get_similars and see if it doesn't crash.
97 | """
98 | res = fdb_mem.get_similars(b'adfasdfasdf',5)
99 | assert isinstance(res,list)
100 |
101 | # Add a function and request a function similar to that function. We expect
102 | # to get one result:
103 | fdb_mem.add_function('func_name',b'func_data','func_comment')
104 | res = fdb_mem.get_similars(b'func_data',num_similars=3)
105 | assert len(res) == 1
106 |
107 | # Add another function, and request functions similar to that function. We
108 | # expect to get all the functions, where func2 will be first on the list:
109 | fdb_mem.add_function('func_name2',b'func_data2','func_comment2')
110 | res = fdb_mem.get_similars(b'func_data2',num_similars=3)
111 | assert len(res) == 2
112 |
113 | # Hash should match:
114 | assert res[0].func_hash == strong_hash(b'func_data2')
115 | assert res[1].func_hash != strong_hash(b'func_data2')
116 |
117 | # Signature should match:
118 | assert res[0].func_sig == sign(b'func_data2',NUM_HASHES)
119 |
120 | # Request for just one similars, and make sure we get only one, although
121 | # the DB contains two functions:
122 | res = fdb_mem.get_similars(b'func_data',num_similars=1)
123 | assert len(res) == 1
124 |
125 |
126 | ########################################
127 | ########################################
128 |
129 |
130 | def test_random_seed(fdb_mem):
131 | """
132 | We expect consistency when using python's random with seed.
133 | """
134 | random.seed(a='this is the seed')
135 | res = random.randint(0,0xffffffff)
136 | random.seed(a='this is the seed')
137 | assert res == random.randint(0,0xffffffff)
138 |
139 |
140 | def rand_bytes(n):
141 | """
142 | Get n random bytes.
143 | """
144 | return bytes(random.getrandbits(8) for i in range(n))
145 |
146 | def rand_ascii_lowercase(n):
147 | """
148 | Get n random lowercase ascii characters. Returns a string of size n.
149 | """
150 | return ''.join(random.choice(string.ascii_lowercase) \
151 | for _ in range(n))
152 |
153 |
154 | def num_matches(s1,s2):
155 | """
156 | Calculate the amount of entries where s1[i] == s2[i]
157 | """
158 | assert len(s1) == len(s2)
159 | return sum(1 for i in range(len(s1)) if s1[i] == s2[i])
160 |
161 | def test_num_matches():
162 | """
163 | Make sure that num_matches works correctly.
164 | """
165 | s1 = [1,2,3,4]
166 | s2 = [1,2,8,4]
167 | s3 = [0,9,4,3]
168 | assert num_matches(s1,s2) == 3
169 | assert num_matches(s1,s1) == 4
170 | assert num_matches(s1,s3) == 0
171 |
172 | def change_random_byte(bs):
173 | """
174 | Change a random byte to another random byte in a stream of bytes.
175 | Return the new bytes stream.
176 | """
177 | # Nothing to do if bs is empty:
178 | if len(bs) == 0:
179 | return bs
180 |
181 | # Pick a random index:
182 | idx = random.randrange(len(bs))
183 | return bs[:idx] + rand_bytes(1) + bs[idx+1:]
184 |
185 |
186 | class TestGetSimilars(unittest.TestCase):
187 | def setUp(self):
188 | """Tests setup"""
189 | # Build database in memory. Should be quicker.
190 | self.fdb_mem = DebugFuncsDB(':memory:',NUM_HASHES)
191 |
192 | # Pick an initial seed, for determinisim.
193 | random.seed(a='A seed for determinism of this test.')
194 |
195 | self.num_funcs = 0x400
196 | self.func_size = 0xf0
197 | self.func_name_len = 0x20
198 |
199 | # Index of the special function. We will later search a small variation
200 | # of the function inside the database, and expect to find this
201 | # function.
202 | special_func_idx = random.randrange(self.num_funcs)
203 | special_func = None
204 |
205 | # Insert functions to db:
206 | for i in range(self.num_funcs):
207 | # Generate function data:
208 | func_data = rand_bytes(self.func_size)
209 | # Generate random name and comment:
210 | func_name = rand_ascii_lowercase(self.func_name_len)
211 | func_comment = rand_ascii_lowercase(self.func_name_len)
212 |
213 | # s = sign(func_data,16)
214 | # Add the function:
215 | self.fdb_mem.add_function(func_name,func_data,func_comment)
216 |
217 | # If this is the special function, we keep it for later.
218 | if i == special_func_idx:
219 | self.special_func_data = bytes(func_data)
220 | self.special_func_name = func_name
221 | self.special_func_comment = func_comment
222 |
223 | # Commit functions to database.
224 | # Maybe not really effective, as we are using a memory database.
225 | # This statement was added here to check if commit_funcs works and
226 | # doesn't raise an exception.
227 | self.fdb_mem.commit_funcs()
228 |
229 |
230 | def test_match_random_func(self):
231 | """
232 | Try to find similarity for a random function. We expect that now
233 | results will show up at all.
234 | """
235 | # Generate a random function:
236 | func_data = rand_bytes(self.func_size)
237 | sims = self.fdb_mem.get_similars(func_data,1)
238 | # We assume that no function is similar to func_data (Even in one entry),
239 | # so we expect to get no results. Getting a result is possible, but very
240 | # surprising.
241 | assert len(sims) == 0
242 |
243 |
244 | def test_match_special_func(self):
245 | """
246 | Try to find similarity for the special function. We expect to find it.
247 | """
248 | sims = self.fdb_mem.get_similars(self.special_func_data,5)
249 | # We assume that only the special function will return:
250 | assert len(sims) == 1
251 |
252 | assert sims[0].func_hash == strong_hash(self.special_func_data)
253 | assert sims[0].func_name == self.special_func_name
254 | assert sims[0].func_comment == self.special_func_comment
255 | assert sims[0].func_sig == sign(self.special_func_data,NUM_HASHES)
256 | assert sims[0].func_grade == NUM_HASHES
257 |
258 |
259 | def test_match_like_special_func(self):
260 | """
261 | Try to find similarity for a function that is just a bit different from
262 | the special function. We expect to find the special function.
263 | """
264 | func_data = self.special_func_data
265 | # Change some bytes randomly:
266 | for i in range(5):
267 | func_data = change_random_byte(func_data)
268 |
269 | sims = self.fdb_mem.get_similars(func_data,5)
270 | # We assume that only the special function will return:
271 | assert len(sims) == 1
272 |
273 | assert sims[0].func_hash == strong_hash(self.special_func_data)
274 | assert sims[0].func_name == self.special_func_name
275 | assert sims[0].func_comment == self.special_func_comment
276 | assert sims[0].func_sig == sign(self.special_func_data,NUM_HASHES)
277 | assert sims[0].func_grade < NUM_HASHES
278 |
279 |
280 | def tearDown(self):
281 | """Tests teardown"""
282 | # Close the database:
283 | self.fdb_mem.close()
284 |
285 |
286 | def test_get_similars_few_similars(fdb_mem):
287 | """
288 | Check the situation of a few matching similar functions.
289 | """
290 | # Data of some functions:
291 | f1 = b'ioewjfoi1wjeioj43ioj23io5j43io5joiasjfdiaosdjfaijdfooisdf'
292 | f2 = b'ioewjfoi2wjeioj43ioj23io5j43io5joiasjfdiaosdjfaijdfooisdf'
293 | f3 = b'ioewjfoi2wjei3j43ioj23io5j43io5joiasjfdiaosdjfaijdfooisdf'
294 | f4 = b'ioewjfoi2wjei3j43ioj23i45j43io5joiasjfdiaosdjfaijdfooisdf'
295 | f5 = b'ioewjfoi1wjeioj43ioj23io5j43io5jasjfdiaosdjfaijdfooisdf'
296 | f6 = b'ioewjfo1wCeioj43ioj23io5j43io5jasjfdiaosdjfaijdfooisdf'
297 | # f7 is non related in its content to the ther 6:
298 | f7 = b'@#%!%!@#$!@#$$$$$$$$$$$$$$$$@#$@#$@#$@#$@#$@#$'
299 |
300 | # Add a few similar functions:
301 | fdb_mem.add_function('f1',f1,'f1')
302 | fdb_mem.add_function('f2',f2,'f2')
303 | fdb_mem.add_function('f3',f3,'f3')
304 | fdb_mem.add_function('f4',f4,'f4')
305 | fdb_mem.add_function('f5',f5,'f5')
306 | fdb_mem.add_function('f6',f6,'f6')
307 | fdb_mem.add_function('f7',f7,'f7')
308 |
309 |
310 | # Search with function 1's data:
311 | res = fdb_mem.get_similars(f1,10)
312 | # f1 to f6 should match somehow:
313 | assert len(res) == 6
314 | assert res[0].func_name == 'f1'
315 |
316 | def get_dist(i):
317 | return num_matches(res[i].func_sig,sign(f1,NUM_HASHES))
318 |
319 | dists = [get_dist(i) for i in range(len(res))]
320 | # Assert that dists is sorted (monotonically nonincreasing):
321 | assert all(dists[i] >= dists[i+1] for i in range(len(dists)-1))
322 |
323 | # The next result should be less relevant:
324 | assert get_dist(1) < NUM_HASHES
325 |
326 | # Search with function 7's data:
327 | res = fdb_mem.get_similars(f7,10)
328 | # Only f7 should match:
329 | assert len(res) == 1
330 | assert res[0].func_name == 'f7'
331 |
332 |
--------------------------------------------------------------------------------
/fcatalog/setup.cfg:
--------------------------------------------------------------------------------
1 | [bdist_wheel]
2 |
--------------------------------------------------------------------------------
/fcatalog/setup.py:
--------------------------------------------------------------------------------
1 | """A setuptools based setup module.
2 |
3 | See:
4 | https://packaging.python.org/en/latest/distributing.html
5 | https://github.com/pypa/sampleproject
6 | """
7 |
8 | # Always prefer setuptools over distutils
9 | from setuptools import setup, find_packages
10 | # To use a consistent encoding
11 | from codecs import open
12 | from os import path
13 |
14 | here = path.abspath(path.dirname(__file__))
15 |
16 | # Get the long description from the relevant file
17 | with open(path.join(here, 'README.md'), encoding='utf-8') as f:
18 | long_description = f.read()
19 |
20 | setup(
21 | name='fcatalog',
22 |
23 | # Versions should comply with PEP440. For a discussion on single-sourcing
24 | # the version across setup.py and the project code, see
25 | # https://packaging.python.org/en/latest/single_source_version.html
26 | version='0.1.0',
27 |
28 | description='Python lib for the fcatalog server',
29 | long_description=long_description,
30 |
31 | # The project's main homepage.
32 | url='http://fcatalog.xorpd.net',
33 |
34 | # Author details
35 | author='xorpd',
36 | author_email='xorpd@xorpd.net',
37 |
38 | # Choose your license
39 | license='GPLv3',
40 |
41 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
42 | classifiers=[
43 | # How mature is this project? Common values are
44 | # 3 - Alpha
45 | # 4 - Beta
46 | # 5 - Production/Stable
47 | 'Development Status :: 3 - Alpha',
48 |
49 | # Indicate who your project is intended for
50 | 'Intended Audience :: Reverse Engineers',
51 | 'Topic :: Software Reversing:: Functions Similarity',
52 |
53 | # Pick your license as you wish (should match "license" above)
54 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
55 |
56 | # Specify the Python versions you support here. In particular, ensure
57 | # that you indicate whether you support Python 2, Python 3 or both.
58 | 'Programming Language :: Python :: 3.4',
59 | ],
60 |
61 | # What does your project relate to?
62 | keywords='functions similarity server reversing asyncio',
63 |
64 | # You can just specify the packages manually here if your project is
65 | # simple. Or you can use find_packages().
66 | packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
67 |
68 | # List run-time dependencies here. These will be installed by pip when
69 | # your project is installed. For an analysis of "install_requires" vs pip's
70 | # requirements files see:
71 | # https://packaging.python.org/en/latest/requirements.html
72 | install_requires=['bidict'],
73 |
74 | # List additional groups of dependencies here (e.g. development
75 | # dependencies). You can install these using the following syntax,
76 | # for example:
77 | # $ pip install -e .[dev,test]
78 | extras_require={
79 | 'dev': [],
80 | 'test': ['pytest'],
81 | },
82 |
83 | # If there are data files included in your packages that need to be
84 | # installed, specify them here. If using Python 2.6 or less, then these
85 | # have to be included in MANIFEST.in as well.
86 | package_data={
87 | 'sample': ['package_data.dat'],
88 | },
89 |
90 | # To provide executable scripts, use entry points in preference to the
91 | # "scripts" keyword. Entry points provide cross-platform support and allow
92 | # pip to create the appropriate form of executable for the target platform.
93 | entry_points={
94 | 'console_scripts': [
95 | 'sample=sample:main',
96 | ],
97 | },
98 | )
99 |
--------------------------------------------------------------------------------
/fcatalog_server:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python3
2 |
3 | import logging
4 | import os
5 | import sys
6 | import signal
7 | import asyncio
8 | from fcatalog import server_conf
9 |
10 | from fcatalog.server.fcatalog_logic import FCatalogServerLogic
11 | from fcatalog.server.fcatalog_proto import cser_serializer
12 | from fcatalog.proto.frame_endpoint import TCPFrameEndpoint
13 | from fcatalog.proto.msg_endpoint import MsgFromFrame
14 |
15 | LOG_FILE_PATH = '/home/ufcatalog/log/fcatalog.log'
16 | logging.basicConfig(filename=LOG_FILE_PATH,level=logging.INFO)
17 |
18 | # Set up logger:
19 | logger = logging.getLogger(__name__)
20 |
21 | @asyncio.coroutine
22 | def client_handler(reader,writer):
23 | """
24 | A coroutine for handling one client.
25 | """
26 | try:
27 | frame_endpoint = TCPFrameEndpoint(reader,writer)
28 | msg_endpoint = MsgFromFrame(cser_serializer,frame_endpoint)
29 | sl = FCatalogServerLogic(server_conf.DB_BASE_PATH,\
30 | server_conf.NUM_HASHES,\
31 | msg_endpoint)
32 |
33 | # Handle one client:
34 | yield from sl.client_handler()
35 |
36 | except Exception:
37 | logging.exception('Unhandled exception at client_handler')
38 |
39 |
40 | def start_server(host,port):
41 | """
42 | Start a fcatalog server on host and port .
43 | """
44 | # Create the server_conf.DB_BASE_PATH if not existent:
45 | if not os.path.exists(server_conf.DB_BASE_PATH):
46 | os.makedirs(server_conf.DB_BASE_PATH)
47 |
48 | loop = asyncio.get_event_loop()
49 | coro = asyncio.start_server(client_handler,host=host,port=port,\
50 | loop=loop,reuse_address=True)
51 | server = loop.run_until_complete(coro)
52 |
53 | def ask_exit(signame):
54 | """
55 | Exit properly after receiving a signal.
56 | """
57 | print('Received signal {}'.format(signame))
58 | print('Sending signal to close server...')
59 | server.close()
60 |
61 | # Set loop handlers to SIGINT and SIGTERM:
62 | for signame in ('SIGINT', 'SIGTERM'):
63 | loop.add_signal_handler(getattr(signal, signame),
64 | lambda: ask_exit(signame))
65 |
66 | print('FCatalog server is running on {}:{}'.format(host,port))
67 |
68 | loop.run_until_complete(server.wait_closed())
69 | loop.close()
70 |
71 | ###################################################################
72 |
73 | if __name__ == '__main__':
74 | if len(sys.argv) != 3:
75 | print('Usage: {} local_host local_port'.format(sys.argv[0]))
76 | sys.exit(2)
77 |
78 | local_host = sys.argv[1]
79 | local_port = int(sys.argv[2])
80 | start_server(local_host,local_port)
81 |
--------------------------------------------------------------------------------
/get_deps:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # A script to get the required dependencies for fcatalog server.
3 | # Run this script when you have internet connection, and python3 installed.
4 | # This script will fill the dep/ directory with all the required stuff for
5 | # offline installation.
6 |
7 | # Stop on any error:
8 | set -e
9 |
10 | ###################################
11 | # Get Virtualenv script:
12 | ###################################
13 |
14 | # Version of virtualenv:
15 | VERSION=13.1.2
16 | # Virtualenv tgz filename:
17 | VENV_TGZ=virtualenv-$VERSION.tar.gz
18 | VENV_DIR=virtualenv-$VERSION
19 |
20 | # Environment name:
21 | INITIAL_ENV=temp_env
22 |
23 | # Python3 interpreter:
24 | PYTHON=$(which python3)
25 |
26 | # URL of pypi to get virtualenv package:
27 | URL_BASE=https://pypi.python.org/packages/source/v/virtualenv
28 |
29 | printf "\nDownloading virtualenv:\n\n"
30 |
31 | # Download virtualenv:
32 | curl -O $URL_BASE/$VENV_TGZ
33 |
34 | # Create the dep directory:
35 | mkdir -p dep/
36 |
37 | cp $VENV_TGZ dep/
38 | # Open VENV_TGZ:
39 | tar xzf $VENV_TGZ
40 | # Remove virtual env if existent:
41 | rm -rf $INITIAL_ENV
42 |
43 | # Create an initial virtual env:
44 | $PYTHON $VENV_DIR/virtualenv.py -p $PYTHON $INITIAL_ENV
45 |
46 | # The tgz file is not needed here anymore. We delete it:
47 | rm -rf $VENV_TGZ
48 | # The virtualenv directory is not needed here anymore:
49 | rm -rf $VENV_DIR
50 |
51 | ####################################
52 | # Create an fcatalog wheel:
53 | ####################################
54 | printf "\nCreating an fcatalog wheel\n\n"
55 | # Install wheel into pip.
56 | $INITIAL_ENV/bin/pip install wheel
57 |
58 | cd fcatalog
59 |
60 | # Remove dirs from a previous build, if existent:
61 | rm -rf build/
62 | rm -rf dist/
63 | rm -rf fcatalog.egg-info/
64 |
65 |
66 | # Create a wheel:
67 | ../$INITIAL_ENV/bin/python setup.py bdist_wheel
68 |
69 | cd ..
70 |
71 | mkdir -p dep/packages
72 |
73 | # Copy the resulting wheel into dep:
74 | cp -R fcatalog/dist/*.whl dep/packages/
75 |
76 |
77 | ####################################
78 | # Get required python packages:
79 | ####################################
80 |
81 | printf "\nGetting required python packages:\n\n"
82 |
83 |
84 | # Downloads packages
85 | $INITIAL_ENV/bin/pip install --download dep/packages -r requirements.txt
86 |
87 | # Remove the temporary python environment:
88 | rm -rf $INITIAL_ENV
89 |
90 | set +e
91 |
--------------------------------------------------------------------------------
/ideas.txt:
--------------------------------------------------------------------------------
1 | 1.9.2015
2 | by xorpd.
3 |
4 | This project will allow saving a database of known/reversing functions, and then
5 | finding similarities between archived functions and functions in new IDBs.
6 |
7 |
8 | Main plan:
9 |
10 |
11 | Server:
12 | -------
13 |
14 | - Saves a database of all functions known:
15 | For every function:
16 | - sha256 hash (To identify the function 1 to 1)
17 | - Catalog1 hash (To check similarities).
18 | - Reverser's name.
19 | - Function name (As given by the reverser).
20 | - Head comment (As given by the reverser).
21 |
22 | - Handles the following request:
23 | - Given a function:
24 | - Search for exact sha256 match. If found, return it.
25 | - Return the function with the closest Catalog1 hash (If it is close enough.
26 | Don't return it if it is has a very low grade).
27 |
28 |
29 | Client:
30 | -------
31 |
32 | - Could be run from outside IDA?
33 |
34 | Main functions:
35 |
36 | - Find known: Send all functions to the server (The functions themselves).
37 | - Wait for response. For each function, a tuple:
38 | {reverser_name:, func_name:, head_comment, exact_match: } is sent back
39 |
40 | - Every function for which a similarity was found will be given a name of the
41 | format: SIMILAR__{grade}__name
42 | The head comment will be changed to contain some more information.
43 |
44 |
45 | - Commit reversing.
46 | - Send all the functions that were reversed (Given an important name) to the
47 | server. Every function will be sent using the format:
48 |
49 | {reverser_name:, func_name: , func_data: ,head_comment: }
50 |
51 | - Functions that begin with SIMILAR__ will not be sent.
52 | - Functions without a name will not be sent.
53 |
54 |
55 |
--------------------------------------------------------------------------------
/install:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # This script installs fcatalog_server. The installation requires root
4 | # privileges.
5 | # Note that you have to run get_deps first.
6 |
7 | # Stop on any error:
8 | set -e
9 |
10 | # Name of the new user to be added for use with the fcatalog server:
11 | USER_NAME="ufcatalog"
12 |
13 | # Virtualenv environment name:
14 | ENV_NAME="${USER_NAME}_env"
15 |
16 | # Python3 interpreter:
17 | PYTHON=$(which python3)
18 |
19 | # Make and make install catalog1.
20 | cd catalog1
21 | echo "Building libcatalog1:"
22 | make
23 | echo "Installing libcatalog1"
24 | make install
25 | # Refresh the linker cache:
26 | sudo ldconfig
27 | echo "Testing libcatalog1:"
28 | ./bin/test_catalog1
29 |
30 | cd ..
31 |
32 | ##########################################
33 | # Add a new system user:
34 | ##########################################
35 |
36 | # See here:
37 | # http://askubuntu.com/questions/29359/how-to-add-user-without-home
38 | # Remove the user $USER_NAME together with his home directory:
39 | set +e
40 | userdel -rf $USER_NAME
41 | set -e
42 | useradd -s /bin/false -m -d /home/$USER_NAME $USER_NAME
43 |
44 | # Create a directory for fcatalog databases:
45 | mkdir -p /var/lib/fcatalog
46 | # Make $USER_NAME the owner of the directory:
47 | sudo chown -R $USER_NAME:$USER_NAME /var/lib/fcatalog
48 |
49 | ###########################################
50 | # Create a virtualenv at /home/${USER_NAME}
51 | ###########################################
52 |
53 | # Keep the current path (Main tree):
54 | BASE_DIR=$PWD
55 |
56 | cd dep/
57 |
58 | # Get the name of the virtualenv tgz:
59 | VENV_TGZ=""
60 | for f in virtualenv*.tar.gz; do VENV_TGZ=$f; done
61 |
62 | # Get the filename without the extension. This gives the expected name of the
63 | # resulting directory:
64 | VENV_DIR="${VENV_TGZ%*.tar.gz}"
65 |
66 | cp $VENV_TGZ /home/${USER_NAME}/$VENV_TGZ
67 |
68 | cd /home/${USER_NAME}
69 |
70 | # Open VENV_TGZ:
71 | tar xzf $VENV_TGZ
72 |
73 | # Create an initial virtual env at the home of $USER_NAME
74 | sudo -u ${USER_NAME} $PYTHON $VENV_DIR/virtualenv.py -p $PYTHON $ENV_NAME
75 |
76 | # Go back to dep/
77 | cd $BASE_DIR/dep
78 |
79 | # Remove the virtualenv dir and tgz. They are not needed anymore:
80 | rm -rf /home/${USER_NAME}/$VENV_DIR
81 | rm -rf /home/${USER_NAME}/$VENV_TGZ
82 |
83 | cd /home/${USER_NAME}
84 |
85 | # Make a bin directory:
86 | sudo -u ${USER_NAME} mkdir -p bin/
87 |
88 | # Make a log directory:
89 | sudo -u ${USER_NAME} mkdir -p log/
90 |
91 | #######################################################
92 | # Install all python dependencies inside the virtualenv
93 | #######################################################
94 |
95 | # Copy dependencies:
96 | cp -R $BASE_DIR/dep /home/${USER_NAME}/dep
97 | sudo chown -R $USER_NAME:$USER_NAME /home/${USER_NAME}/dep
98 |
99 |
100 | echo "Installing python dependencies:"
101 | # Installs all python dependencies:
102 | sudo -H -u ${USER_NAME} $ENV_NAME/bin/pip install \
103 | --no-index \
104 | --find-links /home/${USER_NAME}/dep/packages \
105 | fcatalog
106 |
107 | # Dependencies and requirements.txt are no longer needed:
108 | rm -rf /home/${USER_NAME}/dep
109 |
110 |
111 | # install fcatalog python package.
112 | echo "Copy server binary to /home/${USER_NAME}/bin/fcatalog_server"
113 |
114 | cp -f ${BASE_DIR}/fcatalog_server /home/${USER_NAME}/bin/fcatalog_server
115 | sudo chown -R $USER_NAME:$USER_NAME /home/${USER_NAME}/bin/fcatalog_server
116 |
117 | # Copy assets/fcatalog.conf to /etc/init
118 | cp -f ${BASE_DIR}/assets/fcatalog.conf /etc/init/fcatalog.conf
119 | # Reload upstart configuration:
120 | initctl reload-configuration
121 |
122 | set +e
123 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | bidict==0.9.0.post1
2 |
--------------------------------------------------------------------------------
/uninstall:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Stop on any error:
4 | set -e
5 |
6 | # Stop the fcatalog server if it is currently running:
7 | set +e
8 | sudo stop fcatalog
9 | set -e
10 |
11 | # Name of the new user to be added for use with the fcatalog server:
12 | USER_NAME="ufcatalog"
13 |
14 | cd catalog1
15 | echo "Uninstalling libcatalog1:"
16 | make uninstall
17 |
18 | # Remove the user $USER_NAME together with his home directory:
19 | userdel -rf $USER_NAME
20 |
21 | # Remove fcatalog.conf from the init:
22 | rm -rf /etc/init/fcatalog.conf
23 |
24 | set +e
25 |
--------------------------------------------------------------------------------