├── .gitignore
├── COPYING
├── README.md
├── behaviors
├── __init__.py
├── address_check.py
├── custom_irc_protocol.py
├── models
│ └── customNetzobIRCModel.xml
└── simple_response.py
├── buttinsky.py
├── cli.py
├── conf
├── buttinsky.cfg.dist
└── logging.ini
├── docs
├── Makefile
├── make.bat
└── source
│ ├── conf.py
│ ├── development
│ ├── guidelines.rst
│ ├── index.rst
│ └── requirements.rst
│ ├── extending
│ ├── index.rst
│ └── logging.rst
│ ├── index.rst
│ ├── installation
│ ├── index.rst
│ └── requirements.rst
│ └── usage
│ └── index.rst
├── event_loops
├── __init__.py
└── gevent_client.py
├── logs
└── buttinsky.log
├── modules
├── __init__.py
├── reporter_handler.py
├── reporting
│ ├── __init__.py
│ ├── base_logger.py
│ ├── hpfeeds_logger.py
│ └── print_logger.py
├── sources
│ ├── __init__.py
│ ├── base_source.py
│ └── hpfeeds_sink.py
└── util
│ ├── __init__.py
│ └── validate.py
├── netzobparse.py
├── protocols
├── __init__.py
├── http.py
└── irc.py
├── requirements.txt
├── settings
├── http_test.set
└── irc_test.set
├── spawner.py
└── stack.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 |
3 | # C extensions
4 | *.so
5 |
6 | # Packages
7 | *.egg
8 | *.egg-info
9 | dist
10 | build
11 | eggs
12 | parts
13 | bin
14 | var
15 | sdist
16 | develop-eggs
17 | .installed.cfg
18 | lib
19 | lib64
20 |
21 | # Installer logs
22 | pip-log.txt
23 |
24 | # Unit test / coverage reports
25 | .coverage
26 | .tox
27 | nosetests.xml
28 |
29 | # Translations
30 | *.mo
31 |
32 | # Mr Developer
33 | .mr.developer.cfg
34 | .project
35 | .pydevproject
36 | conf/buttinsky.cfg
37 | .idea
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Buttinsky #
2 |
3 | ## Open Source Botnet Monitoring ##
4 |
5 | ### Description ###
6 |
7 | Botnet monitoring is a crucial part in threat analysis and often neglected due to the lack of proper open source tools. Our tool will provide an open source framework for automated botnet monitoring. The modular design will allow full customization of the used protocols, the monitoring clients behavior, how we log the collected information, processing of the data to analyze the botnets purpose, size and threat and how the monitoring task are distributed between dedicated nodes.
--------------------------------------------------------------------------------
/behaviors/__init__.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append("..")
3 |
--------------------------------------------------------------------------------
/behaviors/address_check.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | from stack import LayerPlugin, Message
6 |
7 |
8 | class AddressCheck(LayerPlugin):
9 |
10 | def settings(self, setting):
11 | pass
12 |
13 | def receive(self, msgs):
14 | # TODO parse webpage content
15 | pass
16 |
17 | def transmit(self, msg):
18 | return msg
19 |
--------------------------------------------------------------------------------
/behaviors/custom_irc_protocol.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2013 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | from stack import LayerPlugin, Message
6 | from netzobparse import NetzobModelParser
7 |
8 |
9 | class CustomIRCProtocol(LayerPlugin):
10 |
11 | def settings(self, settings):
12 | self.settings = settings["protocol"]
13 | self.stateMachine = NetzobModelParser('behaviors/models/customNetzobIRCModel.xml')
14 |
15 | def receive(self, msgs):
16 | messages = []
17 | for m in msgs.data:
18 | if "command" in m:
19 | reply_msg = None
20 | if m["command"] == "JOIN":
21 | reply_msg = self.stateMachine.handleInput(None, self.settings, True)
22 | if len(reply_msg) == 0:
23 | break
24 | reply = dict()
25 | reply["command"] = "PRIVMSG"
26 | reply["args"]= self.settings["channel"].encode("ascii") + " :" + reply_msg
27 | messages.append(reply)
28 | if m["command"] == "PRIVMSG":
29 | reply_msg = self.stateMachine.handleInput(m["args"][1], self.settings)
30 | if len(reply_msg) == 0:
31 | break
32 | reply = dict()
33 | reply["command"] = "PRIVMSG"
34 | reply["args"] = self.settings["channel"].encode("ascii") + " :" + reply_msg
35 | messages.append(reply)
36 | else:
37 | messages.append(m)
38 | return Message(messages, msgs.left)
39 |
40 | def transmit(self, msg):
41 | return msg
42 |
43 |
--------------------------------------------------------------------------------
/behaviors/models/customNetzobIRCModel.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 100
5 | false
6 | 100
7 | true
8 | true
9 | false
10 | false
11 | false
12 | false
13 | hex
14 | none
15 | unsigned
16 | big-endian
17 |
18 |
19 |
20 |
21 |
22 |
23 | 696d20616c697665206d6173746572
24 | 0
25 | /home/peppe/Downloads/Netzob-0.4.1/test
26 | 2013-04-10T19:43:57
27 | 2013-04-10T19:43:57
28 | none
29 | 158
30 |
31 |
32 | 6861696c20746865206d6173746572
33 | 0
34 | /home/peppe/Downloads/Netzob-0.4.1/test
35 | 2013-04-10T19:43:57
36 | 2013-04-10T19:43:57
37 | none
38 | 158
39 |
40 |
41 | 68656c6c6f20776f726c642c206d79206e616d65206973204b6c6173
42 | 0
43 | /home/peppe/Downloads/Netzob-0.4.1/test
44 | 2013-04-10T19:43:57
45 | 2013-04-10T19:43:57
46 | none
47 | 158
48 |
49 |
50 | 64646f73206d74676f782e636f6d
51 | 0
52 | /home/peppe/Downloads/Netzob-0.4.1/test
53 | 2013-04-10T19:43:57
54 | 2013-04-10T19:43:57
55 | none
56 | 158
57 |
58 |
59 | 64646f73696e67206d74676f782e636f6d
60 | 0
61 | /home/peppe/Downloads/Netzob-0.4.1/test
62 | 2013-04-10T19:43:57
63 | 2013-04-10T19:43:57
64 | none
65 | 158
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 | (.{,})
75 | hex
76 | none
77 | unsigned
78 | big-endian
79 | blue
80 |
81 |
82 | True
83 | Binary
84 | 011010010110110100100000011000010110110001101001011101100110010100100000011011010110000101110011011101000110010101110010
85 | 120
86 | 120
87 | None
88 |
89 |
90 |
91 |
92 | (696d20616c697665206d6173746572)
93 | string
94 | none
95 | unsigned
96 | big-endian
97 | black
98 |
99 | True
100 | Word
101 | im alive master
102 | 15
103 | 120
104 | None
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 | (.{,})
117 | hex
118 | none
119 | unsigned
120 | big-endian
121 | blue
122 |
123 |
124 | True
125 | Binary
126 | 011010000110000101101001011011000010000001110100011010000110010100100000011011010110000101110011011101000110010101110010
127 | 120
128 | 120
129 | None
130 |
131 |
132 |
133 |
134 | (6861696c20746865206d6173746572)
135 | string
136 | none
137 | unsigned
138 | big-endian
139 | black
140 |
141 | True
142 | Word
143 | hail the master
144 | 15
145 | 120
146 | None
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 | (.{,})
159 | hex
160 | none
161 | unsigned
162 | big-endian
163 | blue
164 |
165 |
166 | True
167 | Binary
168 | 01101000011001010110110001101100011011110010000001110111011011110111001001101100011001000010110000100000011011010111100100100000011011100110000101101101011001010010000001101001011100110010000001001011011011000110000101110011
169 | 224
170 | 224
171 | None
172 |
173 |
174 |
175 |
176 | (68656c6c6f20776f726c642c206d79206e616d6520697320)?
177 | string
178 | none
179 | unsigned
180 | big-endian
181 | blue
182 |
183 |
184 | True
185 | Word
186 | hello world, my name is
187 | 24
188 | 192
189 | None
190 |
191 |
192 |
193 |
194 |
195 | ((?:(?!68656c6c6f20776f726c642c206d79206e616d6520697320).)*)
196 | string
197 | none
198 | unsigned
199 | big-endian
200 | blue
201 |
202 |
203 | True
204 | Word
205 | settings($nick)
206 | 15
207 | 15
208 | None
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 | (.{,})
222 | hex
223 | none
224 | unsigned
225 | big-endian
226 | blue
227 |
228 |
229 | True
230 | Binary
231 | 0110010001100100011011110111001100100000011011010111010001100111011011110111100000101110011000110110111101101101
232 | 112
233 | 112
234 | None
235 |
236 |
237 |
238 |
239 | ((?:(?!20).)*)
240 | string
241 | none
242 | unsigned
243 | big-endian
244 | blue
245 |
246 |
247 | True
248 | Word
249 | ddos
250 | 4
251 | 32
252 | None
253 |
254 |
255 |
256 |
257 |
258 | (20)?
259 | string
260 | none
261 | unsigned
262 | big-endian
263 | blue
264 |
265 |
266 | True
267 | Word
268 |
269 | 1
270 | 1
271 | None
272 |
273 |
274 |
275 |
276 |
277 | ((?:(?!20).)*)
278 | string
279 | none
280 | unsigned
281 | big-endian
282 | blue
283 |
284 |
285 | True
286 | Word
287 |
288 | 0
289 | 1
290 | None
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 | (.{,})
304 | hex
305 | none
306 | unsigned
307 | big-endian
308 | blue
309 |
310 |
311 | True
312 | Binary
313 | 0110010001100100011011110111001101101001011011100110011100100000011011010111010001100111011011110111100000101110011000110110111101101101
314 | 136
315 | 136
316 | None
317 |
318 |
319 |
320 |
321 | ((?:(?!20).)*)
322 | string
323 | none
324 | unsigned
325 | big-endian
326 | blue
327 |
328 |
329 | True
330 | Word
331 | ddosing
332 | 7
333 | 56
334 | None
335 |
336 |
337 |
338 |
339 |
340 | (20)?
341 | string
342 | none
343 | unsigned
344 | big-endian
345 | blue
346 |
347 |
348 | True
349 | Word
350 |
351 | 1
352 | 1
353 | None
354 |
355 |
356 |
357 |
358 |
359 | ((?:(?!20).)*)
360 | string
361 | none
362 | unsigned
363 | big-endian
364 | blue
365 |
366 |
367 | True
368 | Size Relation
369 | ae709426-a99a-4431-bfae-b99552282a66
370 | 0
371 | 100
372 | None
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 | f70f5e4e-363a-4770-b649-04a9ec8882f1
406 | 6ce548ba-06ec-4a12-a544-d68c9f3b06ce
407 |
408 |
409 |
410 |
411 |
412 |
413 | 6ce548ba-06ec-4a12-a544-d68c9f3b06ce
414 | b529bcf7-2b4d-455e-948c-89db3d5664a3
415 |
416 |
417 |
418 |
419 |
420 |
421 | b529bcf7-2b4d-455e-948c-89db3d5664a3
422 | b529bcf7-2b4d-455e-948c-89db3d5664a3
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
--------------------------------------------------------------------------------
/behaviors/simple_response.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | from stack import LayerPlugin, Message
6 |
7 |
8 | class SimpleResponse(LayerPlugin):
9 |
10 | def settings(self, setting):
11 | pass
12 |
13 | def receive(self, msgs):
14 | messages = []
15 | for m in msgs.data:
16 | if "command" in m:
17 | if m["command"] == "PRIVMSG":
18 | if m["args"][1] == "hello":
19 | reply = dict()
20 | reply["command"] = "PRIVMSG"
21 | reply["args"] = m["prefix"].split('!~')[0] + " hey!"
22 | messages.append(reply)
23 | else:
24 | messages.append(m)
25 | return Message(messages, msgs.left)
26 |
27 | def transmit(self, msg):
28 | return msg
29 |
--------------------------------------------------------------------------------
/buttinsky.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | import os
6 | import sys
7 |
8 | from configobj import ConfigObj
9 |
10 | import gevent.monkey
11 | gevent.monkey.patch_all()
12 |
13 | from SimpleXMLRPCServer import SimpleXMLRPCServer
14 |
15 | from modules.reporting import hpfeeds_logger
16 |
17 | from spawner import MonitorSpawner, ButtinskyXMLRPCServer
18 | import cli
19 |
20 | import gevent
21 | from gevent import queue
22 |
23 | import logging
24 | import logging.config
25 |
26 | logging.config.fileConfig('conf/logging.ini')
27 | logger = logging.getLogger(__name__)
28 |
29 |
30 | buttinsky_config = ConfigObj("conf/buttinsky.cfg")
31 |
32 |
33 | class Buttinsky(object):
34 |
35 | def __init__(self):
36 | logger.info("Starting Buttinsky")
37 | self.servers = []
38 | if not os.path.isfile("conf/buttinsky.cfg"):
39 | sys.exit("Modify and rename conf/buttinsky.cfg.dist to conf/buttinsky.cfg.")
40 | hpfeeds_logger.HPFeedsLogger()
41 | messageQueue = queue.Queue()
42 | gevent.spawn(MonitorSpawner(messageQueue).work)
43 | buttinsky_config = ConfigObj("conf/buttinsky.cfg")
44 | hostname = buttinsky_config["xmlrpc"]["server"]
45 | port = int(buttinsky_config["xmlrpc"]["port"])
46 | server = SimpleXMLRPCServer((hostname, port), logRequests=False)
47 | logger.debug("Listening on port 8000...")
48 | server.register_instance(ButtinskyXMLRPCServer(messageQueue))
49 | if buttinsky_config["hpfeeds"]["enabled"] == "True":
50 | gevent.spawn(ButtinskyXMLRPCServer(messageQueue).load_sink)
51 | try:
52 | xmlrpc_server = gevent.spawn(server.serve_forever)
53 | cli_thread = gevent.spawn(cli.main)
54 | cli_thread.join()
55 | xmlrpc_server.kill()
56 | except (KeyboardInterrupt, SystemExit):
57 | logger.debug("Quitting... Bye!")
58 |
59 |
60 | if __name__ == "__main__":
61 | buttinsky = Buttinsky()
--------------------------------------------------------------------------------
/cli.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | import cmd
6 | import sys
7 | import xmlrpclib
8 | import getopt
9 | import socket
10 | import json
11 | import os
12 |
13 | from configobj import ConfigObj
14 | import modules.util.validate as validate
15 |
16 |
17 | class CLI(cmd.Cmd):
18 |
19 | def __init__(self, connection):
20 | cmd.Cmd.__init__(self)
21 | self.prompt = '\033[1;30m>>\033[0m '
22 | self.conn = connection
23 | self.doc_header = 'Available commands (type help ):'
24 | self.undoc_header = ''
25 | self.intro = "\
26 | ____ __ __ _ __ \n\
27 | / __ )__ __/ /_/ /_(_)___ _____/ /____ __\n\
28 | / __ / / / / __/ __/ / __ \/ ___/ //_/ / / /\n\
29 | / /_/ / /_/ / /_/ /_/ / / / (__ ) ,< / /_/ / \n\
30 | /_____/\__,_/\__/\__/_/_/ /_/____/_/|_|\__, / \n\
31 | /____/ \n\
32 | \033[1;30mButtinsky Command Line Interface\n\tType 'help' for a list of commands\033[0m\n\n"
33 |
34 | def do_create(self, arg):
35 | """
36 | \033[1;30msyntax: create -- create new configuration from JSON encoded string, store it in file\033[0m
37 | """
38 | args = arg.split(' ')
39 | try:
40 | ret = self.conn.create(args[0], json.dumps(''.join(args[1])))
41 | print ret
42 | except IndexError:
43 | print "Not enough parameters: create "
44 | except xmlrpclib.Fault as err:
45 | print "Command failed: ",
46 | print err
47 |
48 | def do_echo(self, arg):
49 | """
50 | \033[1;30msyntax: echo -- send message to echo function to test non-blocking functionality\033[0m
51 | """
52 | if arg == "":
53 | print "Invalid argument: echo "
54 | return
55 | try:
56 | ret = self.conn.echo(arg)
57 | print ret
58 | except xmlrpclib.Fault as err:
59 | print "Command failed: ",
60 | print err
61 |
62 | def do_load(self, arg):
63 | """
64 | \033[1;30msyntax: load -- load configuration from specified filename and identify it using id\033[0m
65 | """
66 | args = arg.split(' ')
67 | try:
68 | validate.validate(args[1])
69 | ret = self.conn.load(args[0], args[1])
70 | print ret
71 | except IndexError:
72 | print "Not enough parameters: load "
73 | except IOError:
74 | print "Invalid settings name. Use 'status' to get a list of available setting files."
75 | except xmlrpclib.Fault as err:
76 | print "Command failed: ",
77 | print err
78 |
79 | def do_status(self, arg):
80 | """
81 | \033[1;30msyntax: status -- show all running monitors\033[0m
82 | """
83 | try:
84 | ret = self.conn.status()
85 | print "\n\033[1;30mFile\t\tMonitor ID\n====\t\t==========\n\033[0m"
86 | for k, v in ret.iteritems():
87 | if k == "":
88 | for i in v:
89 | print i + "\tNone"
90 | else:
91 | print v + "\t" + k
92 | print ""
93 | except xmlrpclib.Fault as err:
94 | print "Command failed: ",
95 | print err
96 |
97 | def do_stop(self, arg):
98 | """
99 | \033[1;30msyntax: stop -- stop execution of monitor identified by id\033[0m
100 | """
101 | if arg == "":
102 | print "Invalid argument: stop "
103 | return
104 | try:
105 | ret = self.conn.stop(arg)
106 | except xmlrpclib.Fault as err:
107 | print "Command failed: ",
108 | print err
109 |
110 | def do_restart(self, arg):
111 | """
112 | \033[1;30msyntax: restart -- restart execution of monitor identified by id\033[0m
113 | """
114 | if arg == "":
115 | print "Invalid argument: restart "
116 | return
117 | try:
118 | ret = self.conn.restart(arg)
119 | except xmlrpclib.Fault as err:
120 | print "Command failed: ",
121 | print err
122 |
123 | def do_list(self, arg):
124 | """
125 | \033[1;30msyntax: list -- list contens of file\033[0m
126 | """
127 | if arg == "":
128 | print "Invalid argument: list "
129 | return
130 | try:
131 | ret = self.conn.list(arg)
132 | print "\n\033[1;30mContents of " + arg + "\033[0m\n"
133 | print ret + "\n"
134 | except IOError:
135 | print "Invalid settings name. Use 'status' to get a list of available setting files."
136 | except xmlrpclib.Fault as err:
137 | print "Command failed: ",
138 | print err
139 |
140 | def do_delete(self, arg):
141 | """
142 | \033[1;30msyntax: delete -- delete configuration specified in file\033[0m
143 | """
144 | if arg == "":
145 | print "Invalid argument: delete "
146 | return
147 | try:
148 | ret = self.conn.delete(arg)
149 | except IOError:
150 | print "Invalid settings name. Use 'status' to get a list of available setting files."
151 | except xmlrpclib.Fault as err:
152 | print "Command failed: ",
153 | print err
154 |
155 | def do_quit(self, arg):
156 | """
157 | \033[1;30msyntax: quit -- exit the client gracefully, Shortcuts: 'q', 'CTRL-D'\033[0m
158 | """
159 | sys.exit(1)
160 |
161 | def help_help(self):
162 | print """\t\033[1;30msyntax: help -- Show help for a particular topic.
163 | List all commands if topic is not specified\033[0m"""
164 |
165 | def default(self, arg):
166 | print "Unknown command: " + arg + "\n"
167 |
168 | def emptyline(self):
169 | pass
170 |
171 | # shortcuts
172 | do_q = do_quit
173 | do_EOF = do_quit # quit with CTRL-D
174 |
175 |
176 | def usage():
177 | print "\nusage: cli.py [-h] [-s server] [-p port]\n\n"\
178 | "\t-h\t\tthis help text\n"\
179 | "\t-s server\thostname of the server, default: localhost\n"\
180 | "\t-p port\t\tport number of the server, default: 8000\n"
181 |
182 |
183 | def main():
184 | if not os.path.isfile("conf/buttinsky.cfg"):
185 | sys.exit("Modify and rename conf/buttinsky.cfg.dist to conf/buttinsky.cfg.")
186 | buttinsky_config = ConfigObj("conf/buttinsky.cfg")
187 | server = buttinsky_config["xmlrpc"]["server"]
188 | port = buttinsky_config["xmlrpc"]["port"]
189 | try:
190 | opts, args = getopt.getopt(sys.argv[1:], "hs:p:")
191 | except getopt.GetoptError:
192 | usage()
193 | sys.exit(2)
194 |
195 | for opt, arg in opts:
196 | if opt in "-h":
197 | usage()
198 | sys.exit()
199 | elif opt in "-s":
200 | server = arg
201 | elif opt in "-p":
202 | port = arg
203 |
204 | url = "http://" + server + ":" + port + "/"
205 | conn = xmlrpclib.ServerProxy(url)
206 |
207 | try:
208 | ret = conn.echo("echo")
209 | except socket.error:
210 | print server + ":" + port + " seems to be down :(\n"
211 | sys.exit(2)
212 | except xmlrpclib.Fault as err:
213 | print "Operation denied\n"
214 | print err
215 | sys.exit(2)
216 |
217 | try:
218 | CLI(conn).cmdloop()
219 | except socket.error:
220 | print server + ":" + port + " seems to be down :(\n"
221 | except (SystemExit, KeyboardInterrupt):
222 | print "bye"
223 |
224 | if __name__ == "__main__":
225 | main()
--------------------------------------------------------------------------------
/conf/buttinsky.cfg.dist:
--------------------------------------------------------------------------------
1 | [hpfeeds]
2 | enabled = False
3 | host = hpfeeds.honeycloud.net
4 | port = 10000
5 | ident =
6 | secret =
7 | source_channel = glastopf.sandbox
8 | publish_channels =
9 |
10 | [xmlrpc]
11 | server = localhost
12 | port = 8000
13 |
--------------------------------------------------------------------------------
/conf/logging.ini:
--------------------------------------------------------------------------------
1 | [loggers]
2 | keys=root
3 |
4 | [handlers]
5 | keys=FileHandler
6 |
7 | [formatters]
8 | keys=LogFormatter
9 |
10 | [logger_root]
11 | level=DEBUG
12 | handlers=FileHandler
13 |
14 | [handler_FileHandler]
15 | class=FileHandler
16 | formatter=LogFormatter
17 | args=("logs/buttinsky.log",)
18 |
19 | [formatter_LogFormatter]
20 | format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
21 | datefmt=
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Buttinsky.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Buttinsky.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/Buttinsky"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Buttinsky"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | REM Command file for Sphinx documentation
4 |
5 | if "%SPHINXBUILD%" == "" (
6 | set SPHINXBUILD=sphinx-build
7 | )
8 | set BUILDDIR=build
9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
10 | set I18NSPHINXOPTS=%SPHINXOPTS% source
11 | if NOT "%PAPER%" == "" (
12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14 | )
15 |
16 | if "%1" == "" goto help
17 |
18 | if "%1" == "help" (
19 | :help
20 | echo.Please use `make ^` where ^ is one of
21 | echo. html to make standalone HTML files
22 | echo. dirhtml to make HTML files named index.html in directories
23 | echo. singlehtml to make a single large HTML file
24 | echo. pickle to make pickle files
25 | echo. json to make JSON files
26 | echo. htmlhelp to make HTML files and a HTML help project
27 | echo. qthelp to make HTML files and a qthelp project
28 | echo. devhelp to make HTML files and a Devhelp project
29 | echo. epub to make an epub
30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31 | echo. text to make text files
32 | echo. man to make manual pages
33 | echo. texinfo to make Texinfo files
34 | echo. gettext to make PO message catalogs
35 | echo. changes to make an overview over all changed/added/deprecated items
36 | echo. linkcheck to check all external links for integrity
37 | echo. doctest to run all doctests embedded in the documentation if enabled
38 | goto end
39 | )
40 |
41 | if "%1" == "clean" (
42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
43 | del /q /s %BUILDDIR%\*
44 | goto end
45 | )
46 |
47 | if "%1" == "html" (
48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
49 | if errorlevel 1 exit /b 1
50 | echo.
51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html.
52 | goto end
53 | )
54 |
55 | if "%1" == "dirhtml" (
56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
57 | if errorlevel 1 exit /b 1
58 | echo.
59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
60 | goto end
61 | )
62 |
63 | if "%1" == "singlehtml" (
64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
65 | if errorlevel 1 exit /b 1
66 | echo.
67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
68 | goto end
69 | )
70 |
71 | if "%1" == "pickle" (
72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
73 | if errorlevel 1 exit /b 1
74 | echo.
75 | echo.Build finished; now you can process the pickle files.
76 | goto end
77 | )
78 |
79 | if "%1" == "json" (
80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
81 | if errorlevel 1 exit /b 1
82 | echo.
83 | echo.Build finished; now you can process the JSON files.
84 | goto end
85 | )
86 |
87 | if "%1" == "htmlhelp" (
88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
89 | if errorlevel 1 exit /b 1
90 | echo.
91 | echo.Build finished; now you can run HTML Help Workshop with the ^
92 | .hhp project file in %BUILDDIR%/htmlhelp.
93 | goto end
94 | )
95 |
96 | if "%1" == "qthelp" (
97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
98 | if errorlevel 1 exit /b 1
99 | echo.
100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^
101 | .qhcp project file in %BUILDDIR%/qthelp, like this:
102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Buttinsky.qhcp
103 | echo.To view the help file:
104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Buttinsky.ghc
105 | goto end
106 | )
107 |
108 | if "%1" == "devhelp" (
109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
110 | if errorlevel 1 exit /b 1
111 | echo.
112 | echo.Build finished.
113 | goto end
114 | )
115 |
116 | if "%1" == "epub" (
117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
118 | if errorlevel 1 exit /b 1
119 | echo.
120 | echo.Build finished. The epub file is in %BUILDDIR%/epub.
121 | goto end
122 | )
123 |
124 | if "%1" == "latex" (
125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
126 | if errorlevel 1 exit /b 1
127 | echo.
128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
129 | goto end
130 | )
131 |
132 | if "%1" == "text" (
133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
134 | if errorlevel 1 exit /b 1
135 | echo.
136 | echo.Build finished. The text files are in %BUILDDIR%/text.
137 | goto end
138 | )
139 |
140 | if "%1" == "man" (
141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
142 | if errorlevel 1 exit /b 1
143 | echo.
144 | echo.Build finished. The manual pages are in %BUILDDIR%/man.
145 | goto end
146 | )
147 |
148 | if "%1" == "texinfo" (
149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
150 | if errorlevel 1 exit /b 1
151 | echo.
152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
153 | goto end
154 | )
155 |
156 | if "%1" == "gettext" (
157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
158 | if errorlevel 1 exit /b 1
159 | echo.
160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
161 | goto end
162 | )
163 |
164 | if "%1" == "changes" (
165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
166 | if errorlevel 1 exit /b 1
167 | echo.
168 | echo.The overview file is in %BUILDDIR%/changes.
169 | goto end
170 | )
171 |
172 | if "%1" == "linkcheck" (
173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
174 | if errorlevel 1 exit /b 1
175 | echo.
176 | echo.Link check complete; look for any errors in the above output ^
177 | or in %BUILDDIR%/linkcheck/output.txt.
178 | goto end
179 | )
180 |
181 | if "%1" == "doctest" (
182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
183 | if errorlevel 1 exit /b 1
184 | echo.
185 | echo.Testing of doctests in the sources finished, look at the ^
186 | results in %BUILDDIR%/doctest/output.txt.
187 | goto end
188 | )
189 |
190 | :end
191 |
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Buttinsky documentation build configuration file, created by
4 | # sphinx-quickstart on Tue Dec 04 13:37:27 2012.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | # -- General configuration -----------------------------------------------------
22 |
23 | # If your documentation needs a minimal Sphinx version, state it here.
24 | #needs_sphinx = '1.0'
25 |
26 | # Add any Sphinx extension module names here, as strings. They can be extensions
27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28 | extensions = []
29 |
30 | # Add any paths that contain templates here, relative to this directory.
31 | templates_path = ['_templates']
32 |
33 | # The suffix of source filenames.
34 | source_suffix = '.rst'
35 |
36 | # The encoding of source files.
37 | #source_encoding = 'utf-8-sig'
38 |
39 | # The master toctree document.
40 | master_doc = 'index'
41 |
42 | # General information about the project.
43 | project = u'Buttinsky'
44 | copyright = u'2012, Buttinsky Project'
45 |
46 | # The version info for the project you're documenting, acts as replacement for
47 | # |version| and |release|, also used in various other places throughout the
48 | # built documents.
49 | #
50 | # The short X.Y version.
51 | version = '0.1'
52 | # The full version, including alpha/beta/rc tags.
53 | release = '0.1'
54 |
55 | # The language for content autogenerated by Sphinx. Refer to documentation
56 | # for a list of supported languages.
57 | #language = None
58 |
59 | # There are two options for replacing |today|: either, you set today to some
60 | # non-false value, then it is used:
61 | #today = ''
62 | # Else, today_fmt is used as the format for a strftime call.
63 | #today_fmt = '%B %d, %Y'
64 |
65 | # List of patterns, relative to source directory, that match files and
66 | # directories to ignore when looking for source files.
67 | exclude_patterns = []
68 |
69 | # The reST default role (used for this markup: `text`) to use for all documents.
70 | #default_role = None
71 |
72 | # If true, '()' will be appended to :func: etc. cross-reference text.
73 | #add_function_parentheses = True
74 |
75 | # If true, the current module name will be prepended to all description
76 | # unit titles (such as .. function::).
77 | #add_module_names = True
78 |
79 | # If true, sectionauthor and moduleauthor directives will be shown in the
80 | # output. They are ignored by default.
81 | #show_authors = False
82 |
83 | # The name of the Pygments (syntax highlighting) style to use.
84 | pygments_style = 'sphinx'
85 |
86 | # A list of ignored prefixes for module index sorting.
87 | #modindex_common_prefix = []
88 |
89 |
90 | # -- Options for HTML output ---------------------------------------------------
91 |
92 | # The theme to use for HTML and HTML Help pages. See the documentation for
93 | # a list of builtin themes.
94 | html_theme = 'default'
95 |
96 | # Theme options are theme-specific and customize the look and feel of a theme
97 | # further. For a list of options available for each theme, see the
98 | # documentation.
99 | #html_theme_options = {}
100 |
101 | # Add any paths that contain custom themes here, relative to this directory.
102 | #html_theme_path = []
103 |
104 | # The name for this set of Sphinx documents. If None, it defaults to
105 | # " v documentation".
106 | #html_title = None
107 |
108 | # A shorter title for the navigation bar. Default is the same as html_title.
109 | #html_short_title = None
110 |
111 | # The name of an image file (relative to this directory) to place at the top
112 | # of the sidebar.
113 | #html_logo = None
114 |
115 | # The name of an image file (within the static path) to use as favicon of the
116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
117 | # pixels large.
118 | #html_favicon = None
119 |
120 | # Add any paths that contain custom static files (such as style sheets) here,
121 | # relative to this directory. They are copied after the builtin static files,
122 | # so a file named "default.css" will overwrite the builtin "default.css".
123 | html_static_path = ['_static']
124 |
125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
126 | # using the given strftime format.
127 | #html_last_updated_fmt = '%b %d, %Y'
128 |
129 | # If true, SmartyPants will be used to convert quotes and dashes to
130 | # typographically correct entities.
131 | #html_use_smartypants = True
132 |
133 | # Custom sidebar templates, maps document names to template names.
134 | #html_sidebars = {}
135 |
136 | # Additional templates that should be rendered to pages, maps page names to
137 | # template names.
138 | #html_additional_pages = {}
139 |
140 | # If false, no module index is generated.
141 | #html_domain_indices = True
142 |
143 | # If false, no index is generated.
144 | #html_use_index = True
145 |
146 | # If true, the index is split into individual pages for each letter.
147 | #html_split_index = False
148 |
149 | # If true, links to the reST sources are added to the pages.
150 | #html_show_sourcelink = True
151 |
152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
153 | #html_show_sphinx = True
154 |
155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
156 | #html_show_copyright = True
157 |
158 | # If true, an OpenSearch description file will be output, and all pages will
159 | # contain a tag referring to it. The value of this option must be the
160 | # base URL from which the finished HTML is served.
161 | #html_use_opensearch = ''
162 |
163 | # This is the file name suffix for HTML files (e.g. ".xhtml").
164 | #html_file_suffix = None
165 |
166 | # Output file base name for HTML help builder.
167 | htmlhelp_basename = 'Buttinskydoc'
168 |
169 |
170 | # -- Options for LaTeX output --------------------------------------------------
171 |
172 | latex_elements = {
173 | # The paper size ('letterpaper' or 'a4paper').
174 | #'papersize': 'letterpaper',
175 |
176 | # The font size ('10pt', '11pt' or '12pt').
177 | #'pointsize': '10pt',
178 |
179 | # Additional stuff for the LaTeX preamble.
180 | #'preamble': '',
181 | }
182 |
183 | # Grouping the document tree into LaTeX files. List of tuples
184 | # (source start file, target name, title, author, documentclass [howto/manual]).
185 | latex_documents = [
186 | ('index', 'Buttinsky.tex', u'Buttinsky Documentation',
187 | u'Buttinsky Project', 'manual'),
188 | ]
189 |
190 | # The name of an image file (relative to this directory) to place at the top of
191 | # the title page.
192 | #latex_logo = None
193 |
194 | # For "manual" documents, if this is true, then toplevel headings are parts,
195 | # not chapters.
196 | #latex_use_parts = False
197 |
198 | # If true, show page references after internal links.
199 | #latex_show_pagerefs = False
200 |
201 | # If true, show URL addresses after external links.
202 | #latex_show_urls = False
203 |
204 | # Documents to append as an appendix to all manuals.
205 | #latex_appendices = []
206 |
207 | # If false, no module index is generated.
208 | #latex_domain_indices = True
209 |
210 |
211 | # -- Options for manual page output --------------------------------------------
212 |
213 | # One entry per manual page. List of tuples
214 | # (source start file, name, description, authors, manual section).
215 | man_pages = [
216 | ('index', 'buttinsky', u'Buttinsky Documentation',
217 | [u'Buttinsky Project'], 1)
218 | ]
219 |
220 | # If true, show URL addresses after external links.
221 | #man_show_urls = False
222 |
223 |
224 | # -- Options for Texinfo output ------------------------------------------------
225 |
226 | # Grouping the document tree into Texinfo files. List of tuples
227 | # (source start file, target name, title, author,
228 | # dir menu entry, description, category)
229 | texinfo_documents = [
230 | ('index', 'Buttinsky', u'Buttinsky Documentation',
231 | u'Buttinsky Project', 'Buttinsky', 'One line description of project.',
232 | 'Miscellaneous'),
233 | ]
234 |
235 | # Documents to append as an appendix to all manuals.
236 | #texinfo_appendices = []
237 |
238 | # If false, no module index is generated.
239 | #texinfo_domain_indices = True
240 |
241 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
242 | #texinfo_show_urls = 'footnote'
243 |
--------------------------------------------------------------------------------
/docs/source/development/guidelines.rst:
--------------------------------------------------------------------------------
1 | ===========
2 | Guidelines
3 | ===========
4 |
5 | Developers Guide
6 | =================
7 |
8 | Indentation
9 | ------------
10 | * We are using 4 spaces-tab
11 | * No one line conditionals
12 |
13 | Style
14 | ------
15 | * We obey to the `PEP8 `_
16 |
17 | Copyright
18 | ----------
19 | * If you are adding a file/code which is produced only by you, feel free to add the license information and a notice who holds the copyrights.
20 |
21 | In general the copyright information at the beginning of the file should look like:
22 |
23 | # Copyright (C) 2012 Buttinsky Developers.
24 | # See 'COPYING' for copying permission.
25 |
26 | Environment
27 | ------------
28 | * `Eclipse `_ with `PyDev `_ and `Subclipse `_ is a good combination.
29 |
--------------------------------------------------------------------------------
/docs/source/development/index.rst:
--------------------------------------------------------------------------------
1 | .. Development chapter frontpage
2 |
3 | Development
4 | ============
5 |
6 | Basics on how to develop Buttinsky
7 |
8 | .. toctree::
9 |
10 | guidelines
--------------------------------------------------------------------------------
/docs/source/development/requirements.rst:
--------------------------------------------------------------------------------
1 | =============
2 | Requirements
3 | =============
4 |
5 | Buttinsky Installation
6 | ==================
7 |
8 | Prerequisites
9 | ------------------
10 |
11 | Install the basic packages::
12 |
13 | apt-get install python2.7 python-configobj python-gevent
14 | pip install validictory
15 |
--------------------------------------------------------------------------------
/docs/source/extending/index.rst:
--------------------------------------------------------------------------------
1 | .. Extending chapter frontpage
2 |
3 | Extending
4 | ==========
5 |
6 | Basics instruction on how to extend Buttinsky
7 |
8 | .. toctree::
9 |
10 | logging
--------------------------------------------------------------------------------
/docs/source/extending/logging.rst:
--------------------------------------------------------------------------------
1 | ============================
2 | Extend Logging Capabilities
3 | ============================
4 |
5 | Getting started
6 | ------------------
7 |
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | .. Buttinsky documentation master file
2 |
3 | Welcome to Buttinsky's documentation!
4 | ======================================
5 |
6 | Contents:
7 |
8 | .. toctree::
9 | :maxdepth: 2
10 |
11 | usage/index
12 | development/index
13 | installation/index
14 | extending/index
15 |
16 |
17 |
18 | Indices and tables
19 | ===================
20 |
21 | * :ref:`genindex`
22 | * :ref:`modindex`
23 | * :ref:`search`
24 |
25 |
--------------------------------------------------------------------------------
/docs/source/installation/index.rst:
--------------------------------------------------------------------------------
1 | .. Installation chapter frontpage
2 |
3 | Installation
4 | ===========
5 |
6 | Basics instruction on how to install Buttinsky
7 |
8 | .. toctree::
9 |
10 | requirements
--------------------------------------------------------------------------------
/docs/source/installation/requirements.rst:
--------------------------------------------------------------------------------
1 | ============
2 | Requirements
3 | ============
4 |
5 | Buttinsky Installation
6 | ======================
7 |
8 | Prerequisites
9 | -------------
10 |
11 | Install the basic packages::
12 |
13 | apt-get install python2.7 python-dev libevent-dev git
14 |
15 | Install hpfeeds::
16 |
17 | cd /opt
18 | git clone git://github.com/rep/hpfeeds.git
19 | cd hpfeeds
20 | python setup.py install
21 |
22 | Install requirements::
23 |
24 | pip install -r requirements.txt
25 |
26 |
27 | Set-Up
28 | ------
29 |
30 | Modify and rename conf/buttinsky.cfg.dist to conf/buttinsky.cfg
31 |
--------------------------------------------------------------------------------
/docs/source/usage/index.rst:
--------------------------------------------------------------------------------
1 | .. Usage chapter frontpage
2 |
3 | Usage
4 | =====
5 |
6 | Basics instruction on how to use Buttinsky
7 |
8 |
9 | Run the spawner:
10 |
11 | python spawner.py
12 |
13 |
14 | Connect with the CLI:
15 |
16 | python cli.py
--------------------------------------------------------------------------------
/event_loops/__init__.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append("..")
3 |
--------------------------------------------------------------------------------
/event_loops/gevent_client.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | import gevent
6 | from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
7 | from gevent import socket, queue
8 | from stack import LayerPlugin, Message
9 | from socks import socksocket, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5
10 |
11 |
12 | class TCPSocket(object):
13 | def __init__(self, host, port):
14 | self._address = (str(host), int(port))
15 | self._socket = socket.socket(AF_INET, SOCK_STREAM)
16 |
17 | def connect(self):
18 | self._socket.connect(self._address)
19 |
20 | def disconnect(self):
21 | self._socket.close()
22 |
23 | def send(self, data):
24 | return self._socket.send(data)
25 |
26 | def recv(self, size):
27 | return self._socket.recv(size)
28 |
29 |
30 | class TCPSocks4Socket(TCPSocket):
31 | def __init__(self, host, port, socks_host, socks_port):
32 | self._address = (str(host), int(port))
33 | self._socket = socksocket(AF_INET, SOCK_STREAM)
34 | self._socket.setproxy(PROXY_TYPE_SOCKS4,
35 | str(socks_host), int(socks_port))
36 |
37 |
38 | class TCPSocks5Socket(TCPSocket):
39 | def __init__(self, host, port, socks_host, socks_port):
40 | self._address = (str(host), int(port))
41 | self._socket = socksocket(AF_INET, SOCK_STREAM)
42 | self._socket.setproxy(PROXY_TYPE_SOCKS5,
43 | str(socks_host), int(socks_port))
44 |
45 |
46 | class UDPSocket(object):
47 | def __init__(self, host, port):
48 | self._address = (str(host), int(port))
49 | self._socket = socket.socket(AF_INET, SOCK_DGRAM)
50 |
51 | def connect(self):
52 | pass
53 |
54 | def disconnect(self):
55 | self._socket.close()
56 |
57 | def send(self, data):
58 | return self._socket.sendto(data, self._address)
59 |
60 | def recv(self, size):
61 | data, _addr = self._socket.recvfrom(size)
62 | return data
63 |
64 |
65 | class Connection(object):
66 | def __init__(self, host, port):
67 | self._ibuffer = ''
68 | self._obuffer = ''
69 | self.iqueue = queue.Queue()
70 | self.oqueue = queue.Queue()
71 | self.host = host
72 | self.port = port
73 | self._socket = self._create_socket()
74 | self.jobs = None
75 |
76 | def _create_socket(self):
77 | raise NotImplementedError
78 |
79 | def connect(self):
80 | self._socket.connect()
81 | try:
82 | self.jobs = [gevent.spawn(self._recv_loop),
83 | gevent.spawn(self._send_loop)]
84 | gevent.joinall(self.jobs)
85 | finally:
86 | gevent.killall(self.jobs)
87 |
88 | def disconnect(self):
89 | self._socket.disconnect()
90 |
91 | def _recv_loop(self):
92 | while True:
93 | try:
94 | data = self._socket.recv(4096)
95 | self.iqueue.put(data)
96 | except:
97 | return
98 |
99 | def _send_loop(self):
100 | while True:
101 | line = self.oqueue.get()
102 | self._obuffer += line.encode('utf-8', 'replace')
103 | while self._obuffer:
104 | sent = self._socket.send(self._obuffer)
105 | self._obuffer = self._obuffer[sent:]
106 |
107 |
108 | class TCPConnection(Connection):
109 | def _create_socket(self):
110 | return TCPSocket(self.host, self.port)
111 |
112 |
113 | class UDPConnection(Connection):
114 | def _create_socket(self):
115 | return UDPSocket(self.host, self.port)
116 |
117 |
118 | class ProxyConnection(Connection):
119 | def __init__(self, host, port, proxy_host, proxy_port):
120 | self.proxy_host = proxy_host
121 | self.proxy_port = proxy_port
122 | super(ProxyConnection, self).__init__(host, port)
123 |
124 |
125 | class TCPSocks4ProxyConnection(ProxyConnection):
126 | def _create_socket(self):
127 | return TCPSocks4Socket(
128 | self.host, self.port,
129 | self.proxy_host, self.proxy_port)
130 |
131 |
132 | class TCPSocks5ProxyConnection(ProxyConnection):
133 | def _create_socket(self):
134 | return TCPSocks5Socket(
135 | self.host, self.port,
136 | self.proxy_host, self.proxy_port)
137 |
138 |
139 | class Client(object):
140 | def __init__(self, host, port, protocol="TCP",
141 | proxy_type="", proxy_host=None, proxy_port=None):
142 | self.lines = queue.Queue()
143 | self.host = host
144 | self.port = port
145 | self.protocol = protocol
146 | self.proxy_type = proxy_type
147 | self.proxy_host = proxy_host
148 | self.proxy_port = proxy_port
149 | self.layer1 = None
150 |
151 | def setLayer1(self, layer1):
152 | self.layer1 = layer1
153 |
154 | def _create_connection(self):
155 | if self.protocol == "UDP":
156 | return UDPConnection(self.host, self.port)
157 | else: # defaults to TCP
158 | if self.proxy_type == "socks4":
159 | return TCPSocks4ProxyConnection(
160 | self.host, self.port,
161 | self.proxy_host, self.proxy_port)
162 | elif self.proxy_type == "socks5":
163 | return TCPSocks5ProxyConnection(
164 | self.host, self.port,
165 | self.proxy_host, self.proxy_port)
166 | else: # TCP without proxy
167 | return TCPConnection(self.host, self.port)
168 |
169 | def connect(self):
170 | self.conn = self._create_connection()
171 | gevent.spawn(self.conn.connect)
172 | self._event_loop()
173 |
174 | def disconnect(self):
175 | self.conn.disconnect()
176 |
177 | def queue(self, msg):
178 | self.conn.iqueue.put(msg)
179 |
180 | def send(self, s):
181 | self.conn.oqueue.put(s)
182 |
183 | def _event_loop(self):
184 | try:
185 | message = Message(self.conn.iqueue.get_nowait())
186 | except queue.Empty:
187 | message = Message()
188 |
189 | while True:
190 | if self.layer1 and message and message.data != "":
191 | self.layer1.receive(message)
192 | message = Message(self.conn.iqueue.get())
193 |
194 |
195 | class Layer1(LayerPlugin):
196 | def __init__(self, client):
197 | LayerPlugin.__init__(self)
198 | self.client = client
199 |
200 | def receive(self, msg):
201 | return msg
202 |
203 | def transmit(self, msg):
204 | if len(msg.left) > 0:
205 | self.client.queue(msg.left)
206 | if len(msg.data) > 0:
207 | self.client.send(msg.data)
208 |
--------------------------------------------------------------------------------
/logs/buttinsky.log:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mushorg/buttinsky/1a2a1b29f1d4078fdad051813a8d90080a1a1e84/logs/buttinsky.log
--------------------------------------------------------------------------------
/modules/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mushorg/buttinsky/1a2a1b29f1d4078fdad051813a8d90080a1a1e84/modules/__init__.py
--------------------------------------------------------------------------------
/modules/reporter_handler.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | import os
6 |
7 | from stack import LayerPlugin
8 |
9 | from modules.reporting.base_logger import BaseLogger
10 |
11 |
12 | class ModuleImporter(object):
13 |
14 | def __init__(self, plugins):
15 | self.plugins = plugins
16 |
17 | def _get_logger_names(self, path='modules/reporting/'):
18 | names = os.listdir(path)
19 | for name in reversed(names):
20 | if (name == 'base_logger.py' or ".pyc" in name
21 | or name == 'hpfeeds.py' or name == '__init__.py'):
22 | names.remove(name)
23 | return names
24 |
25 | def get_loggers(self):
26 | loggers = []
27 | try:
28 | BaseLogger()
29 | for name in self._get_logger_names():
30 | if name.split("_logger.py")[0] in self.plugins:
31 | module_name = "modules.reporting." + name.split('.', 1)[0]
32 | __import__(module_name, globals(), locals(), [], -1)
33 | logger_classes = BaseLogger.__subclasses__()
34 | except ImportError as e:
35 | print e
36 | return None
37 | else:
38 | for logger_class in logger_classes:
39 | logger = logger_class()
40 | if logger.options['enabled'] == 'True':
41 | loggers.append(logger)
42 | return loggers
43 |
44 |
45 | class ReporterHandler(LayerPlugin):
46 |
47 | def __init__(self, plugins):
48 | self.reporting_handler = ModuleImporter(plugins)
49 | self.loggers = self.reporting_handler.get_loggers()
50 |
51 | def settings(self, setting):
52 | pass
53 |
54 | def receive(self, msg):
55 | self.log(msg.data)
56 | return msg
57 |
58 | def transmit(self, msg):
59 | if len(msg.data) > 0:
60 | self.log(msg.data)
61 | return msg
62 |
63 | def log(self, msg):
64 | for logger in self.loggers:
65 | logger.insert(msg)
66 |
--------------------------------------------------------------------------------
/modules/reporting/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mushorg/buttinsky/1a2a1b29f1d4078fdad051813a8d90080a1a1e84/modules/reporting/__init__.py
--------------------------------------------------------------------------------
/modules/reporting/base_logger.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2012 Lukas Rist
2 | #
3 | # This program is free software; you can redistribute it and/or
4 | # modify it under the terms of the GNU General Public License
5 | # as published by the Free Software Foundation; either version 2
6 | # of the License, or (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program; if not, write to the Free Software
15 | # Foundation, Inc.,
16 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | class BaseLogger(object):
20 |
21 | def __init__(self):
22 | pass
23 |
24 | def insert(self):
25 | pass
26 |
--------------------------------------------------------------------------------
/modules/reporting/hpfeeds_logger.py:
--------------------------------------------------------------------------------
1 | import hpfeeds
2 |
3 | from configobj import ConfigObj
4 |
5 | from base_logger import BaseLogger
6 |
7 |
8 | class HPFeedsLogger(BaseLogger):
9 |
10 | def __init__(self):
11 | self.buttinsky_config = ConfigObj("conf/buttinsky.cfg")
12 | if self.buttinsky_config["hpfeeds"]["enabled"] == "False":
13 | self.options = {'enabled': 'False'}
14 | return
15 |
16 | def on_error(payload):
17 | self.hpc.stop()
18 |
19 | def on_message(ident, chan, content):
20 | print content
21 | try:
22 | self.hpc = hpfeeds.new(self.buttinsky_config["hpfeeds"]["host"],
23 | int(self.buttinsky_config["hpfeeds"]["port"]),
24 | self.buttinsky_config["hpfeeds"]["ident"],
25 | self.buttinsky_config["hpfeeds"]["secret"])
26 | self.hpc.connect()
27 | self.options = {'enabled': 'True'}
28 | except KeyError:
29 | pass
30 |
31 | def insert(self, data):
32 | for chaninfo in self.buttinsky_config["hpfeeds"]["publish_channels"]:
33 | self.hpc.publish(chaninfo, data)
34 |
--------------------------------------------------------------------------------
/modules/reporting/print_logger.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | import logging
6 |
7 | from base_logger import BaseLogger
8 |
9 |
10 | staticlogger = {}
11 |
12 |
13 | class PrintLogger(BaseLogger):
14 | def __init__(self):
15 | global staticlogger
16 | if not "PrintLogger" in staticlogger:
17 | self.logger = logging.getLogger("PrintLogger")
18 | self.logger.setLevel(logging.DEBUG)
19 | ch = logging.StreamHandler()
20 | ch.setLevel(logging.DEBUG)
21 | formatter = logging.Formatter(
22 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
23 | ch.setFormatter(formatter)
24 | self.logger.addHandler(ch)
25 | staticlogger["PrintLogger"] = self.logger
26 | else:
27 | self.logger = staticlogger["PrintLogger"]
28 | self.options = {'enabled': 'True'}
29 |
30 | def insert(self, msg):
31 | self.logger.info(msg)
32 |
--------------------------------------------------------------------------------
/modules/sources/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mushorg/buttinsky/1a2a1b29f1d4078fdad051813a8d90080a1a1e84/modules/sources/__init__.py
--------------------------------------------------------------------------------
/modules/sources/base_source.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 |
6 | class BaseSource(object):
7 |
8 | def __init__(self):
9 | pass
10 |
11 | def received(self):
12 | pass
13 |
--------------------------------------------------------------------------------
/modules/sources/hpfeeds_sink.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | import json
6 | import xmlrpclib
7 |
8 | import gevent
9 | from configobj import ConfigObj
10 | import hpfeeds
11 | from base_source import BaseSource
12 |
13 |
14 | class HPFeedsSink(BaseSource):
15 |
16 | def __init__(self):
17 | self.buttinsky_config = ConfigObj("conf/buttinsky.cfg")
18 | url = "http://" + self.buttinsky_config["xmlrpc"]["server"] + ":" + self.buttinsky_config["xmlrpc"]["port"] + "/"
19 | self.xmlrpc_conn = xmlrpclib.ServerProxy(url)
20 | self.options = {'enabled': 'False'}
21 | self.hpc = hpfeeds.new(self.buttinsky_config["hpfeeds"]["host"],
22 | int(self.buttinsky_config["hpfeeds"]["port"]),
23 | self.buttinsky_config["hpfeeds"]["ident"],
24 | self.buttinsky_config["hpfeeds"]["secret"])
25 |
26 | def on_message(identifier, channel, payload):
27 | try:
28 | analysis_report = json.loads(str(payload))
29 | try:
30 | # TODO: Fix botnet id
31 | config = {"config":
32 | {
33 | "nick": analysis_report["irc_nick"],
34 | "host": analysis_report["irc_addr"].split(":", 1)[0],
35 | "port": analysis_report["irc_addr"].split(":", 1)[1],
36 | "server_pwd": analysis_report["irc_server_pwd"],
37 | "channel": analysis_report["irc_channel"]
38 | }
39 | }
40 | ret = self.xmlrpc_conn.create("12341231", json.dumps(config))
41 | print ret
42 | except:
43 | raise
44 | except:
45 | raise
46 |
47 | def on_error(payload):
48 | self.hpc.stop()
49 |
50 | self.hpc.subscribe(self.buttinsky_config["hpfeeds"]["source_channel"])
51 | gevent.spawn(self.hpc.run(on_message, on_error))
52 | self.hpc.close()
53 |
54 |
55 | if __name__ == "__main__":
56 | HPFeedsSink()
57 |
--------------------------------------------------------------------------------
/modules/util/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mushorg/buttinsky/1a2a1b29f1d4078fdad051813a8d90080a1a1e84/modules/util/__init__.py
--------------------------------------------------------------------------------
/modules/util/validate.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import json
4 | import validictory
5 |
6 | network_schema = {
7 | "type": "object",
8 | "properties": {
9 | "host": {
10 | "type": "string",
11 | },
12 | "port": {
13 | "type": "string",
14 | },
15 | "protocol_type": {
16 | "type": "string",
17 | },
18 | "reconn_attempts": {
19 | "type": "string",
20 | },
21 | "proxy_type": {
22 | "type": "string",
23 | "blank": True,
24 | },
25 | "proxy_host": {
26 | "type": "string",
27 | "blank": True,
28 | },
29 | "proxy_port": {
30 | "type": "string",
31 | "blank": True,
32 | }
33 | }
34 | }
35 |
36 | log_schema = {
37 | "type": "object",
38 | "properties": {
39 | "plugins": {
40 | "type": "string",
41 | }
42 | }
43 | }
44 |
45 | protocol_schema = {
46 | "type": "object",
47 | "properties": {
48 | "plugin": {
49 | "type": "string",
50 | }
51 | }
52 | }
53 |
54 | behavior_schema = {
55 | "type": "object",
56 | "properties": {
57 | "plugin": {
58 | "type": "string",
59 | }
60 | }
61 | }
62 |
63 | config_schema = {
64 | "type": "object",
65 | "properties": {
66 | "config": {
67 | "type": "object",
68 | "properties": {
69 | "network": network_schema,
70 | "log": log_schema,
71 | "protocol": protocol_schema,
72 | "behavior": behavior_schema,
73 | }
74 | }
75 | }
76 | }
77 |
78 | irc_protocol_schema = {
79 | "type": "object",
80 | "properties": {
81 | "plugin": {
82 | "type": "string",
83 | },
84 | "nick": {
85 | "type": "string",
86 | },
87 | "channel": {
88 | "type": "string",
89 | }
90 | }
91 | }
92 |
93 | irc_config_schema = {
94 | "type": "object",
95 | "properties": {
96 | "config": {
97 | "type": "object",
98 | "properties": {
99 | "network": network_schema,
100 | "log": log_schema,
101 | "protocol": irc_protocol_schema,
102 | "behavior": behavior_schema,
103 | }
104 | }
105 | }
106 | }
107 |
108 | http_protocol_schema = {} # TODO
109 | http_config_schema = {} # TODO
110 |
111 |
112 | def validate(filename):
113 | json_data = open('settings/' + filename)
114 | data = json.load(json_data)
115 | try:
116 | validictory.validate(data, config_schema)
117 | except ValueError, error:
118 | print error
119 |
--------------------------------------------------------------------------------
/netzobparse.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2013 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | """
6 |
7 | - Parses a Netzob project exported as XML.
8 | - Handles state machine updates based on protocol model and input to handleInput.
9 | - Botnet mimicking (symbol output) is done when a state transition occurs.
10 |
11 | Currently a PoC.
12 | The following protocol shows model of 'behaviors/models/customNetzobIRCModel.xml'
13 | and can be used for similar text based protocols such as IRC and HTTP.
14 |
15 | On channel join:
16 | Bot: im alive
17 | Botherder: hail the master
18 | Bot: hello world, my name is settings($nick)
19 | Botherder: ddos $domain
20 | Bot: ddosing $domain
21 |
22 | TODO:
23 |
24 | - Support for several variables in protocol messages
25 | - Output symbols based on probability and add handle delay of certain response
26 | - Save unsupported protocol messages in delimiter separated logs (for further modeling
27 | of the unkown messages in Netzob).
28 | - Support binary protocols
29 |
30 | """
31 |
32 |
33 | import binascii
34 | from xml.dom import minidom
35 |
36 |
37 | class NetzobModelParser(object):
38 |
39 | def __init__(self, path):
40 | self.STATES = []
41 | self.SYMBOLS = []
42 | self.TRANSITIONS = {}
43 | self.state = None
44 | self.__parse_model(path)
45 |
46 | def __findSymbol(self, id):
47 | for s in self.SYMBOLS:
48 | if s["id"] == id:
49 | return s
50 |
51 | def __findRef(self, id):
52 | for s in self.SYMBOLS:
53 | for f in s["fields"]:
54 | if f["varId"] == id:
55 | return s
56 |
57 | def handleInput(self, input, settings, init=False):
58 | msg = ""
59 | if self.state == None:
60 | initialState = self.STATES[0]["id"]
61 | trans = self.TRANSITIONS[initialState]
62 | if trans["input"] == None and init:
63 | symbol = trans["outputs"][0]
64 | found = self.__findSymbol(symbol)
65 | for i in found["fields"]:
66 | msg = msg + i["value"]
67 | self.state = trans["endState"]
68 | return msg
69 | return ""
70 |
71 | trans = self.TRANSITIONS[self.state]
72 | found = self.__findSymbol(trans["input"])
73 | inputSymbol = ""
74 | for i in found["fields"]:
75 | inputSymbol = inputSymbol + i["value"]
76 |
77 | if input == inputSymbol:
78 | found = self.__findSymbol(trans["outputs"][0])
79 | outputSymbol = ""
80 | for i in found["fields"]:
81 | outputSymbol = outputSymbol + i["value"]
82 | if "settings" in outputSymbol:
83 | setting = outputSymbol.split("settings($")[1].split(")")[0]
84 | msg = outputSymbol.replace("settings($" + setting + ")", settings[setting].encode("ascii"))
85 | elif inputSymbol in input:
86 | found = self.__findSymbol(trans["input"])
87 | sp = input.split(inputSymbol)
88 | found = self.__findSymbol(trans["outputs"][0])
89 | for i in found["fields"]:
90 | if len(i["ref"]) > 0:
91 | for j in sp:
92 | if len(j) > 0:
93 | msg = msg + j
94 | else:
95 | msg = msg + i["value"]
96 |
97 | if msg != "":
98 | self.state = trans["endState"]
99 | return msg
100 |
101 | def __bin2Ascii(self, bin_text):
102 | return ''.join(chr(int(bin_text[i:i+8], 2)) for i in xrange(0, len(bin_text), 8))
103 |
104 | def __parse_model(self, path):
105 | xmldoc = minidom.parse(path)
106 | grammar = xmldoc.getElementsByTagName('netzob:grammar')
107 | automata = grammar[0].getElementsByTagName('netzob:automata')
108 | states = grammar[0].getElementsByTagName('netzob:states')
109 | state = grammar[0].getElementsByTagName('netzob:state')
110 | transitions = grammar[0].getElementsByTagName('netzob:transitions')
111 | transition = grammar[0].getElementsByTagName('netzob:transition')
112 | symbols = xmldoc.getElementsByTagName('netzob:symbols')
113 | symbol = symbols[0].getElementsByTagName('netzob:symbol')
114 |
115 | symbolID = 0
116 | for s in symbol:
117 | symbolID = s.getAttribute("id").encode("ascii")
118 | f = s.getElementsByTagName("netzob:field")
119 | fields = s.getElementsByTagName("netzob:fields")
120 | string = ""
121 | symbol = {}
122 | symbol["id"] = symbolID
123 | symbol["fields"] = list()
124 |
125 | for field in fields:
126 | f = field.getElementsByTagName("netzob:field")
127 | for entry in f:
128 | format = entry.getElementsByTagName("netzob:format")
129 | var = entry.getElementsByTagName("netzob:variable")
130 | for v in var:
131 | id = v.getAttribute("id").encode("ascii")
132 | type = var[0].getElementsByTagName("netzob:type")
133 | mutable = var[0].getAttribute("mutable").encode("ascii")
134 | type = type[0].firstChild.data.encode("ascii")
135 | ref = ""
136 | try:
137 | ref = var[0].getElementsByTagName("netzob:ref")
138 | ref = ref[0].firstChild.data.encode("ascii")
139 | except:
140 | pass
141 | try:
142 | value = var[0].getElementsByTagName("netzob:originalValue")
143 | value = value[0].firstChild.data.encode("ascii")
144 | except:
145 | value = ""
146 | symbol["fields"].append({"varId": id, "value": value,"ref":ref, "mutable":mutable})
147 | self.SYMBOLS.append(symbol)
148 |
149 | for node in state:
150 | stateID = node.getAttribute("id").encode("ascii")
151 | stateName = node.getAttribute("name").encode("ascii")
152 | self.STATES.append({"id": stateID, "name": stateName})
153 |
154 | for node in transition:
155 | start = node.getElementsByTagName("netzob:startState")
156 | startState = start[0].firstChild.data.encode("ascii")
157 |
158 | end = node.getElementsByTagName("netzob:endState")
159 | endState = end[0].firstChild.data.encode("ascii")
160 | input = node.getElementsByTagName("netzob:input")
161 | stateInput = input[0].getAttribute("symbol").encode("ascii")
162 | if stateInput == "EmptySymbol":
163 | stateInput = None
164 | outputs = node.getElementsByTagName("netzob:outputs")
165 | for outs in outputs:
166 | out = outs.getElementsByTagName("netzob:output")
167 | outSymbol = list()
168 | for o in out:
169 | outSymbol.append(o.getAttribute("symbol").encode('ascii'))
170 | if len(outSymbol) == 0:
171 | outSymbol = None
172 | self.TRANSITIONS[startState] = {"endState": endState, "input": stateInput, "outputs": outSymbol}
173 |
--------------------------------------------------------------------------------
/protocols/__init__.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append("..")
3 |
--------------------------------------------------------------------------------
/protocols/http.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | from stack import LayerPlugin, Message
6 | from mimetools import Message as mtmsg
7 | from StringIO import StringIO as strio
8 |
9 |
10 | class HTTPProtocol(LayerPlugin):
11 |
12 | def settings(self, settings):
13 | pr_settings = settings["protocol"]
14 | self._default_method = pr_settings.get("default_method", "GET")
15 | self._default_uri = pr_settings.get("default_URI", "/")
16 | self._default_version = pr_settings.get("default_version", "HTTP/1.1")
17 | self._default_headers = pr_settings.get("default_headers", {})
18 |
19 | def transmit(self, msg):
20 | method = msg.data.get("method", self._default_method)
21 | uri = msg.data.get("URI", self._default_uri)
22 | version = msg.data.get("version", self._default_version)
23 | request = "{} {} {}\r\n".format(method, uri, version)
24 |
25 | headers = dict(self._default_headers.items() +
26 | msg.data.get("headers", {}).items())
27 | for name, value in headers.items():
28 | request += "{}: {}\r\n".format(name, value)
29 |
30 | body = msg.data.get("body", "")
31 | request += "\r\n{}".format(body)
32 |
33 | return Message(request, msg.left)
34 |
35 | def receive(self, msg):
36 | response = msg.data
37 | try:
38 | status, response = response.split("\r\n", 1)
39 | version, code, reason = status.split(" ", 2)
40 | response, body = response.split("\r\n\r\n", 1)
41 | headers = mtmsg(strio(response))
42 | except:
43 | return None
44 | else:
45 | return Message({
46 | "version": version,
47 | "code": code,
48 | "reason": reason,
49 | "headers": headers,
50 | "body": body,
51 | })
52 |
--------------------------------------------------------------------------------
/protocols/irc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | from stack import LayerPlugin, Message
6 |
7 |
8 | class IRCProtocol(LayerPlugin):
9 |
10 | def settings(self, settings):
11 | net_settings = settings["network"]
12 | pr_settings = settings["protocol"]
13 | self.settings = {
14 | "host": net_settings["host"],
15 | "port": int(net_settings["port"]),
16 | "channel": pr_settings["channel"],
17 | "nick": pr_settings["nick"],
18 | "hello": False,
19 | }
20 |
21 | def receive(self, msg):
22 | left = ""
23 | data = msg.data
24 | if not data or "\r\n" not in data:
25 | return Message()
26 | if not data.endswith("\r\n"):
27 | data, left = data.rsplit("\r\n", 1)
28 | messages = []
29 | for msg in data.split("\r\n"):
30 | if msg != "":
31 | message = {
32 | "prefix": "",
33 | "command": "",
34 | "args": [],
35 | }
36 | trailing = []
37 | if msg[0] == ":":
38 | message["prefix"], msg = msg[1:].split(" ", 1)
39 | if msg.find(" :") != -1:
40 | msg, trailing = msg.split(" :", 1)
41 | message["args"] = msg.split()
42 | message["args"].append(trailing)
43 | else:
44 | message["args"] = msg.split()
45 | message["command"] = message["args"].pop(0)
46 | messages.append(message)
47 | return Message(messages, left)
48 |
49 | def transmit(self, msg):
50 | transmsg = ""
51 | for m in msg.data:
52 | if "command" in m:
53 | if m["command"] == "001":
54 | chanlist = self.settings["channel"].split(",")
55 | for chan in chanlist:
56 | transmsg += "JOIN %s\r\n" % chan.strip()
57 | if m["command"] == "PING":
58 | transmsg += "PONG %s\r\n" % m["args"][0]
59 | if m["command"] == "PRIVMSG":
60 | transmsg += "PRIVMSG %s\r\n" % m["args"]
61 | if not self.settings["hello"]:
62 | set_nick = "NICK %s\r\n" % self.settings["nick"]
63 | set_user = "USER %s %s bla :%s\r\n" % (self.settings["nick"],
64 | self.settings["host"],
65 | self.settings["nick"],
66 | )
67 | transmsg = transmsg + set_nick + set_user
68 | self.settings["hello"] = True
69 | return Message(transmsg, msg.left)
70 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | configobj
2 | gevent
3 | validictory
4 | socksipy-branch
--------------------------------------------------------------------------------
/settings/http_test.set:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "network": {
4 | "host": "whatismyipaddress.com",
5 | "port": "80",
6 | "protocol_type": "TCP",
7 | "reconn_attempts": "2",
8 | "proxy_type": "socks5",
9 | "proxy_host": "localhost",
10 | "proxy_port": "9050"
11 | },
12 | "log": {
13 | "plugins": "print"
14 | },
15 | "protocol": {
16 | "plugin": "HTTP",
17 | "default_method": "GET",
18 | "default_URI": "/",
19 | "default_version": "HTTP/1.1",
20 | "default_headers": {
21 | "User-Agent": "Mozilla/5.0",
22 | "Host": "whatismyipaddress.com"
23 | }
24 | },
25 | "behavior": {
26 | "plugin": "address_check"
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/settings/irc_test.set:
--------------------------------------------------------------------------------
1 | {
2 | "config": {
3 | "network": {
4 | "host": "irc.freenode.net",
5 | "port": "6667",
6 | "protocol_type": "TCP",
7 | "reconn_attempts": "2",
8 | "proxy_type": "",
9 | "proxy_host": "",
10 | "proxy_port": ""
11 | },
12 | "log": {
13 | "plugins": "print"
14 | },
15 | "protocol": {
16 | "plugin": "IRC",
17 | "nick": "buttinsky-test",
18 | "channel": "#buttinsky-dev"
19 | },
20 | "behavior": {
21 | "plugin": "custom_irc_protocol"
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/spawner.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 | from gevent.monkey import patch_all
6 | patch_all()
7 |
8 | import json
9 | import os
10 | import sys
11 | from functools import partial
12 |
13 | from gevent import queue
14 |
15 | from event_loops import gevent_client
16 | from configobj import ConfigObj
17 |
18 | from protocols import irc, http
19 | from behaviors import simple_response, address_check, custom_irc_protocol
20 | from modules import reporter_handler
21 | from stack import Layer
22 |
23 | import gevent.pool
24 | group = gevent.pool.Group()
25 | #TODO : hpfeeds import to be removed when report_handler is ready
26 | import modules.reporting.hpfeeds_logger as hpfeeds
27 | import modules.sources.hpfeeds_sink as hpfeeds_sink
28 |
29 | from SimpleXMLRPCServer import SimpleXMLRPCServer
30 |
31 |
32 | def singleton(cls):
33 | instances = {}
34 |
35 | def getinstance():
36 | if cls not in instances:
37 | instances[cls] = cls()
38 | return instances[cls]
39 | return getinstance
40 |
41 |
42 | @singleton
43 | class MonitorList(object):
44 |
45 | def __init__(self):
46 | self.__stackList = {}
47 | self.__settingList = {}
48 | self.__fileList = {}
49 |
50 | def addStack(self, identifier, stack):
51 | self.__stackList[identifier] = stack
52 |
53 | def addSetting(self, identifier, setting):
54 | self.__settingList[identifier] = setting
55 |
56 | def addFile(self, identifier, filename):
57 | self.__fileList[identifier] = filename
58 |
59 | def getStack(self, identifier=None):
60 | if not identifier:
61 | return self.__stackList
62 | stack = None
63 | try:
64 | stack = self.__stackList[identifier]
65 | except (IndexError, KeyError):
66 | pass
67 | return stack
68 |
69 | def getSetting(self, identifier=None):
70 | if not identifier:
71 | return self.__settingList
72 | setting = None
73 | try:
74 | setting = self.__settingList[identifier]
75 | except IndexError:
76 | pass
77 | return setting
78 |
79 | def getFile(self, identifier=None):
80 | if not identifier:
81 | return self.__fileList
82 | filename = None
83 | try:
84 | filename = self.__fileList[identifier]
85 | except IndexError:
86 | pass
87 | return filename
88 |
89 | def removeStack(self, identifier):
90 | stack = self.getStack(identifier)
91 | if stack:
92 | del self.__stackList[identifier]
93 | return stack
94 |
95 | def removeSetting(self, identifier):
96 | setting = self.getSetting(identifier)
97 | if setting:
98 | del self.__settingList[identifier]
99 | return setting
100 |
101 | def removeFile(self, identifier):
102 | filename = self.getFile(identifier)
103 | if filename:
104 | del self.__fileList[identifier]
105 | return filename
106 |
107 |
108 | CONFIG_MONITOR = 0
109 | STOP_MONITOR = 1
110 | RESTART_MONITOR = 2
111 |
112 |
113 | class MonitorSpawner(object):
114 |
115 | def __init__(self, queue):
116 | self.messageQueue = queue
117 | self.ml = MonitorList()
118 |
119 | def work(self):
120 | try:
121 | g = gevent.spawn(self.listen)
122 | g.join()
123 | finally:
124 | g.kill()
125 |
126 | def listen(self):
127 | while True:
128 | data = self.messageQueue.get()
129 | msg_type = data[0]
130 | identifier = data[1]
131 |
132 | if msg_type == STOP_MONITOR or msg_type == RESTART_MONITOR:
133 | stack = self.ml.removeStack(identifier)
134 | setting = self.ml.removeSetting(identifier)
135 | filename = self.ml.removeFile(identifier)
136 | if stack:
137 | stack.disconnect()
138 | group.killone(stack.connect)
139 | if msg_type == RESTART_MONITOR:
140 | self.spawnMonitor(identifier, setting, filename)
141 | continue
142 |
143 | if msg_type == CONFIG_MONITOR:
144 | self.spawnMonitor(identifier, data[2], data[3])
145 |
146 | def spawnMonitor(self, identifier, config, filename):
147 | net_settings = config["network"]
148 | client = gevent_client.Client(net_settings["host"],
149 | net_settings["port"],
150 | net_settings["protocol_type"],
151 | net_settings["proxy_type"],
152 | net_settings["proxy_host"],
153 | net_settings["proxy_port"])
154 | # layer_network <-> layer_log <-> layer_protocol <-> layer_behavior
155 | layer_network = Layer(gevent_client.Layer1(client))
156 |
157 | log_plugins = [
158 | p.strip() for p in config["log"]["plugins"].split(",")]
159 | layer_log = Layer(reporter_handler.ReporterHandler(log_plugins),
160 | layer_network)
161 |
162 | if config["protocol"]["plugin"] == "IRC":
163 | protocol = irc.IRCProtocol()
164 | elif config["protocol"]["plugin"] == "HTTP":
165 | protocol = http.HTTPProtocol()
166 |
167 | if config["behavior"]["plugin"] == "simple_response":
168 | behavior = simple_response.SimpleResponse()
169 | elif config["behavior"]["plugin"] == "custom_irc_protocol":
170 | behavior = custom_irc_protocol.CustomIRCProtocol()
171 | elif config["behavior"]["plugin"] == "address_check":
172 | behavior = address_check.AddressCheck()
173 |
174 | layer_protocol = Layer(protocol, layer_log)
175 | layer_behavior = Layer(behavior, layer_protocol)
176 | layer_behavior.settings(config)
177 | layer_protocol.settings(config)
178 |
179 | layer_log.setUpper(layer_protocol)
180 | layer_network.setUpper(layer_log)
181 | layer_protocol.setUpper(layer_behavior)
182 |
183 | client.setLayer1(layer_network)
184 | g = group.spawn(client.connect)
185 | g.link(partial(self.onException, identifier))
186 | self.ml.addStack(identifier, client)
187 | self.ml.addSetting(identifier, config)
188 | self.ml.addFile(identifier, filename)
189 |
190 | def onException(self, identifier, greenlet):
191 | setting = self.ml.removeSetting(identifier)
192 | reconnAttempts = 3
193 | try:
194 | reconnAttempts = int(setting["network"]["reconn_attempts"])
195 | except KeyError:
196 | pass
197 |
198 | attempts = 0
199 | try:
200 | attempts = setting["attempts"]
201 | except KeyError:
202 | pass
203 |
204 | if attempts < reconnAttempts:
205 | setting["attempts"] = attempts + 1
206 | self.ml.addSetting(identifier, setting)
207 | self.messageQueue.put([RESTART_MONITOR, identifier])
208 | else:
209 | self.messageQueue.put([STOP_MONITOR, identifier])
210 |
211 |
212 | class ButtinskyXMLRPCServer(object):
213 |
214 | def __init__(self, messageQueue):
215 | self.ml = MonitorList()
216 | self.queue = messageQueue
217 |
218 | def load_sink(self):
219 | hpfeeds_sink.HPFeedsSink()
220 |
221 | def load(self, identifier, filename):
222 | if self.ml.getStack(identifier):
223 | raise Exception("Identifier " + identifier + " already exist")
224 | json_data = open('settings/' + filename)
225 | data = json.load(json_data)
226 | config = data["config"]
227 | self.queue.put([CONFIG_MONITOR, identifier, config, filename])
228 | json_data.close()
229 | return filename + " loaded with identifier: " + identifier
230 |
231 | def create(self, filename, config):
232 | path = "settings/" + filename
233 | if os.path.isfile(path):
234 | raise Exception("File " + path + " already exist")
235 | f = open(path, 'wb')
236 | f.write(config)
237 | f.close()
238 | return filename + " created"
239 |
240 | def status(self):
241 | status = self.ml.getFile()
242 | root = "settings/"
243 | status[""] = list()
244 | for path, _subdirs, files in os.walk(root):
245 | for name in files:
246 | filename = os.path.join(path, name).split(root)[1]
247 | if filename not in status.values():
248 | status[""].append(filename)
249 | return status
250 |
251 | def stop(self, identifier):
252 | if not self.ml.getStack(identifier):
253 | raise Exception("Identifier " + identifier + " does not exist")
254 | self.queue.put([STOP_MONITOR, identifier, None])
255 | return identifier + " stopped"
256 |
257 | def restart(self, identifier):
258 | if not self.ml.getStack(identifier):
259 | raise Exception("Identifier " + identifier + " does not exist")
260 | self.queue.put([RESTART_MONITOR, identifier, None])
261 | return identifier + " restarted"
262 |
263 | def list(self, filename):
264 | with open("settings/" + filename, "rb") as f:
265 | content = f.read()
266 | return content
267 |
268 | def delete(self, filename):
269 | os.remove("settings/" + filename)
270 | return filename + " deleted"
271 |
272 | def echo(self, msg):
273 | return "Msg recvd: " + msg
274 |
275 | if __name__ == '__main__':
276 | if not os.path.isfile("conf/buttinsky.cfg"):
277 | sys.exit("Modify and rename conf/buttinsky.cfg.dist to conf/buttinsky.cfg.")
278 | hpfeeds_logger = hpfeeds.HPFeedsLogger()
279 | messageQueue = queue.Queue()
280 | gevent.spawn(MonitorSpawner(messageQueue).work)
281 | buttinsky_config = ConfigObj("conf/buttinsky.cfg")
282 | hostname = buttinsky_config["xmlrpc"]["server"]
283 | port = int(buttinsky_config["xmlrpc"]["port"])
284 | server = SimpleXMLRPCServer((hostname, port))
285 | print "Listening on port 8000..."
286 | server.register_instance(ButtinskyXMLRPCServer(messageQueue))
287 | if buttinsky_config["hpfeeds"]["enabled"] == "True":
288 | gevent.spawn(ButtinskyXMLRPCServer(messageQueue).load_sink)
289 | try:
290 | server.serve_forever()
291 | except KeyboardInterrupt:
292 | print "Quitting... Bye!"
293 |
--------------------------------------------------------------------------------
/stack.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # Copyright (C) 2012 Buttinsky Developers.
3 | # See 'COPYING' for copying permission.
4 |
5 |
6 | class Message(object):
7 |
8 | def __init__(self, data="", left=""):
9 | self.data = data
10 | if not left:
11 | self.left = ""
12 | else:
13 | self.left = left
14 |
15 |
16 | class Layer(object):
17 |
18 | def __init__(self, plugin, lower=None, upper=None):
19 | self.plugin = plugin
20 | self.upper = upper
21 | self.lower = lower
22 |
23 | def setLower(self, lower):
24 | self.lower = lower
25 |
26 | def setUpper(self, upper):
27 | self.upper = upper
28 |
29 | def transmit(self, msg):
30 | msg = self.plugin.transmit(msg)
31 | if self.lower:
32 | self.lower.transmit(msg)
33 |
34 | def receive(self, msg):
35 | msg = self.plugin.receive(msg)
36 | if self.upper:
37 | self.upper.receive(msg)
38 | else:
39 | self.transmit(msg)
40 |
41 | def settings(self, settings):
42 | self.plugin.settings(settings)
43 |
44 |
45 | class LayerPlugin(object):
46 |
47 | def __init__(self):
48 | pass
49 |
50 | def transmit(self, msg):
51 | raise NotImplementedError
52 |
53 | def receive(self, msg):
54 | raise NotImplementedError
55 |
56 | def settings(self, settings):
57 | raise NotImplementedError
58 |
--------------------------------------------------------------------------------