├── .gitignore
├── COPYING
├── Makefile
├── README.md
├── core
├── cert.go
├── config.go
├── log.go
├── module.go
├── project
│ ├── decoder
│ │ └── decoder.go
│ └── project.go
└── session.go
├── darwin
├── .DS_Store
└── Contents
│ ├── Info.plist
│ └── Resources
│ └── broxy.icns
├── go.mod
├── go.sum
├── gui
├── history.go
├── listdelegate.go
├── maingui.go
└── projectgui.go
├── icon.ico
├── icon.rc
├── icon_windows.syso
├── main.go
├── media
├── icon.png
├── main.png
├── screen1.png
└── screen2.png
├── modules
├── coreproxy
│ ├── coreproxy.go
│ ├── coreproxy_controller.go
│ ├── coreproxy_gui.go
│ ├── coreproxy_interceptor.go
│ ├── coreproxy_module.go
│ ├── coreproxy_settings.go
│ └── model
│ │ ├── filters.go
│ │ ├── model.go
│ │ └── sormodel.go
├── log
│ ├── log.go
│ ├── log_controller.go
│ ├── log_gui.go
│ ├── log_module.go
│ └── model
│ │ ├── model.go
│ │ └── sortmodel.go
├── module.go
└── repeater
│ ├── repeater.go
│ ├── repeater_controller.go
│ ├── repeater_gui.go
│ └── repeater_module.go
└── util
└── util.go
/.gitignore:
--------------------------------------------------------------------------------
1 | main
2 | moc.*
3 | *.cpp
4 | .DS_Store
5 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | DEPLOY ?= qtdeploy
2 | FLAGS ?=
3 |
4 | build:
5 | $(DEPLOY) $(FLAGS) build desktop .
6 |
7 | test:
8 | $(DEPLOY) $(FLAGS) test desktop .
9 |
10 | test-fast:
11 | $(DEPLOY) $(FLAGS) --fast test desktop .
12 |
13 | clean:
14 | find . -type f -name 'moc.*' -exec rm {} +
15 | find . -type f -name 'moc_*' -exec rm {} +
16 | find . -type f -name 'rcc.*' -exec rm {} +
17 | find . -type f -name 'rcc_*' -exec rm {} +
18 | rm -r deploy
19 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Broxy
2 |
3 | [](https://raw.githubusercontent.com/rhaidiz/broxy/master/COPYING)
4 |
5 | Broxy is an open source intercept proxy written in Go. It makes use of [goproxy](https://github.com/elazarl/goproxy) as core proxy implementation and the interface is implemented with a [Qt wrapper](https://github.com/therecipe/qt) for Go.
6 |
7 | **DISCLAIMER:** this is a PoC to understand the feseability of the project. As a result of this test a new project has spawn, named [yves](https://github.com/rhaidiz/yves).
8 |
9 | 
10 |
11 | ## Features
12 | Broxy is currently a work in progress project. The current version provides the following features:
13 |
14 | * Interceptor
15 | * History with filters
16 | * Repeater
17 | * Persistent sessions
18 |
19 | # Installation
20 |
21 | ## Grab a Binary
22 | Grab a compiled version of Broxy [here](https://github.com/rhaidiz/broxy/releases).
23 |
24 | ## Compiling from Sources
25 | To compile Broxy make sure you have the following installed and properly configured:
26 |
27 | * [Go](https://golang.org/doc/install)
28 | * [Qt 5.13 and Qt wrapper](https://github.com/therecipe/qt/wiki/Installation)
29 |
30 | Once Go, Qt 5.13 and the Qt wrapper are ready, just do:
31 |
32 | go get github.com/rhaidiz/broxy
33 | cd $GOPATH/src/github.com/rhaidiz/broxy
34 | make build
35 |
36 | Once the compilation is finished, you'll have the binary inside the folder `deploy` ... 🤞!
37 |
38 | # License
39 | Broxy is released under the GPLv3 license.
40 |
41 |
--------------------------------------------------------------------------------
/core/cert.go:
--------------------------------------------------------------------------------
1 | // thanks to evilsocket's amazing code from bettercap
2 |
3 | package core
4 |
5 | import (
6 | "crypto/rand"
7 | "crypto/rsa"
8 | "crypto/tls"
9 | "crypto/x509"
10 | "crypto/x509/pkix"
11 | "fmt"
12 | "math/big"
13 | "net"
14 | "strconv"
15 | "strings"
16 | "sync"
17 | "time"
18 |
19 | "github.com/elazarl/goproxy"
20 | )
21 |
22 | var (
23 | certCache = make(map[string]*tls.Certificate)
24 | certLock = &sync.Mutex{}
25 | )
26 |
27 | // CreateCA returns a Certificate Authority and its private key
28 | func CreateCA() ([]byte, []byte, error) {
29 | priv, err := rsa.GenerateKey(rand.Reader, 4096)
30 | if err != nil {
31 | return nil, nil, err
32 | }
33 |
34 | notBefore := time.Now()
35 | aYear := time.Duration(365*24) * time.Hour
36 | notAfter := notBefore.Add(aYear)
37 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
38 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
39 | if err != nil {
40 | return nil, nil, err
41 | }
42 |
43 | template := x509.Certificate{
44 | SerialNumber: serialNumber,
45 | Subject: pkix.Name{
46 | Country: []string{"US"},
47 | Locality: []string{""},
48 | Organization: []string{"broxy"},
49 | OrganizationalUnit: []string{"https://github.com/rhaidiz/broxy/"},
50 | CommonName: "broxy Certificate Authority",
51 | },
52 | NotBefore: notBefore,
53 | NotAfter: notAfter,
54 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
55 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
56 | BasicConstraintsValid: true,
57 | IsCA: true,
58 | }
59 |
60 | cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
61 | if err != nil {
62 | return nil, nil, err
63 | }
64 |
65 | return x509.MarshalPKCS1PrivateKey(priv), cert, err
66 | }
67 |
68 | // TLSConfigFromCA returns a TLS configuration with a custom CA
69 | func TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *goproxy.ProxyCtx) (*tls.Config, error) {
70 | return func(host string, ctx *goproxy.ProxyCtx) (c *tls.Config, err error) {
71 | parts := strings.SplitN(host, ":", 2)
72 | hostname := parts[0]
73 | port := 443
74 | if len(parts) > 1 {
75 | port, err = strconv.Atoi(parts[1])
76 | if err != nil {
77 | port = 443
78 | }
79 | }
80 |
81 | cert := getCachedCert(hostname, port)
82 | if cert == nil {
83 | cert, err = signHost(ca, hostname, port)
84 | if err != nil {
85 | return nil, err
86 | }
87 | setCachedCert(hostname, port, cert)
88 | }
89 |
90 | config := tls.Config{
91 | InsecureSkipVerify: true,
92 | Certificates: []tls.Certificate{*cert},
93 | }
94 |
95 | return &config, nil
96 | }
97 | }
98 |
99 | func signHost(ca *tls.Certificate, host string, port int) (cert *tls.Certificate, err error) {
100 | var x509ca *x509.Certificate
101 | var template x509.Certificate
102 |
103 | if x509ca, err = x509.ParseCertificate(ca.Certificate[0]); err != nil {
104 | return
105 | }
106 |
107 | notBefore := time.Now()
108 | aYear := time.Duration(365) * time.Hour
109 | notAfter := notBefore.Add(aYear)
110 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
111 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
112 | if err != nil {
113 | return nil, err
114 | }
115 |
116 | template = x509.Certificate{
117 | SerialNumber: serialNumber,
118 | Issuer: x509ca.Subject,
119 | Subject: pkix.Name{
120 | Country: []string{"US"},
121 | Locality: []string{""},
122 | Organization: []string{"broxy"},
123 | OrganizationalUnit: []string{"https://github.com/rhaidiz/broxy/"},
124 | CommonName: "broxy mitm certificate",
125 | },
126 | NotBefore: notBefore,
127 | NotAfter: notAfter,
128 | //KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
129 | //ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
130 | //BasicConstraintsValid: true,
131 | }
132 |
133 | if ip := net.ParseIP(host); ip != nil {
134 | template.IPAddresses = append(template.IPAddresses, ip)
135 | } else {
136 | template.DNSNames = append(template.DNSNames, host)
137 | }
138 |
139 | var certpriv *rsa.PrivateKey
140 | if certpriv, err = rsa.GenerateKey(rand.Reader, 2048); err != nil {
141 | return
142 | }
143 |
144 | var derBytes []byte
145 | if derBytes, err = x509.CreateCertificate(rand.Reader, &template, x509ca, &certpriv.PublicKey, ca.PrivateKey); err != nil {
146 | return
147 | }
148 |
149 | return &tls.Certificate{
150 | Certificate: [][]byte{derBytes, ca.Certificate[0]},
151 | PrivateKey: certpriv,
152 | }, nil
153 | }
154 |
155 | func keyFor(domain string, port int) string {
156 | return fmt.Sprintf("%s:%d", domain, port)
157 | }
158 |
159 | func getCachedCert(domain string, port int) *tls.Certificate {
160 | certLock.Lock()
161 | defer certLock.Unlock()
162 | if cert, found := certCache[keyFor(domain, port)]; found {
163 | return cert
164 | }
165 | return nil
166 | }
167 |
168 | func setCachedCert(domain string, port int, cert *tls.Certificate) {
169 | certLock.Lock()
170 | defer certLock.Unlock()
171 | certCache[keyFor(domain, port)] = cert
172 | }
173 |
--------------------------------------------------------------------------------
/core/config.go:
--------------------------------------------------------------------------------
1 | package core
2 |
3 | import (
4 | "encoding/pem"
5 | "encoding/xml"
6 | "fmt"
7 | "io/ioutil"
8 | "os"
9 | "path/filepath"
10 | )
11 | // Config represents the global configuration
12 | type BroxySettings struct {
13 | CACertificate []byte `xml:"CACert"`
14 | CAPrivateKey []byte `xml:"CAPvt"`
15 | }
16 |
17 | type GlobalSettings struct {
18 | GZipDecode bool
19 | }
20 |
21 | var broxySettingsFileName = "broxy_settings.xml"
22 |
23 | // LoadGlobalSettings loads the global settings
24 | func LoadGlobalSettings(path string) *BroxySettings {
25 |
26 | // if path doesn't exists, create it
27 | if _, err := os.Stat(path); os.IsNotExist(err) {
28 | os.MkdirAll(path, 0700)
29 | }
30 |
31 | var cfg *BroxySettings
32 | xmlSettingsPath := filepath.Join(path, broxySettingsFileName)
33 | xmlSettingsFile, err := os.Open(xmlSettingsPath)
34 | defer xmlSettingsFile.Close()
35 | if err != nil {
36 | // create the file and put in a new fresh default settings
37 | cfg = initGlobalSettings()
38 | saveGlobalSettings(cfg, xmlSettingsPath)
39 | return cfg
40 | }
41 |
42 | byteValue, err := ioutil.ReadAll(xmlSettingsFile)
43 | if err != nil {
44 | fmt.Println(err)
45 | }
46 |
47 | err = xml.Unmarshal(byteValue, &cfg)
48 | if err != nil {
49 | cfg = initGlobalSettings()
50 | saveGlobalSettings(cfg, xmlSettingsPath)
51 | }
52 |
53 | // TODO: add a method that checks the configuration just loaded
54 |
55 | return cfg
56 |
57 | }
58 |
59 | func initGlobalSettings() *BroxySettings {
60 | // generate a new CA
61 | // TODO: handle error generated by CreateCA
62 | rawPvt, rawCA, _ := CreateCA()
63 | pemPvt := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: rawPvt})
64 | pemCA := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rawCA})
65 | cfg := &BroxySettings{
66 | CACertificate: pemCA,
67 | CAPrivateKey: pemPvt,
68 | }
69 | return cfg
70 | }
71 |
72 | func saveGlobalSettings(cfg *BroxySettings, path string) error {
73 | xmlSettings, _ := xml.MarshalIndent(cfg, "", " ")
74 | return ioutil.WriteFile(path, xmlSettings, 0700)
75 | }
76 |
--------------------------------------------------------------------------------
/core/log.go:
--------------------------------------------------------------------------------
1 | package core
2 |
3 | import "fmt"
4 |
5 | // Log represents a log message
6 | type Log struct {
7 | Type string
8 | ModuleName string
9 | Time string
10 | Message string
11 | }
12 |
13 | // ToString prints a string representation of a log message
14 | func (l *Log) ToString() string {
15 | return fmt.Sprintf("[%s][%s][%s] %s", l.Type, l.ModuleName, l.Time, l.Message)
16 | }
17 |
--------------------------------------------------------------------------------
/core/module.go:
--------------------------------------------------------------------------------
1 | package core
2 |
3 | // Module interface
4 | type Module interface {
5 | Name() string
6 | Description() string
7 | Status() bool
8 | Start() error
9 | Stop() error
10 | }
11 |
12 | // GuiModule interface
13 | type GuiModule interface {
14 | GetModuleGui() interface{}
15 | GetSettings() interface{}
16 | Title() string
17 | }
18 |
19 | // ControllerModule interface
20 | type ControllerModule interface {
21 | ExecCommand(string, ...interface{})
22 | GetModule() Module
23 | GetGui() GuiModule
24 | }
25 |
--------------------------------------------------------------------------------
/core/project/decoder/decoder.go:
--------------------------------------------------------------------------------
1 | package decoder
2 |
3 | type Decoder interface {
4 | Decode(interface{}) error
5 | Unmarshal([]byte, interface{}) error
6 | }
7 |
8 | type Encoder interface {
9 | Encode(interface{}) error
10 | Marshal(interface{}) ([]byte, error)
11 | }
--------------------------------------------------------------------------------
/core/project/project.go:
--------------------------------------------------------------------------------
1 | package project
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "strings"
7 | "os"
8 | "path/filepath"
9 | "io/ioutil"
10 |
11 | "github.com/rhaidiz/broxy/core/project/decoder"
12 | )
13 |
14 | // PersistentProject represents a persistent project
15 | type PersistentProject struct {
16 | project *Project
17 | projectPath string // the path to the project to disk (including projectName)
18 | projectName string // the name of the project to disk
19 | isPersistent bool
20 | }
21 |
22 | // Project represents the basic information of a project
23 | type Project struct {
24 | Title string
25 | Path string
26 | }
27 |
28 | var fileExtension = "broxy"
29 | var fileSuffix = "settings"
30 |
31 | func NewPersistentProject(t string, p string) (*PersistentProject, error) {
32 |
33 | projectName := t //fmt.Sprintf("%s.%s",t,fileExtension)
34 | projectPath := filepath.Join(p,projectName)
35 |
36 | err := os.MkdirAll(projectPath, os.ModePerm)
37 | if err != nil{
38 | return nil, err
39 | }
40 | return &PersistentProject{
41 | projectPath: projectPath,
42 | projectName: projectName,
43 | project: &Project{Title:t, Path:p},
44 | isPersistent: false,
45 | },nil
46 | }
47 |
48 | // TODO: add error in case of opening. How do I even know if this is a broxy project?
49 | func OpenPersistentProject(t string, p string) (*PersistentProject, error) {
50 | projectName := t
51 | projectPath := filepath.Join(p,projectName)
52 | // check if the project path actually exists
53 | if _, err := os.Stat(projectPath); os.IsNotExist(err) {
54 | return nil, err
55 | }
56 | return &PersistentProject{
57 | projectPath: projectPath,
58 | projectName: projectName,
59 | project: &Project{Title:t, Path:p},
60 | isPersistent: false,
61 | }, nil
62 | }
63 |
64 | func (p *PersistentProject) GetTitle() string {
65 | return p.project.Title
66 | }
67 |
68 | // SaveToFile provides modules the possibility of saving something to file in a JSON format
69 | func (p *PersistentProject) SaveToFile(m string, stg interface{}) error {
70 | return p.saveToFile(m,"_",stg)
71 | }
72 |
73 | // LoadModuleSettings provides modules the possibility of loading something in JSON
74 | func (p *PersistentProject) LoadFromFile(m string, stg interface{}) error {
75 | return p.loadFromFile(m,"_",stg)
76 | }
77 |
78 | // SaveSettings saves a setting file
79 | func (p *PersistentProject) SaveSettings(m string, stg interface{}) error {
80 | return p.saveToFile(m,"settings_",stg)
81 | }
82 |
83 | // LoadSettings loads a setting file
84 | func (p *PersistentProject) LoadSettings(m string, stg interface{}) error {
85 | return p.loadFromFile(m,"settings_",stg)
86 | }
87 |
88 | func (p *PersistentProject) saveToFile(m,t string, stg interface{}) error {
89 | b, err := json.Marshal(stg)
90 | if err != nil {
91 | return err
92 | }
93 | // write to file
94 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s%s.json",t,strings.ToLower(m)))
95 | return ioutil.WriteFile(fileName, b, 0644)
96 | }
97 |
98 | func (p *PersistentProject) loadFromFile(m,t string, stg interface{}) error {
99 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s%s.json",t,strings.ToLower(m)))
100 | jsonFile, err := os.Open(fileName)
101 | if err != nil {
102 | // file does not exist, create it
103 | return p.saveToFile(m,t,stg)
104 | }
105 | byteValue, _ := ioutil.ReadAll(jsonFile)
106 | return json.Unmarshal(byteValue, &stg)
107 | }
108 |
109 | // FileEncoder provides an Encoder to write stuff to file
110 | func (p *PersistentProject) FileEncoder(m string) (*json.Encoder, error) {
111 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s.json",strings.ToLower(m)))
112 | jsonFile, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
113 | if err != nil {
114 | return nil, err
115 | }
116 | return json.NewEncoder(jsonFile), nil
117 | }
118 |
119 | // FileDecoder provides a Decoder to read stuff from file
120 | func (p *PersistentProject) FileDecoder(m string) (*json.Decoder, error) {
121 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s.json",strings.ToLower(m)))
122 | jsonFile, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_RDONLY, 0644)
123 | if err != nil {
124 | return nil, err
125 | }
126 | return json.NewDecoder(jsonFile), nil
127 | }
128 |
129 | type FileDecoder struct {
130 | decoder.Decoder
131 | actualDecoder *json.Decoder
132 | }
133 |
134 | func (d *FileDecoder) Decode(i interface{}) error {
135 | return d.actualDecoder.Decode(i)
136 | }
137 |
138 | func (d *FileDecoder) Unmarshal(data []byte, v interface{}) error {
139 | return json.Unmarshal(data, v)
140 | }
141 |
142 | type FileEncoder struct {
143 | decoder.Encoder
144 | actualEncoder *json.Encoder
145 | }
146 |
147 | func (d *FileEncoder) Encode(i interface{}) error {
148 | return d.actualEncoder.Encode(i)
149 | }
150 |
151 | func (d *FileEncoder) Marshal(v interface{}) ([]byte, error){
152 | return json.Marshal(v)
153 | }
154 |
155 | func (p *PersistentProject) FileDecoder2(m string) (decoder.Decoder, error){
156 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s.json",strings.ToLower(m)))
157 | jsonFile, err := os.OpenFile(fileName, os.O_RDONLY|os.O_CREATE, 0644)
158 | if err != nil {
159 | return nil, err
160 | }
161 | return &FileDecoder{actualDecoder: json.NewDecoder(jsonFile)},nil
162 | }
163 |
164 | func (p *PersistentProject) FileEncoder2(m string) (decoder.Encoder, error) {
165 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s.json",strings.ToLower(m)))
166 | jsonFile, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
167 | if err != nil {
168 | return nil, err
169 | }
170 | return &FileEncoder{actualEncoder: json.NewEncoder(jsonFile)},nil
171 | }
172 |
173 | func (p *PersistentProject) CreateFile(f string) (*os.File, error){
174 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s.json",strings.ToLower(f)))
175 | return os.Create(fileName)
176 | }
177 |
178 | func (p *PersistentProject) DeleteFile(f string) error {
179 | fileName := filepath.Join(p.projectPath, fmt.Sprintf("%s.json",strings.ToLower(f)))
180 | return os.Remove(fileName)
181 | }
182 |
183 |
184 | // Persist persists the project to disk in location pa
185 | func (p *PersistentProject) Persist(pn, pa string) error {
186 | dest := filepath.Join(pa,pn)
187 | err := os.Rename(p.projectPath, dest)
188 | if err != nil {
189 | return err
190 | }
191 | p.isPersistent = true
192 | p.projectName = pn
193 | p.project.Title = pn
194 | p.projectPath = dest
195 | return nil
196 | }
197 |
--------------------------------------------------------------------------------
/core/session.go:
--------------------------------------------------------------------------------
1 | package core
2 |
3 | import (
4 | "time"
5 | "github.com/rhaidiz/broxy/core/project"
6 | "github.com/rhaidiz/broxy/util"
7 | )
8 |
9 | type MainGui interface {
10 | AddGuiModule(GuiModule)
11 | InitWith(*Session)
12 | ShowErrorMessage(string)
13 | }
14 |
15 | // Session represents a running session in Broxy with a GUI and loaded modules
16 | type Session struct {
17 | Controllers []ControllerModule
18 |
19 | Logs []Log
20 | LogEvent chan Log
21 |
22 | MainGui MainGui
23 | PersistentProject *project.PersistentProject
24 |
25 | Settings *BroxySettings
26 | GlobalSettings *GlobalSettings
27 | }
28 |
29 | // NewSession creates a new session
30 | func NewSession(cfg *BroxySettings, p *project.PersistentProject, gui MainGui) *Session {
31 | gc := &GlobalSettings{}
32 | p.LoadSettings("project",gc)
33 | s := &Session{
34 | MainGui: gui,
35 | Settings: cfg,
36 | GlobalSettings: gc,
37 | LogEvent: make(chan Log),
38 | PersistentProject: p,
39 | }
40 | gui.InitWith(s)
41 | return s
42 | }
43 |
44 | // LoadModule loads a module in the current session
45 | func (s *Session) LoadModule(c ControllerModule) {
46 | if !util.IsNil(c) {
47 | s.Controllers = append(s.Controllers, c)
48 | s.MainGui.AddGuiModule(c.GetGui())
49 | }
50 | }
51 |
52 | // Exec executes, for a given module m, a function f with parameters a
53 | func (s *Session) Exec(c string, f string, a ...interface{}) {
54 | for _, ctrl := range s.Controllers {
55 | if c == ctrl.GetModule().Name() {
56 | ctrl.ExecCommand(f, a...)
57 | }
58 | }
59 | }
60 |
61 | // Info logs an information message in the current session
62 | func (s *Session) Info(mod string, message string) {
63 | t := time.Now()
64 | l := Log{Type: "I", ModuleName: mod, Time: t.Format("2006-01-02 15:04:05"), Message: message}
65 | s.Logs = append(s.Logs, l)
66 | go func() { s.LogEvent <- l }()
67 | }
68 |
69 | // Debug logs a debug information messasge in the current session
70 | func (s *Session) Debug(mod string, message string) {
71 | t := time.Now()
72 | l := Log{Type: "D", ModuleName: mod, Time: t.Format("2006-01-02 15:04:05"), Message: message}
73 | s.Logs = append(s.Logs, l)
74 | go func() { s.LogEvent <- l }()
75 | }
76 |
77 | // Err logs an error information message in the current session
78 | func (s *Session) Err(mod string, message string) {
79 | t := time.Now()
80 | l := Log{Type: "E", ModuleName: mod, Time: t.Format("2006-01-02 15:04:05"), Message: message}
81 | s.Logs = append(s.Logs, l)
82 | go func() { s.LogEvent <- l }()
83 | }
84 |
85 | func (s *Session) ShowErrorMessage(message string){
86 | s.MainGui.ShowErrorMessage(message)
87 | }
88 |
--------------------------------------------------------------------------------
/darwin/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/darwin/.DS_Store
--------------------------------------------------------------------------------
/darwin/Contents/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleExecutable
6 | darwin
7 | CFBundleIconFile
8 | broxy.icns
9 | CFBundleExecutable
10 | broxy
11 | CFBundleIdentifier
12 | com.rhaidiz.broxy
13 | CFBundleName
14 | broxy
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 0.1.0
19 | CFBundleSignature
20 | ????
21 | LSMinimumSystemVersion
22 | 10.11
23 | NSPrincipalClass
24 | NSApplication
25 | NSSupportsAutomaticGraphicsSwitching
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/darwin/Contents/Resources/broxy.icns:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/darwin/Contents/Resources/broxy.icns
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/rhaidiz/broxy
2 |
3 | go 1.12
4 |
5 | require (
6 | github.com/atotto/clipboard v0.1.2
7 | github.com/elazarl/goproxy v0.0.0-20191011121108-aa519ddbe484
8 | github.com/therecipe/qt v0.0.0-20200103041036-2b818d970888
9 | github.com/therecipe/qt/internal/binding/files/docs/5.13.0 v0.0.0-20200103041036-2b818d970888 // indirect
10 | )
11 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/atotto/clipboard v0.1.2 h1:YZCtFu5Ie8qX2VmVTBnrqLSiU9XOWwqNRmdT3gIQzbY=
2 | github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
5 | github.com/elazarl/goproxy v0.0.0-20191011121108-aa519ddbe484 h1:pEtiCjIXx3RvGjlUJuCNxNOw0MNblyR9Wi+vJGBFh+8=
6 | github.com/elazarl/goproxy v0.0.0-20191011121108-aa519ddbe484/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM=
7 | github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 h1:dWB6v3RcOy03t/bUadywsbyrQwCqZeNIEX6M1OtSZOM=
8 | github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8=
9 | github.com/gopherjs/gopherjs v0.0.0-20190411002643-bd77b112433e h1:XWcjeEtTFTOVA9Fs1w7n2XBftk5ib4oZrhzWk0B+3eA=
10 | github.com/gopherjs/gopherjs v0.0.0-20190411002643-bd77b112433e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
11 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
12 | github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
13 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
14 | github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc=
15 | github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
16 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
17 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
18 | github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
19 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
20 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
21 | github.com/therecipe/qt v0.0.0-20200103041036-2b818d970888 h1:kwDtZGIbjPGYzvs4Dk/4O4E2nnJugQkccLyfFUHpHk0=
22 | github.com/therecipe/qt v0.0.0-20200103041036-2b818d970888/go.mod h1:SUUR2j3aE1z6/g76SdD6NwACEpvCxb3fvG82eKbD6us=
23 | github.com/therecipe/qt/internal/binding/files/docs/5.12.0 v0.0.0-20200103041036-2b818d970888/go.mod h1:7m8PDYDEtEVqfjoUQc2UrFqhG0CDmoVJjRlQxexndFc=
24 | github.com/therecipe/qt/internal/binding/files/docs/5.13.0 v0.0.0-20200103041036-2b818d970888/go.mod h1:mH55Ek7AZcdns5KPp99O0bg+78el64YCYWHiQKrOdt4=
25 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
26 | golang.org/x/crypto v0.0.0-20190418165655-df01cb2cc480/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
27 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
28 | golang.org/x/net v0.0.0-20190420063019-afa5a82059c6/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
29 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
30 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
31 | golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
32 | golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
33 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
34 | golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
35 |
--------------------------------------------------------------------------------
/gui/history.go:
--------------------------------------------------------------------------------
1 | package gui
2 |
3 | import (
4 | "os"
5 | "path/filepath"
6 | "encoding/json"
7 | "io/ioutil"
8 | "fmt"
9 | "github.com/rhaidiz/broxy/core/project"
10 | )
11 |
12 | // History represents a history of projects
13 | type History struct {
14 | H []*project.Project `json:"ProjectsHistory"`
15 | path string
16 | }
17 |
18 | var historyFileName = "history.json"
19 |
20 | // LoadHistory loads the projects history stored in path
21 | func LoadHistory(path string) *History {
22 |
23 | historyPath := filepath.Join(path, historyFileName)
24 | historyFile, err := os.Open(historyPath)
25 | defer historyFile.Close()
26 | if err != nil {
27 | // no history
28 | return &History{path:path}
29 | }
30 | byteValue, err := ioutil.ReadAll(historyFile)
31 | // TODO: handle error
32 | if err != nil {
33 | fmt.Println(err)
34 | }
35 | var history *History
36 | err = json.Unmarshal(byteValue, &history)
37 | if err != nil {
38 | return &History{path:path}
39 | }
40 | history.path = path
41 | return history
42 | }
43 |
44 | // SaveToHistory saves a new project to the history
45 | func (h *History) Add(p *project.Project) error {
46 | h.H = append(h.H, p)
47 |
48 | historyJson, _ := json.MarshalIndent(h, "", " ")
49 | historyFile := filepath.Join(h.path, historyFileName)
50 |
51 | return ioutil.WriteFile(historyFile, historyJson, 0700)
52 | }
53 |
54 | // RemoveFromHistory removes an entry from the history
55 | func (h *History) Remove(p *project.Project) error{
56 | r := -1
57 | for i,e := range h.H {
58 | if e.Title == p.Title && e.Path == p.Path{
59 | r = i
60 | }
61 | }
62 | copy(h.H[r:], h.H[r+1:]) // Shift a[i+1:] left one index.
63 | h.H = h.H[:len(h.H)-1] // Truncate slice.
64 |
65 | historyJson, _ := json.MarshalIndent(h, "", " ")
66 | historyFile := filepath.Join(h.path, historyFileName)
67 |
68 | return ioutil.WriteFile(historyFile, historyJson, 0700)
69 | }
--------------------------------------------------------------------------------
/gui/listdelegate.go:
--------------------------------------------------------------------------------
1 | package gui
2 |
3 | import (
4 | "github.com/therecipe/qt/core"
5 | "github.com/therecipe/qt/gui"
6 | "github.com/therecipe/qt/widgets"
7 | )
8 |
9 | // Delegate represents the listView delegate to list projects
10 | type Delegate struct {
11 | widgets.QStyledItemDelegate
12 | qApp *widgets.QApplication
13 | }
14 |
15 | // InitDelegate is used to initialize the delegate
16 | func InitDelegate(qApp *widgets.QApplication) *Delegate {
17 | item := NewDelegate(nil) //will be generated in moc.go
18 | item.qApp = qApp
19 | item.ConnectPaint(item.paint)
20 | item.ConnectSizeHint(item.sizeHint)
21 | return item
22 | }
23 |
24 | func (i Delegate) paint(painter *gui.QPainter, option *widgets.QStyleOptionViewItem, index *core.QModelIndex) {
25 |
26 | //widgets.QStyleOptionViewItem options = option
27 | i.InitStyleOption(option, index)
28 |
29 | painter.Save()
30 |
31 | doc := gui.NewQTextDocument(nil)
32 | //doc.setHtml(options.text);
33 | //fontMetric := gui.NewQFontMetricsF(painter.Font())
34 |
35 | //localElidedText := fontMetric.ElidedText(option.Text(), core.Qt__ElideMiddle, 355, 0)
36 | doc.SetHtml(option.Text())
37 |
38 | /* Call this to get the focus rect and selection background. */
39 | option.SetText("")
40 | //option.GetWidget.Style().drawControl(widgets.QStyle__CE_ItemViewItem, option, painter)
41 | //w := widgets.NewQWidgetFromPointer(option.Pointer())
42 | //style := widgets.NewQStyle2()
43 |
44 | //style :=(*widgets.QApplication).Style();
45 | //w.Style().DrawControl(widgets.QStyle__CE_ItemViewItem, option, painter, nil)
46 | i.qApp.Style().DrawControl(widgets.QStyle__CE_ItemViewItem, option, painter, nil)
47 |
48 | // /* Draw using our rich text document. */
49 | painter.Translate3(float64(option.Rect().Left()), float64(option.Rect().Top()))
50 | // QRect clip(0, 0, options.rect.width(), options.rect.height());
51 | clip := core.NewQRectF4(0, 0, float64(option.Rect().Width()), float64(option.Rect().Height()))
52 | doc.DrawContents(painter, clip.QRectF_PTR())
53 |
54 | painter.Restore()
55 | }
56 |
57 | func (i Delegate) sizeHint(option *widgets.QStyleOptionViewItem, index *core.QModelIndex) *core.QSize {
58 | return core.NewQSize2(20,45);
59 | }
60 |
--------------------------------------------------------------------------------
/gui/maingui.go:
--------------------------------------------------------------------------------
1 | package gui
2 |
3 | import (
4 | "path/filepath"
5 | "fmt"
6 |
7 | "github.com/therecipe/qt/core"
8 | "github.com/therecipe/qt/gui"
9 | "github.com/therecipe/qt/widgets"
10 | "github.com/rhaidiz/broxy/core/project"
11 | bcore "github.com/rhaidiz/broxy/core"
12 | "github.com/rhaidiz/broxy/modules"
13 | "github.com/rhaidiz/broxy/util"
14 | )
15 |
16 | var broxyTitle = "Broxy (1.0.0-alpha.4)"
17 |
18 | // Broxygui is the main GUI made of tabs
19 | type Broxygui struct {
20 | widgets.QMainWindow
21 | bcore.MainGui
22 |
23 | _ func() `constructor:"setup"`
24 |
25 | tabWidget *widgets.QTabWidget
26 | treeWidget *widgets.QTreeWidget
27 |
28 | settingsMapping map[string]widgets.QWidget_ITF
29 | modulesTreeItem *widgets.QTreeWidgetItem
30 | current string
31 | hLayout *widgets.QHBoxLayout
32 | gzipDecodeCheckBox *widgets.QCheckBox
33 |
34 | s *bcore.Session
35 |
36 | history *History
37 | }
38 |
39 | func (g *Broxygui) setup() {
40 | // loading global config
41 | g.history = LoadHistory(util.GetSettingsDir())
42 |
43 | g.settingsMapping = make(map[string]widgets.QWidget_ITF)
44 | g.SetWindowTitle(broxyTitle)
45 | //g.SetMinimumSize(core.NewQSize2(523, 317))
46 |
47 | g.tabWidget = widgets.NewQTabWidget(nil)
48 | g.tabWidget.SetDocumentMode(true)
49 |
50 | g.SetCentralWidget(g.tabWidget)
51 | g.tabWidget.AddTab(g.settingsTab(), "Settings")
52 |
53 | g.createMenuBar()
54 | }
55 |
56 | func (g *Broxygui) createMenuBar(){
57 | menuBar := g.MenuBar().AddMenu2("&File")
58 |
59 | newAction := widgets.NewQAction2("New project", g)
60 | //saveAction := widgets.NewQAction2("Persist project", g)
61 | openAction := widgets.NewQAction2("Open project...", g)
62 |
63 | menuBar.AddActions([]*widgets.QAction{})
64 | menuBar.AddActions([]*widgets.QAction{newAction, openAction})
65 |
66 | newAction.SetShortcuts2(gui.QKeySequence__New)
67 | //saveAction.SetShortcuts2(gui.QKeySequence__SaveAs)
68 | openAction.SetShortcuts2(gui.QKeySequence__Open)
69 |
70 | newAction.ConnectTriggered(g.newProjectAction)
71 | //saveAction.ConnectTriggered(g.saveProjectAction)
72 | openAction.ConnectTriggered(g.openProjectAction)
73 |
74 | }
75 |
76 | func (g *Broxygui) openProjectAction(b bool){
77 | var fileDialog = widgets.NewQFileDialog2(g, "Open project", "", "")
78 | fileDialog.SetFileMode(widgets.QFileDialog__DirectoryOnly);
79 | fileDialog.SetOption(widgets.QFileDialog__ShowDirsOnly, false);
80 | if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
81 | return
82 | }
83 | var fn = fileDialog.SelectedFiles()[0]
84 | dir, file := filepath.Split(fn)
85 | c, err := project.OpenPersistentProject(file,dir)
86 | if err != nil{
87 | g.ShowErrorMessage(fmt.Sprintf("Error while opening project: %s",err))
88 | return
89 | }
90 |
91 | gui := NewBroxygui(nil,0)
92 | s := bcore.NewSession(g.s.Settings, c, gui)
93 | //Load All modules
94 | defer func() {
95 | if r := recover(); r != nil {
96 | m := fmt.Sprintf("Error while opening project:\n%s", r)
97 | s.ShowErrorMessage(m)
98 | }
99 | }()
100 | modules.LoadModules(s)
101 |
102 | g.history.Add(&project.Project{file,dir})
103 | gui.Show()
104 | g.Close()
105 | }
106 |
107 | func (g *Broxygui) saveProjectAction(b bool){
108 | // ask the user where he should save the project
109 | var fileDialog = widgets.NewQFileDialog2(g, "Save as...", "", "")
110 | fileDialog.SetAcceptMode(widgets.QFileDialog__AcceptSave)
111 | if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
112 | return
113 | }
114 | var fn = fileDialog.SelectedFiles()[0]
115 | dir, file := filepath.Split(fn)
116 | err := g.s.PersistentProject.Persist(file,dir)
117 | if err != nil {
118 | g.ShowErrorMessage(fmt.Sprintf("Error while persisting project: %s",err))
119 | return
120 | }
121 |
122 | projectTitle := g.s.PersistentProject.GetTitle()
123 | windowTitle := fmt.Sprintf("%s [%s]", broxyTitle, projectTitle)
124 | g.SetWindowTitle(windowTitle)
125 | g.history.Add(&project.Project{file,dir})
126 | }
127 |
128 |
129 | func (g *Broxygui) newProjectAction(b bool){
130 | var fileDialog = widgets.NewQFileDialog2(g, "Create new project", "", "")
131 | fileDialog.SetAcceptMode(widgets.QFileDialog__AcceptSave)
132 | if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
133 | return
134 | }
135 | var fn = fileDialog.SelectedFiles()[0]
136 | dir, file := filepath.Split(fn)
137 |
138 | c, err := project.NewPersistentProject(file,dir)
139 |
140 | if err != nil {
141 | g.ShowErrorMessage(fmt.Sprintf("Error while creating project: %s",err))
142 | return
143 | }
144 |
145 | // temporary, for now, everytime I create a new project I save it in the history
146 | gui := NewBroxygui(nil,0)
147 | s := bcore.NewSession(g.s.Settings, c, gui)
148 | //Load All modules
149 | modules.LoadModules(s)
150 |
151 | //g.history.Add(&project.Project{"NewProject",p})
152 | gui.Show()
153 | g.Close()
154 | }
155 |
156 | func (g *Broxygui) InitWith(s *bcore.Session) {
157 | g.s = s
158 | projectTitle := s.PersistentProject.GetTitle()
159 | windowTitle := fmt.Sprintf("%s [%s]", broxyTitle, projectTitle)
160 | g.SetWindowTitle(windowTitle)
161 | //if s.GlobalSettings.GZipDecode {
162 | // g.gzipDecodeCheckBox.SetChecked(true)
163 | //}else{
164 | // g.gzipDecodeCheckBox.SetChecked(false)
165 | //}
166 |
167 | }
168 |
169 | //AddGuiModule adds a new module to the main GUI
170 | func (g *Broxygui) AddGuiModule(m bcore.GuiModule) {
171 | g.tabWidget.InsertTab(0,m.GetModuleGui().(widgets.QWidget_ITF), m.Title())
172 | g.tabWidget.SetCurrentIndex(0)
173 | if m.GetSettings() != nil {
174 | g.settingsMapping[m.Title()] = m.GetSettings().(widgets.QWidget_ITF)
175 | item := widgets.NewQTreeWidgetItem(0)
176 | item.SetText(0,m.Title())
177 | g.modulesTreeItem.AddChild(item)
178 | g.modulesTreeItem.SetExpanded(true)
179 | }
180 | }
181 |
182 | //ShowErrorMessage shows a critical message box
183 | func (g *Broxygui) ShowErrorMessage(message string) {
184 | widgets.QMessageBox_Critical(nil, "OK", message, widgets.QMessageBox__Ok, widgets.QMessageBox__Ok)
185 | }
186 |
187 | func (g *Broxygui) settingsTab() widgets.QWidget_ITF{
188 | widget := widgets.NewQWidget(nil, 0)
189 | g.hLayout = widgets.NewQHBoxLayout()
190 | widget.SetLayout(g.hLayout)
191 |
192 | g.treeWidget = widgets.NewQTreeWidget(nil)
193 | g.treeWidget.ConnectItemClicked(g.itemClicked)
194 | g.treeWidget.SetHeaderHidden(true)
195 | g.hLayout.AddWidget(g.treeWidget,0 ,0)
196 |
197 | //item := widgets.NewQTreeWidgetItem(0)
198 | //item.SetText(0,"Global Settings")
199 |
200 | g.modulesTreeItem = widgets.NewQTreeWidgetItem(0)
201 | g.modulesTreeItem.SetText(0, "Modules")
202 |
203 | //g.treeWidget.AddTopLevelItem(item)
204 | g.treeWidget.AddTopLevelItem(g.modulesTreeItem)
205 | //g.treeWidget.SetSizePolicy(widgets.QSizePolicy__Fixed)
206 | g.treeWidget.SetFixedWidth(200)
207 |
208 | g.treeWidget.SetCurrentItem(g.modulesTreeItem)
209 | global := g.emptySettings()
210 | g.hLayout.AddWidget(global,0 ,0)
211 |
212 | g.current = "Modules"
213 | g.settingsMapping["Modules"] = global
214 | //g.settingsMapping["Modules"] = g.emptySettings()
215 |
216 | return widget
217 | }
218 |
219 |
220 |
221 | func (g *Broxygui) globalSettings() widgets.QWidget_ITF {
222 | widget := widgets.NewQWidget(nil, 0)
223 | return widget
224 | hLayout := widgets.NewQVBoxLayout()
225 | widget.SetLayout(hLayout)
226 |
227 | label := widgets.NewQLabel(nil, 0)
228 | font := gui.NewQFont()
229 | font.SetPointSize(20)
230 | font.SetBold(true)
231 | font.SetWeight(75)
232 | label.SetFont(font)
233 | label.SetObjectName("label")
234 | label.SetText("Global Settings")
235 |
236 | g.gzipDecodeCheckBox = widgets.NewQCheckBox(nil)
237 | g.gzipDecodeCheckBox.SetText("Decode GZIP Responses")
238 | g.gzipDecodeCheckBox.ConnectClicked(g.gzipDecodeCheckBoxClicked)
239 |
240 | spacerItem := widgets.NewQSpacerItem(20, 40, widgets.QSizePolicy__Minimum, widgets.QSizePolicy__Expanding)
241 |
242 | hLayout.AddWidget(label, 0, core.Qt__AlignLeft)
243 | hLayout.AddWidget(g.gzipDecodeCheckBox, 0, core.Qt__AlignLeft)
244 | hLayout.AddItem(spacerItem)
245 |
246 | return widget
247 | }
248 |
249 | func ( g *Broxygui) gzipDecodeCheckBoxClicked(b bool){
250 | g.s.GlobalSettings.GZipDecode = g.gzipDecodeCheckBox.IsChecked()
251 | g.s.PersistentProject.SaveSettings("project",g.s.GlobalSettings)
252 | }
253 |
254 | // used for testing
255 | func (g *Broxygui) emptySettings() widgets.QWidget_ITF {
256 | widget := widgets.NewQWidget(nil, 0)
257 | //hLayout := widgets.NewQHBoxLayout()
258 | //widget.SetLayout(hLayout)
259 | //hLayout.AddWidget(widgets.NewQPushButton2("AAAAAA", nil),0,0)
260 | return widget
261 | }
262 |
263 | func (g *Broxygui) itemClicked(item *widgets.QTreeWidgetItem, column int){
264 | if _, ok := g.settingsMapping[item.Text(0)]; ok {
265 | g.hLayout.ReplaceWidget(g.settingsMapping[g.current], g.settingsMapping[item.Text(0)], core.Qt__FindChildrenRecursively)
266 | g.settingsMapping[g.current].QWidget_PTR().SetVisible(false)
267 | g.settingsMapping[item.Text(0)].QWidget_PTR().SetVisible(true)
268 | g.current = item.Text(0)
269 | }
270 | }
271 |
--------------------------------------------------------------------------------
/gui/projectgui.go:
--------------------------------------------------------------------------------
1 | package gui
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | bcore "github.com/rhaidiz/broxy/core"
7 | "github.com/rhaidiz/broxy/modules"
8 | "github.com/rhaidiz/broxy/util"
9 | "github.com/rhaidiz/broxy/core/project"
10 | "github.com/therecipe/qt/core"
11 | "github.com/therecipe/qt/gui"
12 | "github.com/therecipe/qt/widgets"
13 | //"time"
14 | "path/filepath"
15 | )
16 |
17 | // Projectgui shows a project history and allows to create a new project or load an existing one
18 | type Projectgui struct {
19 | widgets.QMainWindow
20 | _ func() `constructor:"setup"`
21 |
22 | projectsListWidget *widgets.QListWidget
23 |
24 | newProjectButton *widgets.QPushButton
25 | loadProjectButton *widgets.QPushButton
26 | openProjectButton *widgets.QPushButton
27 | qApp *widgets.QApplication
28 | config *bcore.BroxySettings
29 | history *History
30 | contextMenu *widgets.QMenu
31 |
32 |
33 | }
34 |
35 | func (g *Projectgui) setup() {
36 |
37 | }
38 |
39 | // InitWith initializes Projectgui with a given history, configuration and QApplication
40 | func (g *Projectgui) InitWith(qApp *widgets.QApplication) {
41 | g.qApp = qApp
42 | g.init()
43 | }
44 |
45 | func (g *Projectgui) init(){
46 |
47 | g.config = bcore.LoadGlobalSettings(util.GetSettingsDir())
48 | g.history = LoadHistory(util.GetSettingsDir())
49 |
50 | g.SetWindowTitle("Welcome to Broxy")
51 | g.Resize(core.NewQSize2(488, 372))
52 | g.SetMinimumSize(core.NewQSize2(488, 372))
53 | g.SetMaximumSize(core.NewQSize2(488, 372))
54 |
55 | mainWidget := widgets.NewQWidget(nil, 0)
56 | hLayout := widgets.NewQHBoxLayout()
57 | hLayout.SetContentsMargins(0, 0, 12, 0)
58 | mainWidget.SetLayout(hLayout)
59 | g.SetCentralWidget(mainWidget)
60 | g.projectsListWidget = widgets.NewQListWidget(nil)
61 |
62 | delegate := InitDelegate(g.qApp)
63 | g.projectsListWidget.SetItemDelegate(delegate)
64 | g.projectsListWidget.ConnectItemDoubleClicked(g.itemDoubleClicked)
65 | g.projectsListWidget.SetContextMenuPolicy(core.Qt__CustomContextMenu)
66 | g.projectsListWidget.ConnectCustomContextMenuRequested(g.customContextMenuRequested)
67 |
68 | font := gui.NewQFont2("Monospace", 11, int(gui.QFont__Normal), false)
69 | fontMetrics := gui.NewQFontMetricsF(font)
70 |
71 | p := ""
72 | t := ""
73 | for _,h := range g.history.H {
74 | //println("first instruction in loop")
75 | p = h.Path
76 | // this ElidedText is performing very poorly, I might implement something myself
77 | localElidedText := fontMetrics.ElidedText(p, core.Qt__ElideMiddle, 230, 0)
78 | t = fmt.Sprintf("%s
", h.Title)
79 | g.projectsListWidget.AddItem(t + localElidedText)
80 | }
81 |
82 |
83 | hLayout.AddWidget(g.projectsListWidget, 0, 0)
84 |
85 | rightWidget := widgets.NewQWidget(nil, 0)
86 | vLayout := widgets.NewQVBoxLayout()
87 | rightWidget.SetLayout(vLayout)
88 |
89 | hLayout.AddWidget(rightWidget, 0, 0)
90 |
91 | g.newProjectButton = widgets.NewQPushButton2("New Project", nil)
92 | g.newProjectButton.ConnectClicked(g.newProject)
93 |
94 | //g.loadProjectButton = widgets.NewQPushButton2("Load Project", nil)
95 | g.openProjectButton = widgets.NewQPushButton2("Open Existing Project", nil)
96 | g.openProjectButton.ConnectClicked(g.openProject)
97 |
98 | spacerItem := widgets.NewQSpacerItem(40, 20, widgets.QSizePolicy__Minimum, widgets.QSizePolicy__Expanding)
99 |
100 | vLayout.AddItem(spacerItem)
101 | vLayout.AddWidget(g.newProjectButton, 0, 0)
102 | //vLayout.AddWidget(g.loadProjectButton, 0, 0)
103 | vLayout.AddWidget(g.openProjectButton, 0, 0)
104 | vLayout.AddItem(spacerItem)
105 | }
106 |
107 | func (g *Projectgui) customContextMenuRequested(p *core.QPoint) {
108 | if g.contextMenu == nil {
109 | g.contextMenu = widgets.NewQMenu(nil)
110 | remove := g.contextMenu.AddAction("Remove")
111 | remove.ConnectTriggered(func(b bool) {
112 | r := g.projectsListWidget.CurrentRow()
113 | project := g.history.H[r]
114 | g.history.Remove(project)
115 | g.projectsListWidget.TakeItem(r)
116 | // remove from file-system
117 | path := filepath.Join(project.Path, project.Title)
118 | os.RemoveAll(path)
119 | })
120 | }
121 | g.contextMenu.Exec2(g.projectsListWidget.MapToGlobal(p), nil)
122 | }
123 |
124 | func (g *Projectgui) itemDoubleClicked(item *widgets.QListWidgetItem){
125 | r := g.projectsListWidget.CurrentRow()
126 | path := g.history.H[r].Path
127 | title := g.history.H[r].Title
128 | c, err := project.OpenPersistentProject(title,path)
129 | if err != nil {
130 | g.showErrorMessage(fmt.Sprintf("Error while opening project: %s",err))
131 | return
132 | }
133 | gui := NewBroxygui(nil,0)
134 | s := bcore.NewSession(g.config, c, gui)
135 | //Load All modules
136 | modules.LoadModules(s)
137 |
138 | gui.Show()
139 | g.Close()
140 | }
141 |
142 | func (g *Projectgui) newProject(b bool) {
143 |
144 | var fileDialog = widgets.NewQFileDialog2(g, "Create new project", "", "")
145 | fileDialog.SetAcceptMode(widgets.QFileDialog__AcceptSave)
146 | if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
147 | return
148 | }
149 | var fn = fileDialog.SelectedFiles()[0]
150 | dir, file := filepath.Split(fn)
151 |
152 | c, err := project.NewPersistentProject(file,dir)
153 | if err != nil {
154 | g.showErrorMessage(fmt.Sprintf("Error while creating a new project: %s",err))
155 | }
156 |
157 | g.history.Add(&project.Project{file,dir})
158 | gui := NewBroxygui(nil,0)
159 | s := bcore.NewSession(g.config, c, gui)
160 | //Load All modules
161 | modules.LoadModules(s)
162 |
163 | gui.Show()
164 | g.Close()
165 | }
166 |
167 | func (g *Projectgui) openProject(b bool) {
168 | var fileDialog = widgets.NewQFileDialog2(g, "Open project", "", "")
169 | fileDialog.SetFileMode(widgets.QFileDialog__DirectoryOnly);
170 | fileDialog.SetOption(widgets.QFileDialog__ShowDirsOnly, false);
171 | if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
172 | return
173 | }
174 | var fn = fileDialog.SelectedFiles()[0]
175 | dir, file := filepath.Split(fn)
176 | c, err := project.OpenPersistentProject(file,dir)
177 | if err != nil{
178 | g.showErrorMessage(fmt.Sprintf("Error while opening a new project: %s",err))
179 | return
180 | }
181 | gui := NewBroxygui(nil,0)
182 | s := bcore.NewSession(g.config, c, gui)
183 | //Load All modules
184 | defer func() {
185 | if r := recover(); r != nil {
186 | m := fmt.Sprintf("Error while opening project\n%s", r)
187 | s.ShowErrorMessage(m)
188 | }
189 | }()
190 | modules.LoadModules(s)
191 |
192 | g.history.Add(&project.Project{file,dir})
193 |
194 | gui.Show()
195 | g.Close()
196 | }
197 |
198 | //ShowErrorMessage shows a critical message box
199 | func (g *Projectgui) showErrorMessage(message string) {
200 | widgets.QMessageBox_Critical(nil, "OK", message, widgets.QMessageBox__Ok, widgets.QMessageBox__Ok)
201 | }
202 |
--------------------------------------------------------------------------------
/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/icon.ico
--------------------------------------------------------------------------------
/icon.rc:
--------------------------------------------------------------------------------
1 | IDI_ICON1 ICON DISCARDABLE "icon.ico"
--------------------------------------------------------------------------------
/icon_windows.syso:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/icon_windows.syso
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "os"
5 |
6 | "github.com/rhaidiz/broxy/gui"
7 | "github.com/therecipe/qt/widgets"
8 | )
9 |
10 | func main() {
11 |
12 | qa := widgets.NewQApplication(len(os.Args), os.Args)
13 | prj := gui.NewProjectgui(nil, 0)
14 | prj.InitWith(qa)
15 |
16 | prj.Show()
17 |
18 | widgets.QApplication_Exec()
19 | }
20 |
--------------------------------------------------------------------------------
/media/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/media/icon.png
--------------------------------------------------------------------------------
/media/main.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/media/main.png
--------------------------------------------------------------------------------
/media/screen1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/media/screen1.png
--------------------------------------------------------------------------------
/media/screen2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rhaidiz/broxy/e9dc7d8d5be21cf8d21f55f0fc0f662168dac771/media/screen2.png
--------------------------------------------------------------------------------
/modules/coreproxy/coreproxy.go:
--------------------------------------------------------------------------------
1 | package coreproxy
2 |
3 | import (
4 | "context"
5 | "crypto/tls"
6 | "crypto/x509"
7 | "fmt"
8 | "net/http"
9 | "regexp"
10 |
11 | "github.com/elazarl/goproxy"
12 | "github.com/elazarl/goproxy/transport"
13 | "github.com/rhaidiz/broxy/core"
14 | )
15 |
16 | // Coreproxy represents the intercept proxy
17 | type Coreproxy struct {
18 | core.Module
19 |
20 | Sess *core.Session
21 |
22 | Address string
23 | Port int
24 | Proxyh *goproxy.ProxyHttpServer
25 | Req int
26 | Resp int
27 | Srv *http.Server
28 | OnReq func(*http.Request, *goproxy.ProxyCtx) (*http.Request, *http.Response)
29 | OnResp func(*http.Response, *goproxy.ProxyCtx) *http.Response
30 | status bool
31 | tr *transport.Transport
32 | }
33 |
34 | // NewCoreProxy creates a new intercept proxy
35 | func NewCoreProxy(s *core.Session) *Coreproxy {
36 | setCa(s.Settings.CACertificate, s.Settings.CAPrivateKey)
37 | p := &Coreproxy{
38 | Address: Stg.IP,
39 | Port: Stg.Port,
40 | Proxyh: goproxy.NewProxyHttpServer(),
41 | Req: 0,
42 | Resp: 0,
43 | Sess: s,
44 | status: false,
45 | tr: &transport.Transport{Proxy: transport.ProxyFromEnvironment, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
46 | }
47 |
48 | // this is the golang HTTP server with its handler
49 | p.Srv = &http.Server{
50 | Addr: fmt.Sprintf("%s:%d", p.Address, p.Port),
51 | Handler: p.Proxyh,
52 | }
53 |
54 | // enable always HTTPS mitm
55 | //p.Proxyh.OnRequest().HandleConnect(goproxy.AlwaysMitm)
56 |
57 | // set the default behavior onReq\Resp
58 | p.Proxyh.OnRequest().DoFunc(p.onReqDef)
59 | p.Proxyh.OnResponse().DoFunc(p.onRespDef)
60 |
61 | return p
62 | }
63 |
64 | // ChangeIPPort is used to change the ip and port of the current intercept proxy
65 | func (p *Coreproxy) ChangeIPPort(ip string, port int) error {
66 |
67 | ipReg := "^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))"
68 | portReg := "(6553[0-5]|655[0-2][0-9]|65[0-4][0-9][0-9]|6[0-4][0-9][0-9][0-9]|[1-5]?[0-9]?[0-9]?[0-9]?[0-9])?$"
69 |
70 | rIP := regexp.MustCompile(ipReg)
71 | rPort := regexp.MustCompile(portReg)
72 |
73 | if s := rIP.FindStringSubmatch(ip); s == nil {
74 | return fmt.Errorf("Not a valid ip %s", ip)
75 | }
76 |
77 | if s := rPort.FindStringSubmatch(string(port)); s == nil {
78 | return fmt.Errorf("Not a valid port %s", port)
79 | }
80 |
81 | p.Address = ip
82 | p.Port = port
83 |
84 | p.Srv = &http.Server{
85 | Addr: fmt.Sprintf("%s:%d", p.Address, p.Port),
86 | Handler: p.Proxyh,
87 | }
88 |
89 | return nil
90 | }
91 |
92 | // Name returns the name of the current module
93 | func (p *Coreproxy) Name() string {
94 | return "Proxy"
95 | }
96 |
97 | // Description returns the description of the current module
98 | func (p *Coreproxy) Description() string {
99 | return "The main core proxy module, the one that logs and sees everything"
100 | }
101 |
102 | // Status returns the status of the current module if any
103 | func (p *Coreproxy) Status() bool {
104 | return p.status
105 | }
106 |
107 | // Start bind the proxy for listening
108 | func (p *Coreproxy) Start() error {
109 | return p.Srv.ListenAndServe()
110 | }
111 |
112 | // Stop stops the proxy
113 | func (p *Coreproxy) Stop() error {
114 |
115 | return p.Srv.Shutdown(context.Background())
116 | }
117 |
118 | func (p *Coreproxy) onReqDef(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
119 | r1, rsp := p.OnReq(r, ctx)
120 | // ctx.RoundTripper = goproxy.RoundTripperFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (resp *http.Response, err error) {
121 | // ctx.UserData, resp, err = p.tr.DetailedRoundTrip(req)
122 | // return
123 | // })
124 | return r1, rsp
125 | }
126 |
127 | // Run when a response is received
128 | func (p *Coreproxy) onRespDef(r *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
129 | if r != nil {
130 | r = p.OnResp(r, ctx)
131 | }
132 |
133 | return r
134 | }
135 |
136 | func setCa(caCert, caKey []byte) error {
137 | goproxyCa, err := tls.X509KeyPair(caCert, caKey)
138 | if err != nil {
139 | return err
140 | }
141 | if goproxyCa.Leaf, err = x509.ParseCertificate(goproxyCa.Certificate[0]); err != nil {
142 | return err
143 | }
144 | goproxy.GoproxyCa = goproxyCa
145 | goproxy.OkConnect = &goproxy.ConnectAction{Action: goproxy.ConnectAccept, TLSConfig: core.TLSConfigFromCA(&goproxyCa)}
146 | goproxy.MitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: core.TLSConfigFromCA(&goproxyCa)}
147 | goproxy.HTTPMitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectHTTPMitm, TLSConfig: core.TLSConfigFromCA(&goproxyCa)}
148 | goproxy.RejectConnect = &goproxy.ConnectAction{Action: goproxy.ConnectReject, TLSConfig: core.TLSConfigFromCA(&goproxyCa)}
149 | return nil
150 | }
151 |
--------------------------------------------------------------------------------
/modules/coreproxy/coreproxy_controller.go:
--------------------------------------------------------------------------------
1 | package coreproxy
2 |
3 | import (
4 | "bytes"
5 | "github.com/rhaidiz/broxy/core/project/decoder"
6 | "fmt"
7 | "io/ioutil"
8 | "net"
9 | "net/http"
10 | "regexp"
11 | "strconv"
12 | "strings"
13 | "sync"
14 |
15 | "github.com/elazarl/goproxy"
16 | "github.com/rhaidiz/broxy/core"
17 | _ "github.com/rhaidiz/broxy/core/project"
18 | "github.com/rhaidiz/broxy/modules/coreproxy/model"
19 | "github.com/atotto/clipboard"
20 | )
21 |
22 | // Controller represents the controller for the main intercetp proxy
23 | type Controller struct {
24 | core.ControllerModule
25 | Module *Coreproxy
26 | Gui *Gui
27 | Sess *core.Session
28 | Filter *model.Filter
29 |
30 | isRunning bool
31 | model *model.SortFilterModel
32 | id int
33 | ignoreHTTPS bool
34 |
35 | forwardChan chan bool
36 | dropChan chan bool
37 | // will maintain the number of requests in queue
38 | requestsQueue int
39 | responsesQueue int
40 |
41 | dropped map[int64]bool
42 |
43 | // encoders
44 | requestEnc decoder.Encoder
45 | requestEditedEnc decoder.Encoder
46 | responseEnc decoder.Encoder
47 | responseEditedEnc decoder.Encoder
48 |
49 | // decoders
50 | requestDec decoder.Decoder
51 | requestEditedDec decoder.Decoder
52 | responseDec decoder.Decoder
53 | responseEditedDec decoder.Decoder
54 | }
55 |
56 | var mutex = &sync.Mutex{}
57 | var count int64
58 |
59 | // NewController creates a new controller for the core intercetp proxy
60 | func NewController(proxy *Coreproxy, proxygui *Gui, s *core.Session) *Controller {
61 | c := &Controller{
62 | Module: proxy,
63 | Gui: proxygui,
64 | Sess: s,
65 | isRunning: false,
66 | id: 0,
67 | ignoreHTTPS: false,
68 | forwardChan: make(chan bool),
69 | dropChan: make(chan bool),
70 | requestsQueue: 0,
71 | responsesQueue: 0,
72 | dropped: make(map[int64]bool),
73 | Filter: model.DefaultFilter,
74 | }
75 |
76 | // get the encoders
77 | var err error
78 | c.requestEnc, err = s.PersistentProject.FileEncoder2("requests")
79 | if err != nil {
80 | panic("Error while opening history!")
81 | }
82 | c.requestEditedEnc, err = s.PersistentProject.FileEncoder2("requests_edited")
83 | if err != nil {
84 | panic("Error while opening history!")
85 | }
86 | c.responseEnc, err = s.PersistentProject.FileEncoder2("response")
87 | if err != nil {
88 | panic("Error while opening history!")
89 | }
90 | c.responseEditedEnc, err = s.PersistentProject.FileEncoder2("response_edited")
91 | if err != nil {
92 | panic("Error while opening history!")
93 | }
94 |
95 | // get the decoders, which I only need to read the history the first time
96 | c.requestDec, err = s.PersistentProject.FileDecoder2("requests")
97 | if err != nil {
98 | panic("Error while opening history!")
99 | }
100 | c.requestEditedDec, err = s.PersistentProject.FileDecoder2("requests_edited")
101 | if err != nil {
102 | panic("Error while opening history!")
103 | }
104 | c.responseDec, err = s.PersistentProject.FileDecoder2("response")
105 | if err != nil {
106 | panic("Error while opening history!")
107 | }
108 | c.responseEditedDec, err = s.PersistentProject.FileDecoder2("response_edited")
109 | if err != nil {
110 | panic("Error while opening history!")
111 | }
112 |
113 | // load the history
114 | count = 1
115 | for {
116 | // load the requests
117 | var req model.Request
118 | var row model.Row
119 | if err := c.requestDec.Decode(&req); err != nil {
120 | break
121 | }
122 | row.ID = req.ID
123 | if req.ID > count{
124 | count = req.ID
125 | }
126 | row.Req = &req
127 | model.History = append(model.History, &row)
128 | model.HashMapHistory[row.ID] = len(model.History) - 1
129 | }
130 | for{
131 | // load edited requests
132 | var req model.Request
133 | if err := c.requestEditedDec.Decode(&req); err != nil {
134 | break
135 | }
136 | row := model.History[model.HashMapHistory[req.ID]]
137 | (*row).EditedReq = &req
138 | }
139 | for{
140 | // load the responses
141 | var resp model.Response
142 | if err := c.responseDec.Decode(&resp); err != nil {
143 | break
144 | }
145 | row := model.History[model.HashMapHistory[resp.ID]]
146 | (*row).Resp = &resp
147 | }
148 | for{
149 | // load edited responses
150 | var resp model.Response
151 | if err := c.responseEditedDec.Decode(&resp); err != nil {
152 | break
153 | }
154 | row := model.History[model.HashMapHistory[resp.ID]]
155 | (*row).EditedResp = &resp
156 | }
157 |
158 | //count = int64(len(model.History))
159 | // load settings and save settings
160 | c.Sess.PersistentProject.LoadSettings("coreproxy", Stg)
161 | c.Sess.PersistentProject.SaveSettings("coreproxy", Stg)
162 |
163 | c.Sess.PersistentProject.LoadSettings("filters", c.Filter)
164 | c.Sess.PersistentProject.SaveSettings("filters", c.Filter)
165 |
166 |
167 | c.model = model.NewSortFilterModel(nil)
168 | //c.model.Custom.Refresh()
169 |
170 | c.Module.OnReq = c.onReq
171 | c.Module.OnResp = c.onResp
172 | c.Module.Proxyh.OnRequest().HandleConnect(goproxy.FuncHttpsHandler(c.broxyConnectHandle))
173 | c.Gui.SetTableModel(c.model)
174 |
175 | // UI events
176 | c.Gui.RowClicked = c.selectRow
177 | c.Gui.Forward = c.forward
178 | c.Gui.Drop = c.drop
179 | c.Gui.ApplyFilters = c.applyFilter
180 | c.Gui.ResetFilters = c.resetFilter
181 | c.Gui.SaveCAClicked = c.downloadCAClicked
182 | c.Gui.RightItemClicked = c.rightItemClicked
183 |
184 | // UI settings events
185 | c.Gui.StartProxy = c.startProxy
186 | c.Gui.Toggle = c.interceptorToggle
187 | c.Gui.CheckReqInterception = c.checkReqInterception
188 | c.Gui.CheckRespInterception = c.checkRespInterception
189 | c.Gui.CheckIgnoreHTTPS = c.ignoreHTTPSToggle
190 |
191 | // UI init
192 | c.Gui.ControllerInit = c.initUIContent
193 | return c
194 | }
195 |
196 | // GetGui returns the Gui of the current controller
197 | func (c *Controller) GetGui() core.GuiModule {
198 | return c.Gui
199 | }
200 |
201 | // GetModule returns the module of the current controller
202 | func (c *Controller) GetModule() core.Module {
203 | return c.Module
204 | }
205 |
206 | // ExecCommand execs commands submitted by other modules
207 | func (c *Controller) ExecCommand(m string, args ...interface{}) {
208 |
209 | }
210 |
211 | func (c *Controller) initUIContent() {
212 | //c.setDefaultFilter()
213 | c.setFilter(c.Filter)
214 | c.Gui.ListenerLineEdit.SetText(fmt.Sprintf("%s:%d", Stg.IP, Stg.Port))
215 | if Stg.Interceptor {
216 | c.Gui.InterceptorToggleButton.SetChecked(true)
217 | }
218 | if Stg.ReqIntercept {
219 | c.Gui.ReqInterceptCheckBox.SetChecked(true)
220 | }
221 | if Stg.RespIntercept {
222 | c.Gui.RespInterceptCheckBox.SetChecked(true)
223 | }
224 | }
225 |
226 | func (c *Controller) rightItemClicked(s string, r int) {
227 | req, _, _, _ := c.model.Custom.GetReqResp(c.model.GetRowId(r))
228 | // shouldn't this be a switch?
229 | if s == CopyURLLabel {
230 | clipboard.WriteAll(fmt.Sprintf("%s://%s%s", req.URL.Scheme, req.Host, req.URL.Path))
231 | } else if s == CopyBaseURLLabel {
232 | clipboard.WriteAll(fmt.Sprintf("%s://%s", req.URL.Scheme, req.Host))
233 | } else if s == RepeatLabel {
234 | // FIXME: I **really** don't like this
235 | c.Sess.Exec("Repeater", "send-to", req)
236 | } else if s == ClearHistoryLabel {
237 | c.model.Custom.ClearHistory()
238 | c.id = 0
239 | } else if s == AddToScopeLabel {
240 | c.Filter.Scope = append(c.Filter.Scope, req.Host)
241 | c.setFilter(c.Filter)
242 | }
243 | }
244 |
245 | func (c *Controller) downloadCAClicked(b bool) {
246 | c.Gui.FileSaveAs(string(c.Sess.Settings.CACertificate))
247 | }
248 |
249 | func (c *Controller) checkReqInterception(b bool) {
250 | Stg.ReqIntercept = c.Gui.ReqInterceptCheckBox.IsChecked()
251 | c.saveSettings()
252 | }
253 |
254 | func (c *Controller) checkRespInterception(b bool) {
255 | Stg.RespIntercept = c.Gui.RespInterceptCheckBox.IsChecked()
256 | c.saveSettings()
257 | }
258 |
259 | func (c *Controller) setFilter(f *model.Filter){
260 | c.Gui.TextSearchLineEdit.SetText(f.Search)
261 | for _, s := range f.StatusCode {
262 | switch s {
263 | case 100:
264 | c.Gui.S100CheckBox.SetChecked(true)
265 | break
266 | case 200:
267 | c.Gui.S200CheckBox.SetChecked(true)
268 | break
269 | case 300:
270 | c.Gui.S300CheckBox.SetChecked(true)
271 | break
272 | case 400:
273 | c.Gui.S400CheckBox.SetChecked(true)
274 | break
275 | case 500:
276 | c.Gui.S500CheckBox.SetChecked(true)
277 | break
278 | }
279 | }
280 | if f.Show {
281 | c.Gui.ShowOnlyCheckBox.SetChecked(true)
282 | }
283 | if f.Hide {
284 | c.Gui.HideOnlyCheckBox.SetChecked(true)
285 | }
286 | if f.ScopeOnly {
287 | c.Gui.ShowScopeOnlyCheckBox.SetChecked(true)
288 | }
289 |
290 | showExt := strings.Join(f.ShowExt, ", ")
291 | c.Gui.ShowExtensionLineEdit.SetText(showExt)
292 |
293 | hideExt := strings.Join(f.HideExt, ", ")
294 | c.Gui.HideExtensionLineEdit.SetText(hideExt)
295 |
296 | scope := strings.Join(f.Scope, ", ")
297 | c.Gui.ScopeLineEdit.SetText(scope)
298 |
299 | c.applyFilter(true)
300 | }
301 |
302 | // Defaut history filters
303 | func (c *Controller) setDefaultFilter() {
304 | c.Gui.TextSearchLineEdit.SetText("")
305 | c.Gui.S100CheckBox.SetChecked(true)
306 | c.Gui.S200CheckBox.SetChecked(true)
307 | c.Gui.S300CheckBox.SetChecked(true)
308 | c.Gui.S400CheckBox.SetChecked(true)
309 | c.Gui.S500CheckBox.SetChecked(true)
310 | c.Gui.ShowOnlyCheckBox.SetChecked(false)
311 | c.Gui.HideOnlyCheckBox.SetChecked(true)
312 | c.Gui.ShowExtensionLineEdit.SetText("asp, aspx, jsp, php, html, htm")
313 | c.Gui.HideExtensionLineEdit.SetText("png, jpg, css, woff2, ico")
314 | c.applyFilter(true)
315 | }
316 |
317 | func (c *Controller) applyFilter(b bool) {
318 | c.Filter.Search = c.Gui.TextSearchLineEdit.DisplayText()
319 | var status []int
320 | if c.Gui.S100CheckBox.IsChecked() {
321 | status = append(status, 100)
322 | }
323 | if c.Gui.S200CheckBox.IsChecked() {
324 | status = append(status, 200)
325 | }
326 | if c.Gui.S300CheckBox.IsChecked() {
327 | status = append(status, 300)
328 | }
329 | if c.Gui.S400CheckBox.IsChecked() {
330 | status = append(status, 400)
331 | }
332 | if c.Gui.S500CheckBox.IsChecked() {
333 | status = append(status, 500)
334 | }
335 | // this also looks bad, creating a new status each time and replacing it ... bleah ...
336 | //IMP: make me pretier
337 | c.Filter.StatusCode = status
338 | var showExt []string
339 | c.Filter.Show = c.Gui.ShowOnlyCheckBox.IsChecked()
340 | for _, e := range strings.Split(strings.Replace(c.Gui.ShowExtensionLineEdit.DisplayText(), " ", "", -1), ",") {
341 | if len(e) > 0 {
342 | //c.Filter.ShowExt[e] = true
343 | showExt = append(showExt, e)
344 | }
345 | }
346 | c.Filter.ShowExt = showExt
347 | //c.Filter.HideExt = make(map[string]bool)
348 | var hideExt []string
349 | c.Filter.Hide = c.Gui.HideOnlyCheckBox.IsChecked()
350 | for _, e := range strings.Split(strings.Replace(c.Gui.HideExtensionLineEdit.DisplayText(), " ", "", -1), ",") {
351 | if len(e) > 0{
352 | //c.Filter.HideExt[e] = true
353 | hideExt = append(hideExt, e)
354 | }
355 | }
356 | c.Filter.HideExt = hideExt
357 |
358 | // scope
359 | var scope []string
360 | c.Filter.ScopeOnly = c.Gui.ShowScopeOnlyCheckBox.IsChecked()
361 | for _, e := range strings.Split(strings.Replace(c.Gui.ScopeLineEdit.DisplayText(), " ", "", -1), ",") {
362 | //c.Filter.HideExt[e] = true
363 | if len(e) > 0{
364 | scope = append(scope, e)
365 | }
366 | }
367 | c.Filter.Scope = scope
368 |
369 | c.model.SetFilter(c.Filter)
370 | c.Sess.PersistentProject.SaveSettings("filters", c.Filter)
371 | }
372 |
373 | func (c *Controller) resetFilter(b bool) {
374 | c.setDefaultFilter()
375 | }
376 |
377 | func (c *Controller) selectRow(r int) {
378 | c.Gui.HideAllTabs()
379 | rowId := c.model.GetRowId(r)
380 | req, editedReq, resp, editedResp := c.model.Custom.GetReqResp(rowId)
381 | if req != nil {
382 | c.Gui.ShowReqTab(req.ToString())
383 | }
384 | if editedReq != nil {
385 | c.Gui.ShowEditedReqTab(editedReq.ToString())
386 | }
387 | if resp != nil {
388 | c.Gui.ShowRespTab(resp.ToString())
389 | }
390 | if editedResp != nil {
391 | c.Gui.ShowEditedRespTab(editedResp.ToString())
392 | }
393 | }
394 |
395 | func (c *Controller) startProxy(b bool) {
396 |
397 | if !c.isRunning {
398 | // Start and stop the proxy
399 | IPPortReg := "^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)):(6553[0-5]|655[0-2][0-9]|65[0-4][0-9][0-9]|6[0-4][0-9][0-9][0-9]|[1-5]?[0-9]?[0-9]?[0-9]?[0-9])?$"
400 |
401 | r := regexp.MustCompile(IPPortReg)
402 |
403 | if s := r.FindStringSubmatch(c.Gui.ListenerLineEdit.DisplayText()); s != nil {
404 | p, _ := strconv.Atoi(s[2])
405 | if e := c.Module.ChangeIPPort(s[1], p); e == nil {
406 | // if I can change ip and port, change it also in the config struct
407 | Stg.IP = s[1]
408 | Stg.Port = p
409 | go func() {
410 | c.Gui.StartStopButton.SetText("Stop")
411 | c.isRunning = true
412 | c.Sess.Info(c.Module.Name(), "Starting proxy ...")
413 | if e := c.Module.Start(); e != nil && e != http.ErrServerClosed {
414 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("Error starting the proxy %s\n", e))
415 | c.isRunning = false
416 | c.Gui.StartStopButton.SetText("Start")
417 | }
418 | }()
419 | } else {
420 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("Error starting the proxy %s\n", e))
421 | }
422 | } else {
423 | c.Sess.Err(c.Module.Name(), "Wrong input")
424 | }
425 | } else {
426 | if Stg.Interceptor {
427 | c.interceptorToggle(false)
428 | }
429 | c.Module.Stop()
430 | c.isRunning = false
431 | c.Sess.Info(c.Module.Name(), "Stopping proxy.")
432 | c.Gui.StartStopButton.SetText("Start")
433 | }
434 | c.saveSettings()
435 | }
436 |
437 | // Executed when a response arrives
438 | func (c *Controller) onResp(r *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
439 |
440 | httpItem := model.NewHTTPItem(nil)
441 |
442 | var bodyBytes []byte
443 | if r != nil {
444 | bodyBytes, _ = ioutil.ReadAll(r.Body)
445 | // Restore the io.ReadCloser to its original state
446 | r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
447 | }
448 | httpItem.Resp = &model.Response{
449 | ID: count + ctx.Session,
450 | Status: r.Status,
451 | StatusCode: r.StatusCode,
452 | Body: bodyBytes,
453 | Proto: r.Proto,
454 | ContentLength: int64(len(bodyBytes)),
455 | Headers: cloneHeaders(r.Header),
456 | }
457 |
458 | go func(){ c.responseEnc.Encode(httpItem.Resp) }()
459 | c.model.Custom.AddResponse(httpItem.Resp, count+ctx.Session)
460 | // activate interceptor
461 | _, dropped := c.dropped[ctx.Session]
462 | if Stg.Interceptor && Stg.RespIntercept && !dropped {
463 | // if the response is nil, it means the interceptor did not change the response
464 |
465 | r.ContentLength = int64(len(bodyBytes))
466 | editedResp := c.interceptorResponseActions(ctx.Req, r)
467 | // the response was edited
468 | if editedResp != nil {
469 | var editedBodyBytes []byte
470 | editedBodyBytes, _ = ioutil.ReadAll(editedResp.Body)
471 | editedResp.Body = ioutil.NopCloser(bytes.NewBuffer(editedBodyBytes))
472 | httpItem.EditedResp = &model.Response{
473 | ID: count + ctx.Session,
474 | Status: editedResp.Status,
475 | StatusCode: editedResp.StatusCode,
476 | Proto: editedResp.Proto,
477 | Body: editedBodyBytes,
478 | ContentLength: int64(len(editedBodyBytes)),
479 | Headers: cloneHeaders(editedResp.Header),
480 | }
481 | r = editedResp
482 | go func(){ c.responseEditedEnc.Encode(httpItem.EditedResp) }()
483 | c.model.Custom.AddEditedResponse(httpItem.EditedResp, count+ctx.Session)
484 | }
485 |
486 | }
487 | return r
488 | }
489 |
490 | // Executed when a request arrives
491 | func (c *Controller) onReq(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
492 |
493 |
494 | var resp *http.Response
495 | var bodyBytes []byte
496 | if r != nil {
497 | bodyBytes, _ = ioutil.ReadAll(r.Body)
498 | // Restore the io.ReadCloser to its original state
499 | r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
500 | }
501 | httpItem := model.NewHTTPItem(nil)
502 | c.id = c.id + 1
503 | httpItem.ID = c.id
504 |
505 | re := regexp.MustCompile(`\.(\w*)($|\?|\#)`)
506 | matches := re.FindStringSubmatch(r.URL.Path)
507 | ext := ""
508 | if len(matches) >= 1 {
509 | ext = matches[1]
510 | }
511 | params := false
512 | if len(r.URL.RawQuery) > 0 || len(bodyBytes) > 0 {
513 | params = true
514 | }
515 | ips, err := net.LookupHost(r.Host)
516 | var ip string
517 | if err != nil {
518 | ip = "Unknown host"
519 | }else{
520 | ip = ips[0]
521 | }
522 | // this is the original request, save it for the history
523 | httpItem.Req = &model.Request{
524 | ID: count + ctx.Session,
525 | URL: r.URL,
526 | Method: r.Method,
527 | Body: bodyBytes,
528 | Host: r.Host,
529 | ContentLength: r.ContentLength,
530 | Headers: cloneHeaders(r.Header),
531 | Proto: r.Proto,
532 | Extension: ext,
533 | Params: params,
534 | IP: ip,
535 | }
536 |
537 | go func(){ c.requestEnc.Encode(httpItem.Req) }()
538 | c.model.Custom.AddRequest(httpItem.Req, count+ctx.Session)
539 |
540 | // activate interceptor
541 | if Stg.Interceptor && Stg.ReqIntercept {
542 |
543 | editedReq, editedResp := c.interceptorRequestActions(r, nil, ctx)
544 |
545 | if editedReq != nil {
546 | var editedBodyBytes []byte
547 | editedBodyBytes, _ = ioutil.ReadAll(editedReq.Body)
548 | editedReq.Body = ioutil.NopCloser(bytes.NewBuffer(editedBodyBytes))
549 |
550 | re := regexp.MustCompile(`\.(\w*)($|\?|\#)`)
551 | matches := re.FindStringSubmatch(r.URL.Path)
552 | ext := ""
553 | if len(matches) >= 1 {
554 | ext = matches[1]
555 | }
556 |
557 | httpItem.EditedReq = &model.Request{
558 | ID: count + ctx.Session,
559 | URL: editedReq.URL,
560 | Method: editedReq.Method,
561 | Body: editedBodyBytes,
562 | Host: editedReq.Host,
563 | ContentLength: editedReq.ContentLength,
564 | Headers: cloneHeaders(editedReq.Header),
565 | Proto: editedReq.Proto,
566 | Extension: ext,
567 | }
568 | r = editedReq
569 | resp = editedResp
570 | go func(){ c.requestEditedEnc.Encode(httpItem.EditedReq) }()
571 | c.model.Custom.AddEditedRequest(httpItem.EditedReq, count+ctx.Session)
572 | }
573 |
574 | }
575 | return r, resp
576 | }
577 |
578 | func (c *Controller) ignoreHTTPSToggle(b bool) {
579 | c.ignoreHTTPS = !c.ignoreHTTPS
580 | }
581 |
582 | func (c *Controller) broxyConnectHandle(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
583 | if c.ignoreHTTPS {
584 | return goproxy.OkConnect, host
585 | }
586 | return goproxy.MitmConnect, host
587 | }
588 |
589 | func (c *Controller) saveSettings(){
590 | c.Sess.PersistentProject.SaveSettings("coreproxy", Stg)
591 | }
592 |
--------------------------------------------------------------------------------
/modules/coreproxy/coreproxy_gui.go:
--------------------------------------------------------------------------------
1 | package coreproxy
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "time"
7 |
8 | "github.com/rhaidiz/broxy/core"
9 | "github.com/rhaidiz/broxy/modules/coreproxy/model"
10 | qtcore "github.com/therecipe/qt/core"
11 | "github.com/therecipe/qt/gui"
12 | "github.com/therecipe/qt/quick"
13 | "github.com/therecipe/qt/widgets"
14 | )
15 |
16 | const (
17 | CopyURLLabel = "Copy URL"
18 | CopyBaseURLLabel = "Copy base URL"
19 | RepeatLabel = "Repeat"
20 | ClearHistoryLabel = "Clear History"
21 | AddToScopeLabel = "Add Host to Scope"
22 | )
23 |
24 | // Gui represents the GUI of the main intercept proxy
25 | type Gui struct {
26 | core.GuiModule
27 |
28 | Sess *core.Session
29 |
30 | rightClickLabels []string
31 | ControllerInit func()
32 | StartProxy func(bool)
33 | StopProxy func()
34 | RowClicked func(int)
35 | ApplyFilters func(bool)
36 | ResetFilters func(bool)
37 | CheckReqInterception func(bool)
38 | CheckRespInterception func(bool)
39 | CheckIgnoreHTTPS func(bool)
40 | SaveCAClicked func(bool)
41 | RightItemClicked func(string, int)
42 | settingsTab *widgets.QTabWidget
43 | settingsWidget widgets.QWidget_ITF
44 |
45 | // history tab
46 | historyTableView *widgets.QTableView
47 | contextMenu *widgets.QMenu
48 | splitter *widgets.QSplitter
49 | reqRespTab *widgets.QTabWidget
50 | RequestTextEdit *widgets.QPlainTextEdit
51 | EditedRequestTextEdit *widgets.QPlainTextEdit
52 | ResponseTextEdit *widgets.QPlainTextEdit
53 | EditedResponseTextEdit *widgets.QPlainTextEdit
54 | historyTab *widgets.QTabWidget
55 |
56 | // Filter
57 | TextSearchLineEdit *widgets.QLineEdit
58 | ShowScopeOnlyCheckBox *widgets.QCheckBox
59 | ScopeLineEdit *widgets.QLineEdit
60 | ApplyFiltersButton *widgets.QPushButton
61 | ResetFiltersButton *widgets.QPushButton
62 | S100CheckBox *widgets.QCheckBox
63 | S200CheckBox *widgets.QCheckBox
64 | S300CheckBox *widgets.QCheckBox
65 | S400CheckBox *widgets.QCheckBox
66 | S500CheckBox *widgets.QCheckBox
67 | ShowExtensionLineEdit *widgets.QLineEdit
68 | HideExtensionLineEdit *widgets.QLineEdit
69 | ShowOnlyCheckBox *widgets.QCheckBox
70 | HideOnlyCheckBox *widgets.QCheckBox
71 |
72 | coreProxyGui *widgets.QTabWidget
73 |
74 | tableModel *model.CustomTableModel
75 |
76 | view *quick.QQuickView
77 |
78 | // settings tab
79 | ListenerLineEdit *widgets.QLineEdit
80 | StartStopButton *widgets.QPushButton
81 | ReqInterceptCheckBox *widgets.QCheckBox
82 | RespInterceptCheckBox *widgets.QCheckBox
83 | SaveCAButton *widgets.QPushButton
84 | ignoreHTTPSCheckBox *widgets.QCheckBox
85 |
86 | // interceptor
87 | ForwardButton *widgets.QPushButton
88 | DropButton *widgets.QPushButton
89 | InterceptorToggleButton *widgets.QPushButton
90 | InterceptorTextEdit *widgets.QPlainTextEdit
91 | Toggle func(bool)
92 | Forward func(bool)
93 | Drop func(bool)
94 | }
95 |
96 | // NewGui creates a new Gui for the main intercetp proxy
97 | func NewGui(s *core.Session) *Gui {
98 | return &Gui{
99 | Sess: s,
100 | historyTableView: widgets.NewQTableView(nil),
101 | view: quick.NewQQuickView(nil),
102 | rightClickLabels: []string{CopyURLLabel, CopyBaseURLLabel, RepeatLabel, ClearHistoryLabel, AddToScopeLabel},
103 | }
104 | }
105 |
106 | func (g *Gui) interceptorTabGui() widgets.QWidget_ITF {
107 | widget := widgets.NewQWidget(nil, 0)
108 | vlayout := widgets.NewQVBoxLayout()
109 | widget.SetLayout(vlayout)
110 |
111 | widget.SetContentsMargins(0, 0, 0, 0)
112 |
113 | hlayout := widgets.NewQHBoxLayout()
114 |
115 | g.ForwardButton = widgets.NewQPushButton2("Forward", nil)
116 | g.DropButton = widgets.NewQPushButton2("Drop", nil)
117 | g.InterceptorToggleButton = widgets.NewQPushButton2("Interceptor", nil)
118 | spacerItem := widgets.NewQSpacerItem(400, 20, widgets.QSizePolicy__Expanding, widgets.QSizePolicy__Minimum)
119 |
120 | hlayout.AddWidget(g.ForwardButton, 0, qtcore.Qt__AlignLeft)
121 | g.ForwardButton.ConnectClicked(g.Forward)
122 | hlayout.AddWidget(g.DropButton, 0, qtcore.Qt__AlignLeft)
123 | g.DropButton.ConnectClicked(g.Drop)
124 | hlayout.AddWidget(g.InterceptorToggleButton, 0, qtcore.Qt__AlignLeft)
125 | g.InterceptorToggleButton.ConnectClicked(g.Toggle)
126 | g.InterceptorToggleButton.SetAutoRepeat(true)
127 | g.InterceptorToggleButton.SetCheckable(true)
128 | hlayout.AddItem(spacerItem)
129 |
130 | vlayout.AddLayout(hlayout, 0)
131 |
132 | g.InterceptorTextEdit = widgets.NewQPlainTextEdit(nil)
133 | vlayout.AddWidget(g.InterceptorTextEdit, 0, 0)
134 |
135 | return widget
136 |
137 | }
138 |
139 | func (g *Gui) filtersTabGui() widgets.QWidget_ITF {
140 | scrollArea := widgets.NewQScrollArea(nil)
141 | scrollArea.SetWidgetResizable(true)
142 | //scrollArea.SetGeometry2(10, 10, 400, 400)
143 | scrollAreaWidget := widgets.NewQWidget(nil, 0)
144 | vlayout1 := widgets.NewQVBoxLayout()
145 | scrollAreaWidget.SetLayout(vlayout1)
146 | scrollArea.SetWidget(scrollAreaWidget)
147 |
148 | //TODO: implement scope
149 |
150 | // search text
151 | label2 := widgets.NewQLabel(nil, 0)
152 | font2 := gui.NewQFont()
153 | font2.SetPointSize(20)
154 | font2.SetBold(true)
155 | font2.SetWeight(75)
156 | label2.SetFont(font2)
157 | label2.SetText("Text search")
158 | vlayout1.AddWidget(label2, 0, qtcore.Qt__AlignLeft)
159 | //scrollAreaWidget.SetStyleSheet("background-color: red")
160 |
161 | g.TextSearchLineEdit = widgets.NewQLineEdit(nil)
162 | g.TextSearchLineEdit.SetMinimumSize(qtcore.NewQSize2(450, 0))
163 | //g.TextSearchLineEdit.SetMaximumSize(qtcore.NewQSize2(450, 16777215))
164 | g.TextSearchLineEdit.SetBaseSize(qtcore.NewQSize2(0, 0))
165 | g.TextSearchLineEdit.SetText("")
166 | vlayout1.AddWidget(g.TextSearchLineEdit, 0, qtcore.Qt__AlignLeft)
167 |
168 | labelScope := widgets.NewQLabel(nil, 0)
169 | fontScope := gui.NewQFont()
170 | fontScope.SetPointSize(20)
171 | fontScope.SetBold(true)
172 | fontScope.SetWeight(75)
173 | labelScope.SetFont(fontScope)
174 | labelScope.SetText("Scope")
175 | vlayout1.AddWidget(labelScope, 0, qtcore.Qt__AlignLeft)
176 |
177 | // Scope
178 | g.ScopeLineEdit = widgets.NewQLineEdit(nil)
179 | //g.ScopeLineEdit.SetMinimumSize(qtcore.NewQSize2(150, 0))
180 | g.ScopeLineEdit.SetMinimumSize(qtcore.NewQSize2(450, 16777215))
181 | //g.ScopeLineEdit.SetBaseSize(qtcore.NewQSize2(0, 0))
182 | g.ScopeLineEdit.SetText("")
183 | vlayout1.AddWidget(g.ScopeLineEdit, 0, qtcore.Qt__AlignLeft)
184 |
185 | g.ShowScopeOnlyCheckBox = widgets.NewQCheckBox(nil)
186 | g.ShowScopeOnlyCheckBox.SetText("Show Scope Only")
187 | vlayout1.AddWidget(g.ShowScopeOnlyCheckBox, 0, qtcore.Qt__AlignLeft)
188 |
189 | // Status
190 | label3 := widgets.NewQLabel(nil, 0)
191 | font3 := gui.NewQFont()
192 | font3.SetPointSize(20)
193 | font3.SetBold(true)
194 | font3.SetWeight(75)
195 | label3.SetFont(font3)
196 | label3.SetText("Status")
197 | vlayout1.AddWidget(label3, 0, qtcore.Qt__AlignLeft)
198 |
199 | g.S100CheckBox = widgets.NewQCheckBox(nil)
200 | g.S100CheckBox.SetText("1xx")
201 | vlayout1.AddWidget(g.S100CheckBox, 0, qtcore.Qt__AlignLeft)
202 |
203 | g.S200CheckBox = widgets.NewQCheckBox(nil)
204 | g.S200CheckBox.SetText("2xx")
205 | vlayout1.AddWidget(g.S200CheckBox, 0, qtcore.Qt__AlignLeft)
206 |
207 | g.S300CheckBox = widgets.NewQCheckBox(nil)
208 | g.S300CheckBox.SetText("3xx")
209 | vlayout1.AddWidget(g.S300CheckBox, 0, qtcore.Qt__AlignLeft)
210 |
211 | g.S400CheckBox = widgets.NewQCheckBox(nil)
212 | g.S400CheckBox.SetText("4xx")
213 | vlayout1.AddWidget(g.S400CheckBox, 0, qtcore.Qt__AlignLeft)
214 |
215 | g.S500CheckBox = widgets.NewQCheckBox(nil)
216 | g.S500CheckBox.SetText("5xx")
217 | vlayout1.AddWidget(g.S500CheckBox, 0, qtcore.Qt__AlignLeft)
218 |
219 | // Extensions
220 | label4 := widgets.NewQLabel(nil, 0)
221 | font4 := gui.NewQFont()
222 | font4.SetPointSize(20)
223 | font4.SetBold(true)
224 | font4.SetWeight(75)
225 | label4.SetFont(font4)
226 | label4.SetText("Extension")
227 |
228 | vlayout1.AddWidget(label4, 0, qtcore.Qt__AlignLeft)
229 |
230 | gridLayout := widgets.NewQGridLayout2()
231 | g.ShowExtensionLineEdit = widgets.NewQLineEdit(nil)
232 | g.ShowExtensionLineEdit.SetMinimumSize(qtcore.NewQSize2(150, 0))
233 | g.ShowExtensionLineEdit.SetMaximumSize(qtcore.NewQSize2(150, 16777215))
234 | g.ShowExtensionLineEdit.SetBaseSize(qtcore.NewQSize2(0, 0))
235 | g.ShowExtensionLineEdit.SetText("")
236 |
237 | g.HideExtensionLineEdit = widgets.NewQLineEdit(nil)
238 | g.HideExtensionLineEdit.SetMinimumSize(qtcore.NewQSize2(150, 0))
239 | g.HideExtensionLineEdit.SetMaximumSize(qtcore.NewQSize2(150, 16777215))
240 | g.HideExtensionLineEdit.SetBaseSize(qtcore.NewQSize2(0, 0))
241 | g.HideExtensionLineEdit.SetText("")
242 |
243 | g.ShowOnlyCheckBox = widgets.NewQCheckBox(nil)
244 | g.ShowOnlyCheckBox.SetText("Show only")
245 |
246 | g.HideOnlyCheckBox = widgets.NewQCheckBox(nil)
247 | g.HideOnlyCheckBox.SetText("Hide")
248 |
249 | gridLayout.AddWidget(g.ShowExtensionLineEdit)
250 | gridLayout.AddWidget(g.ShowOnlyCheckBox)
251 |
252 | gridLayout.AddWidget(g.HideExtensionLineEdit)
253 | gridLayout.AddWidget(g.HideOnlyCheckBox)
254 |
255 |
256 | spacerItem := widgets.NewQSpacerItem(400, 20, widgets.QSizePolicy__Expanding, widgets.QSizePolicy__Minimum)
257 | gridLayout.AddItem(spacerItem, 0, 2, 1, 1, qtcore.Qt__AlignRight)
258 |
259 | vlayout1.AddLayout(gridLayout, 0)
260 |
261 | // Apply\Reset buttons
262 | g.ApplyFiltersButton = widgets.NewQPushButton2("Apply", nil)
263 | g.ApplyFiltersButton.ConnectClicked(g.ApplyFilters)
264 |
265 | gridLayout.AddWidget(g.ApplyFiltersButton)
266 |
267 | g.ResetFiltersButton = widgets.NewQPushButton2("Reset", nil)
268 | g.ResetFiltersButton.ConnectClicked(g.ResetFilters)
269 |
270 | gridLayout.AddWidget(g.ResetFiltersButton)
271 |
272 | spacerItem1 := widgets.NewQSpacerItem(20, 1000, widgets.QSizePolicy__Minimum, widgets.QSizePolicy__Expanding)
273 | vlayout1.AddItem(spacerItem1)
274 |
275 | return scrollArea
276 | }
277 |
278 | //func (g *Gui) settingsTabGui() widgets.QWidget_ITF {
279 | func (g *Gui) GetSettings() interface{} {
280 | return g.settingsWidget
281 | }
282 |
283 | func (g *Gui) settingsGui() widgets.QWidget_ITF {
284 | scrollArea := widgets.NewQScrollArea(nil)
285 | scrollArea.SetWidgetResizable(true)
286 | scrollArea.SetGeometry2(10, 10, 200, 200)
287 | scrollAreaWidget := widgets.NewQWidget(nil, 0)
288 | vlayout1 := widgets.NewQVBoxLayout()
289 | scrollAreaWidget.SetLayout(vlayout1)
290 | scrollArea.SetWidget(scrollAreaWidget)
291 |
292 | scrollArea.SetContentsMargins(11, 11, 11, 11)
293 | ////widget.SetSpacing(6)
294 | scrollArea.SetObjectName("verticalLayout")
295 |
296 | label := widgets.NewQLabel(nil, 0)
297 | font := gui.NewQFont()
298 | font.SetPointSize(20)
299 | font.SetBold(true)
300 | font.SetWeight(75)
301 | label.SetFont(font)
302 | label.SetObjectName("label")
303 | label.SetText("Proxy Listener")
304 | vlayout1.AddWidget(label, 0, qtcore.Qt__AlignLeft)
305 |
306 | label2 := widgets.NewQLabel(nil, 0)
307 | label2.SetObjectName("label2")
308 | label2.SetText("Description goes here")
309 | vlayout1.AddWidget(label2, 0, qtcore.Qt__AlignLeft)
310 |
311 | gridLayout := widgets.NewQGridLayout2()
312 | g.ListenerLineEdit = widgets.NewQLineEdit(nil)
313 | g.ListenerLineEdit.SetMinimumSize(qtcore.NewQSize2(150, 0))
314 | g.ListenerLineEdit.SetMaximumSize(qtcore.NewQSize2(150, 16777215))
315 | g.ListenerLineEdit.SetBaseSize(qtcore.NewQSize2(0, 0))
316 | g.ListenerLineEdit.SetText("127.0.0.1:8080")
317 | gridLayout.AddWidget(g.ListenerLineEdit)
318 |
319 | g.StartStopButton = widgets.NewQPushButton2("Start", nil)
320 | g.StartStopButton.ConnectClicked(g.StartProxy)
321 | gridLayout.AddWidget(g.StartStopButton)
322 |
323 | spacerItem := widgets.NewQSpacerItem(400, 20, widgets.QSizePolicy__Expanding, widgets.QSizePolicy__Minimum)
324 | gridLayout.AddItem(spacerItem, 0, 2, 1, 1, qtcore.Qt__AlignRight)
325 |
326 | vlayout1.AddLayout(gridLayout, 0)
327 |
328 | // interception settings
329 | label1 := widgets.NewQLabel(nil, 0)
330 | label1.SetFont(font)
331 | label1.SetText("Interception")
332 | vlayout1.AddWidget(label1, 0, qtcore.Qt__AlignLeft)
333 |
334 | g.ReqInterceptCheckBox = widgets.NewQCheckBox(nil)
335 | g.ReqInterceptCheckBox.SetText("Intercept requests")
336 | g.ReqInterceptCheckBox.ConnectClicked(g.CheckReqInterception)
337 | vlayout1.AddWidget(g.ReqInterceptCheckBox, 0, qtcore.Qt__AlignLeft)
338 |
339 | g.RespInterceptCheckBox = widgets.NewQCheckBox(nil)
340 | g.RespInterceptCheckBox.SetText("Intercept responses")
341 | g.RespInterceptCheckBox.ConnectClicked(g.CheckRespInterception)
342 | vlayout1.AddWidget(g.RespInterceptCheckBox, 0, qtcore.Qt__AlignLeft)
343 |
344 | labelCA := widgets.NewQLabel(nil, 0)
345 | labelCA.SetText("Certificate Authority")
346 | labelCA.SetFont(font)
347 | vlayout1.AddWidget(labelCA, 0, qtcore.Qt__AlignLeft)
348 |
349 | g.SaveCAButton = widgets.NewQPushButton2("Save CA certificate", nil)
350 | g.SaveCAButton.ConnectClicked(g.SaveCAClicked)
351 | vlayout1.AddWidget(g.SaveCAButton, 0, qtcore.Qt__AlignLeft)
352 |
353 | g.ignoreHTTPSCheckBox = widgets.NewQCheckBox(nil)
354 | g.ignoreHTTPSCheckBox.SetText("Do not intercept HTTPS")
355 | g.ignoreHTTPSCheckBox.ConnectClicked(g.CheckIgnoreHTTPS)
356 | vlayout1.AddWidget(g.ignoreHTTPSCheckBox, 0, qtcore.Qt__AlignLeft)
357 |
358 | spacerItem1 := widgets.NewQSpacerItem(20, 40, widgets.QSizePolicy__Minimum, widgets.QSizePolicy__Expanding)
359 | vlayout1.AddItem(spacerItem1)
360 |
361 | return scrollArea
362 | }
363 |
364 | // SetRightClickMenu sets the menu items when right clicking an item in the history table
365 | func (g *Gui) SetRightClickMenu() {
366 | }
367 |
368 | // SetTableModel sets the table model along with some column width to use in the history table
369 | func (g *Gui) SetTableModel(m *model.SortFilterModel) {
370 | g.historyTableView.SetModel(m)
371 | g.historyTableView.SetColumnWidth(model.ID, 40)
372 | g.historyTableView.SetColumnWidth(model.Host, 200)
373 | g.historyTableView.SetColumnWidth(model.Method, 80)
374 | g.historyTableView.SetColumnWidth(model.Path, 200)
375 | g.historyTableView.SetColumnWidth(model.Params, 60)
376 | g.historyTableView.SetColumnWidth(model.Edit, 60)
377 | g.historyTableView.SetColumnWidth(model.Status, 80)
378 | g.historyTableView.SetColumnWidth(model.Length, 80)
379 | //TODO: move the SetRightClickMenu somewhere that makes sense
380 | g.SetRightClickMenu()
381 | }
382 |
383 | // HideAllTabs hides the tabs used to view details of a single row in the history table
384 | func (g *Gui) HideAllTabs() {
385 | for i := g.reqRespTab.Count(); i != 0; i-- {
386 | g.reqRespTab.RemoveTab(i)
387 | }
388 | }
389 |
390 | // ShowReqTab shows the request tab for the currently selected item in the history table
391 | func (g *Gui) ShowReqTab(req string) {
392 | g.reqRespTab.AddTab(g.RequestTextEdit, "Request")
393 | g.RequestTextEdit.SetPlainText(req)
394 | }
395 |
396 | // ShowEditedReqTab shows the edited request tab for the currently selected item in the history table
397 | func (g *Gui) ShowEditedReqTab(editedReq string) {
398 | g.reqRespTab.AddTab(g.EditedRequestTextEdit, "Edited Request")
399 | g.EditedRequestTextEdit.SetPlainText(editedReq)
400 |
401 | }
402 |
403 | // ShowRespTab shows the response tab for the currently selected item in the history table
404 | func (g *Gui) ShowRespTab(resp string) {
405 | g.reqRespTab.AddTab(g.ResponseTextEdit, "Response")
406 | g.ResponseTextEdit.SetPlainText(resp)
407 | }
408 |
409 | // ShowEditedRespTab shows the edited response tab for the currently selected item in the history table
410 | func (g *Gui) ShowEditedRespTab(editedResp string) {
411 | g.reqRespTab.AddTab(g.EditedResponseTextEdit, "Edited Response")
412 | g.EditedResponseTextEdit.SetPlainText(editedResp)
413 | }
414 |
415 | func (g *Gui) customContextMenuRequested(p *qtcore.QPoint) {
416 | if g.contextMenu == nil {
417 | g.contextMenu = widgets.NewQMenu(nil)
418 | copyURLAction := g.contextMenu.AddAction(CopyURLLabel)
419 | copyURLAction.ConnectTriggered(func(b bool) {
420 | if len(g.historyTableView.SelectedIndexes()) > 0 {
421 | g.RightItemClicked(CopyURLLabel, g.historyTableView.SelectedIndexes()[0].Row())
422 | }
423 | })
424 |
425 | copyBaseURLAction := g.contextMenu.AddAction(CopyBaseURLLabel)
426 | copyBaseURLAction.ConnectTriggered(func(b bool) {
427 | if len(g.historyTableView.SelectedIndexes()) > 0 {
428 | g.RightItemClicked(CopyBaseURLLabel, g.historyTableView.SelectedIndexes()[0].Row())
429 | }
430 | })
431 |
432 | repeatAction := g.contextMenu.AddAction(RepeatLabel)
433 | repeatAction.ConnectTriggered(func(b bool) {
434 | if len(g.historyTableView.SelectedIndexes()) > 0 {
435 | g.RightItemClicked(RepeatLabel, g.historyTableView.SelectedIndexes()[0].Row())
436 | }
437 | })
438 |
439 | clearHistoryAction := g.contextMenu.AddAction(ClearHistoryLabel)
440 | clearHistoryAction.ConnectTriggered(func(b bool) {
441 | if len(g.historyTableView.SelectedIndexes()) > 0 {
442 | g.RightItemClicked(ClearHistoryLabel, g.historyTableView.SelectedIndexes()[0].Row())
443 | }
444 | })
445 |
446 | addToScopeAction := g.contextMenu.AddAction(AddToScopeLabel)
447 | addToScopeAction.ConnectTriggered(func(b bool) {
448 | if len(g.historyTableView.SelectedIndexes()) > 0 {
449 | g.RightItemClicked(AddToScopeLabel, g.historyTableView.SelectedIndexes()[0].Row())
450 | }
451 | })
452 |
453 | }
454 | p.SetY(p.Ry() + 15)
455 | g.contextMenu.Exec2(g.historyTableView.MapToGlobal(p), nil)
456 | }
457 |
458 | // GetModuleGui returns the Gui for the current module
459 | func (g *Gui) GetModuleGui() interface{} {
460 | g.coreProxyGui = widgets.NewQTabWidget(nil)
461 | g.coreProxyGui.SetDocumentMode(true)
462 |
463 | g.historyTableView.SetShowGrid(false)
464 | g.historyTableView.VerticalHeader().Hide()
465 | g.historyTableView.SetAlternatingRowColors(true)
466 | g.historyTableView.ConnectClicked(func(index *qtcore.QModelIndex) {
467 | g.RowClicked(index.Row())
468 | })
469 | //g.historyTableView.ConnectActivated(model.ShowMessage2)
470 | g.historyTableView.ConnectCurrentChanged(func(current *qtcore.QModelIndex, prev *qtcore.QModelIndex) {
471 | g.historyTableView.ScrollTo(current, 0)
472 | g.RowClicked(current.Row())
473 | })
474 | g.historyTableView.SetEditTriggers(widgets.QAbstractItemView__NoEditTriggers)
475 | g.historyTableView.SetSelectionBehavior(widgets.QAbstractItemView__SelectRows)
476 | g.historyTableView.SetSelectionMode(widgets.QAbstractItemView__SingleSelection)
477 | g.historyTableView.SetContextMenuPolicy(qtcore.Qt__CustomContextMenu)
478 | g.historyTableView.ConnectCustomContextMenuRequested(g.customContextMenuRequested)
479 | g.historyTableView.SetSortingEnabled(true)
480 | g.historyTableView.VerticalHeader().SetSectionResizeMode(widgets.QHeaderView__Fixed)
481 | g.historyTableView.VerticalHeader().SetDefaultSectionSize(10)
482 |
483 | // history tab with filters
484 | g.historyTab = widgets.NewQTabWidget(nil)
485 | g.historyTab.SetDocumentMode(true)
486 |
487 | // request\response tabs with text editor
488 | g.reqRespTab = widgets.NewQTabWidget(nil)
489 | g.reqRespTab.SetDocumentMode(true)
490 | g.RequestTextEdit = widgets.NewQPlainTextEdit(nil)
491 | g.RequestTextEdit.SetReadOnly(true)
492 | g.ResponseTextEdit = widgets.NewQPlainTextEdit(nil)
493 | g.ResponseTextEdit.SetReadOnly(true)
494 | g.EditedRequestTextEdit = widgets.NewQPlainTextEdit(nil)
495 | g.EditedRequestTextEdit.SetReadOnly(true)
496 | g.EditedResponseTextEdit = widgets.NewQPlainTextEdit(nil)
497 | g.EditedResponseTextEdit.SetReadOnly(true)
498 | //g.reqRespTab.AddTab(g.RequestTextEdit, "Request")
499 | //g.reqRespTab.AddTab(g.EditedRequestTextEdit, "Edited Request")
500 | //g.reqRespTab.AddTab(g.ResponseTextEdit, "Response")
501 |
502 | // the splitter for tab history
503 | g.splitter = widgets.NewQSplitter(nil)
504 | g.splitter.SetOrientation(qtcore.Qt__Vertical)
505 | g.splitter.AddWidget(g.historyTableView)
506 | g.splitter.AddWidget(g.reqRespTab)
507 |
508 | g.historyTab.AddTab(g.splitter, "History")
509 | g.historyTab.AddTab(g.filtersTabGui(), "Filters")
510 |
511 | var sizes []int
512 | sizes = make([]int, 2)
513 | sizes[0] = 1 * g.splitter.SizeHint().Height()
514 | sizes[1] = 1 * g.splitter.SizeHint().Height()
515 | g.splitter.SetSizes(sizes)
516 |
517 | // a start button
518 | // g.startBtn = widgets.NewQPushButton2("Start", nil)
519 | // g.startBtn.ConnectClicked(g.StartProxy)
520 |
521 | g.coreProxyGui.AddTab(g.interceptorTabGui(), "Interceptor")
522 | g.coreProxyGui.AddTab(g.historyTab, "History")
523 | g.settingsWidget = g.settingsGui()
524 | //g.coreProxyGui.AddTab(g.settingsTabGui(), "Settings")
525 |
526 | //IMP: make me pretier
527 | g.ControllerInit()
528 |
529 | return g.coreProxyGui
530 | }
531 |
532 | // FileSaveAs saves the CA file
533 | func (g *Gui) FileSaveAs(s string) bool {
534 | var fileDialog = widgets.NewQFileDialog2(nil, "Save as...", "broxyca.pem", "PEM (*.pem)")
535 | fileDialog.SetAcceptMode(widgets.QFileDialog__AcceptSave)
536 | var mimeTypes = []string{"application/x-pem-file"}
537 | fileDialog.SetMimeTypeFilters(mimeTypes)
538 | fileDialog.SetDefaultSuffix("pem")
539 | if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
540 | return false
541 | }
542 | var fn = fileDialog.SelectedFiles()[0]
543 |
544 | f, err := os.Create(fn)
545 | if err != nil {
546 | return false
547 | }
548 | defer f.Close()
549 | _, err1 := f.WriteString(s)
550 | if err1 != nil {
551 | return false
552 | }
553 | return true
554 | }
555 |
556 | func (g *Gui) bench(b bool) {
557 | fmt.Println("start here")
558 |
559 | s := time.Now()
560 | rows := g.tableModel.RowCount(qtcore.NewQModelIndex())
561 | columns := g.tableModel.ColumnCount(qtcore.NewQModelIndex())
562 |
563 | for i := 0; i < rows; i++ {
564 |
565 | for j := 0; j < columns; j++ {
566 |
567 | value := g.tableModel.Data(g.tableModel.Index(i, j, qtcore.NewQModelIndex()), 0)
568 | fmt.Println(value.ToString())
569 |
570 | }
571 |
572 | }
573 |
574 | elapsed := time.Since(s)
575 | fmt.Println(elapsed)
576 |
577 | }
578 |
579 | // Title returns the time of this Gui
580 | func (g *Gui) Title() string {
581 | return "Proxy"
582 | }
583 |
--------------------------------------------------------------------------------
/modules/coreproxy/coreproxy_interceptor.go:
--------------------------------------------------------------------------------
1 | package coreproxy
2 |
3 | import (
4 | "bufio"
5 | "encoding/hex"
6 | "fmt"
7 | "io"
8 | "net/http"
9 | "regexp"
10 | "strings"
11 |
12 | "github.com/elazarl/goproxy"
13 | "github.com/rhaidiz/broxy/util"
14 | )
15 |
16 | func (c *Controller) interceptorToggle(b bool) {
17 | if !Stg.Interceptor {
18 | Stg.Interceptor = true
19 | } else {
20 | Stg.Interceptor = false
21 | if c.requestsQueue > 0 || c.responsesQueue > 0 {
22 | tmp := c.requestsQueue + c.responsesQueue
23 | for i := 0; i < tmp; i++ {
24 | c.forwardChan <- true
25 | }
26 | }
27 | }
28 | c.Sess.Debug(c.Module.Name(), fmt.Sprintf("Interceptor is: %v", Stg.Interceptor))
29 | c.saveSettings()
30 | }
31 |
32 | func (c *Controller) forward(b bool) {
33 | go func() {
34 | // activate only if there's something waiting
35 | if c.requestsQueue > 0 || c.responsesQueue > 0 {
36 | c.forwardChan <- true
37 | }
38 | }()
39 | }
40 |
41 | func (c *Controller) drop(b bool) {
42 | go func() {
43 | // activate only if there's something waiting
44 | if c.requestsQueue > 0 || c.responsesQueue > 0 {
45 | c.dropChan <- true
46 | }
47 | }()
48 | }
49 |
50 | func (c *Controller) interceptorResponseActions(req *http.Request, resp *http.Response) *http.Response {
51 |
52 | var _resp *http.Response
53 | bodyHex := false
54 | // increase the requests in queue
55 | c.responsesQueue = c.responsesQueue + 1
56 | mutex.Lock()
57 | // if response is bigger than 100mb, show message that is too big
58 | // if the response has come sort of encoding, show the body as hex
59 | // and confert it back to string after the editing
60 | if resp.ContentLength >= 1e+8 {
61 | c.Gui.InterceptorTextEdit.SetPlainText("Response too big")
62 | } else {
63 | _, contentTypeOK := resp.Header["Content-Type"]
64 | _, contentEncodingOK := resp.Header["Content-Encoding"]
65 | if (contentTypeOK && strings.HasPrefix(resp.Header["Content-Type"][0], "image")) || contentEncodingOK {
66 | c.Gui.InterceptorTextEdit.SetPlainText(util.ResponseToString(resp, true))
67 | bodyHex = true
68 | } else {
69 | c.Gui.InterceptorTextEdit.SetPlainText(util.ResponseToString(resp, false))
70 | }
71 | }
72 | for {
73 | parseError := false
74 | select {
75 | case <-c.forwardChan:
76 | if !Stg.Interceptor {
77 | _resp = resp
78 | break
79 | }
80 | // if response is bigger than 100mb, ignore the content of the QPlainTextEditor
81 | if resp.ContentLength >= 1e+8 {
82 | _resp = resp
83 | }
84 |
85 | var tmp *http.Response
86 | var err error
87 | // pressed forward
88 | // remove "Content-Length" so that the ReadResponse will compute the right ContentLength
89 | var re = regexp.MustCompile(`(Content-Length: *\d+)\n?`)
90 | s := re.ReplaceAllString(c.Gui.InterceptorTextEdit.ToPlainText(), "")
91 |
92 | if bodyHex {
93 | a := regexp.MustCompile(`\n\n`)
94 | s1 := a.Split(s, 2)
95 | if len(s1) == 2 {
96 | br, err := hex.DecodeString(s1[1])
97 | if err != nil {
98 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("Forward Resp: %s", err.Error()))
99 | parseError = true
100 | } else {
101 | bodyHex = false
102 | s = fmt.Sprintf("%s\n%s", s1[0], string(br))
103 | }
104 | }
105 | } else {
106 |
107 | reader := strings.NewReader(s)
108 | buf := bufio.NewReader(reader)
109 |
110 | tmp, err = http.ReadResponse(buf, nil)
111 | // so bad, fix me
112 | _resp = tmp
113 |
114 | if err != nil && err == io.ErrUnexpectedEOF {
115 | reader := strings.NewReader(s + "\n\n")
116 | buf := bufio.NewReader(reader)
117 | // this is so ugly
118 | tmp, err = http.ReadResponse(buf, nil)
119 | _resp = tmp
120 | if err != nil {
121 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("Forward Resp: %s", err.Error()))
122 | parseError = true
123 | }
124 | }
125 |
126 | if err == nil {
127 | if util.ResponsesEquals(resp, _resp) {
128 | // response not edited
129 | _resp = nil
130 | }
131 | }
132 | }
133 | case <-c.dropChan:
134 | // pressed drop
135 | _resp = goproxy.NewResponse(req,
136 | goproxy.ContentTypeText, http.StatusForbidden, "Request droppped")
137 | }
138 | if !parseError {
139 | break
140 | }
141 | }
142 |
143 | // decrease the requests in queue
144 | c.responsesQueue = c.responsesQueue - 1
145 | // rest the editor
146 | c.Gui.InterceptorTextEdit.SetPlainText("")
147 | mutex.Unlock()
148 |
149 | return _resp
150 | }
151 |
152 | func cloneHeaders(src http.Header) http.Header {
153 | dst := http.Header{}
154 | for k, vs := range src {
155 | for _, v := range vs {
156 | dst.Add(k, v)
157 | }
158 | }
159 | return dst
160 | }
161 |
162 | func (c *Controller) interceptorRequestActions(req *http.Request, resp *http.Response, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
163 |
164 | // the request to return
165 | var _req *http.Request
166 | var _resp *http.Response
167 |
168 | c.requestsQueue = c.requestsQueue + 1
169 | mutex.Lock()
170 | delete(req.Header, "Connection")
171 | c.Gui.InterceptorTextEdit.SetPlainText(util.RequestToString(req) + "\n")
172 |
173 | for {
174 | parseError := false
175 | select {
176 | // pressed forward
177 | case <-c.forwardChan:
178 | if !Stg.Interceptor {
179 | _req = req
180 | _resp = nil
181 | break
182 | }
183 | var r *http.Request
184 | var err error
185 |
186 | reader := strings.NewReader(util.NormalizeRequest(c.Gui.InterceptorTextEdit.ToPlainText()))
187 | buf := bufio.NewReader(reader)
188 |
189 | r, err = http.ReadRequest(buf)
190 | if err != nil && err == io.ErrUnexpectedEOF {
191 | reader := strings.NewReader(util.NormalizeRequest(c.Gui.InterceptorTextEdit.ToPlainText()) + "\n\n")
192 | buf := bufio.NewReader(reader)
193 | // this is so ugly
194 | r, err = http.ReadRequest(buf)
195 | if err != nil {
196 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("Forward Req: %s", err.Error()))
197 | parseError = true
198 | }
199 | }
200 | if err == nil {
201 | r.URL.Scheme = req.URL.Scheme
202 | r.URL.Host = req.URL.Host
203 | r.RequestURI = ""
204 | if util.RequestsEquals(req, r) {
205 | _req = nil
206 | _resp = nil
207 | } else {
208 | _req = r
209 | _resp = nil
210 | }
211 | }
212 | // pressed drop
213 | case <-c.dropChan:
214 | c.dropped[ctx.Session] = true
215 | _req = req
216 | _resp = goproxy.NewResponse(req,
217 | goproxy.ContentTypeText, http.StatusForbidden, "Request droppped")
218 | }
219 | if !parseError {
220 | break
221 | }
222 | }
223 | // decrease the requests in queue
224 | c.requestsQueue = c.requestsQueue - 1
225 | // rest the editor
226 | c.Gui.InterceptorTextEdit.SetPlainText("")
227 | mutex.Unlock()
228 |
229 | return _req, _resp
230 | }
231 |
--------------------------------------------------------------------------------
/modules/coreproxy/coreproxy_module.go:
--------------------------------------------------------------------------------
1 | package coreproxy
2 |
3 | import (
4 | "github.com/rhaidiz/broxy/core"
5 | )
6 |
7 | // LoadCoreProxyModule loads the core proxy module in the given session
8 | func LoadCoreProxyModule(s *core.Session) *Controller {
9 | m := NewCoreProxy(s)
10 | g := NewGui(s)
11 | c := NewController(m, g, s)
12 | return c
13 | }
14 |
--------------------------------------------------------------------------------
/modules/coreproxy/coreproxy_settings.go:
--------------------------------------------------------------------------------
1 | package coreproxy
2 |
3 | // Settings represents the settings for the core intercept proxy
4 | // TODO: fix it because you also have core.Config
5 | type Settings struct {
6 | IP string
7 | Port int
8 | Interceptor bool
9 | ReqIntercept bool
10 | RespIntercept bool
11 | }
12 |
13 | var Stg = &Settings{
14 | IP: "127.0.0.1",
15 | Port: 8080,
16 | Interceptor: false,
17 | ReqIntercept: true,
18 | RespIntercept: false,
19 | }
20 |
--------------------------------------------------------------------------------
/modules/coreproxy/model/filters.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | // Filter represents the filter of the history table
4 | type Filter struct {
5 | Search string
6 | StatusCode []int
7 | Show bool
8 | Hide bool
9 | ShowExt []string
10 | HideExt []string
11 | ScopeOnly bool
12 | Scope []string
13 | }
14 |
15 |
16 | var DefaultFilter = & Filter{
17 | Search : "",
18 | StatusCode : []int{100, 200, 300, 400, 500},
19 | Show : false,
20 | Hide : true,
21 | HideExt : []string{"jpg", "png"},
22 | ShowExt : []string{"asp","php"},
23 | ScopeOnly : false,
24 | Scope : []string{},
25 | }
26 |
--------------------------------------------------------------------------------
/modules/coreproxy/model/model.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "fmt"
5 | "net/http"
6 | "net/url"
7 | "sync"
8 |
9 | "github.com/therecipe/qt/core"
10 | )
11 |
12 | var History []*Row
13 |
14 | // used to map id to actual rows in the table
15 | var HashMapHistory = make(map[int64]int)
16 |
17 | type Row struct {
18 | ID int64
19 | Req *Request
20 | Resp *Response
21 | EditedReq *Request
22 | EditedResp *Response
23 | }
24 |
25 | // Request represents an HTTP request logged in the history
26 | type Request struct {
27 | ID int64
28 | URL *url.URL
29 | Proto string
30 | Method string
31 | Host string
32 | Headers http.Header
33 | ContentLength int64
34 | Body []byte
35 | Extension string
36 | Params bool
37 | IP string
38 | }
39 |
40 | // ToString returns a string representation of an HTTP request logged in the history
41 | func (r *Request) ToString() string {
42 | /*
43 | Metho Path Proto
44 | Host
45 | Headers
46 |
47 | Body
48 | */
49 | if r == nil {
50 | return ""
51 | }
52 | //u1 := fmt.Sprintf("%v", r.URL)
53 | ret := fmt.Sprintf("%s %s %s\nHost: %s\n", r.Method, r.URL.Path, r.Proto, r.Host)
54 | for k, v := range r.Headers {
55 | values := ""
56 | for _, s := range v {
57 | values = values + s
58 | }
59 | ret = ret + fmt.Sprintf("%s: %s\n", k, values)
60 | }
61 | if len(r.Body) > 0 {
62 | ret = ret + fmt.Sprintf("\n%s", string(r.Body))
63 | }
64 | return ret
65 | }
66 |
67 | // Response represents an HTTP response logged in the history
68 | type Response struct {
69 | ID int64
70 | Proto string
71 | Status string
72 | StatusCode int
73 | Headers http.Header
74 | ContentLength int64
75 | Body []byte
76 | }
77 |
78 | // ToString returns a string representation of an HTTP response logged in the history
79 | func (r *Response) ToString() string {
80 | /*
81 | Proto Status
82 | Headers
83 |
84 | Body
85 | */
86 | if r == nil {
87 | return ""
88 | }
89 | ret := fmt.Sprintf("%s %s\n", r.Proto, r.Status)
90 | for k, v := range r.Headers {
91 | values := ""
92 | for _, s := range v {
93 | values = values + s
94 | }
95 | ret = ret + fmt.Sprintf("%s: %s\n", k, values)
96 | }
97 | ret = ret + fmt.Sprintf("Content-Length: %d\n", r.ContentLength)
98 | if len(r.Body) > 0 {
99 | ret = ret + fmt.Sprintf("\n%s", string(r.Body))
100 | }
101 | return ret
102 | }
103 |
104 | // HTTPItem represent an item in the history table
105 | type HTTPItem struct {
106 | core.QObject
107 | ID int
108 | Req *Request
109 | Resp *Response
110 | EditedReq *Request
111 | EditedResp *Response
112 | }
113 |
114 | const (
115 | ID = iota
116 | Host
117 | Method
118 | Path
119 | Params
120 | Edit
121 | Status
122 | Length
123 | Ip
124 | )
125 |
126 | /*func (m *CustomTableModel) row(i *HTTPItem) int {
127 | for index, item := range m.modelData {
128 | if item.Pointer() == i.Pointer() {
129 | return index
130 | }
131 | }
132 | return 0
133 | }*/
134 |
135 | // CustomTableModel represents a table model used to populate the history QtTableView
136 | type CustomTableModel struct {
137 | core.QAbstractTableModel
138 | _ func() `constructor:"init"`
139 |
140 | //modelData []HTTPItem
141 | //hashMap map[int64]*HTTPItem
142 |
143 | /* _ func(item *HTTPItem, i int64) `signal:"addItem,auto"`
144 | _ func(item *HTTPItem, i int64) `signal:editItem,auto"`*/
145 | _ func() `signal:clearHistory,auto"`
146 | }
147 |
148 | var mutex = &sync.Mutex{}
149 |
150 | func (m *CustomTableModel) init() {
151 | //m.modelData = []HTTPItem{}
152 | //m.hashMap = make(map[int64]*HTTPItem)
153 | //HashMapHistory = make(map[int64]int)
154 |
155 | m.ConnectHeaderData(m.headerData)
156 | m.ConnectRowCount(m.rowCount)
157 | m.ConnectColumnCount(m.columnCount)
158 | m.ConnectData(m.data)
159 | }
160 |
161 | func (m *CustomTableModel) headerData(section int, orientation core.Qt__Orientation, role int) *core.QVariant {
162 | if role != int(core.Qt__DisplayRole) || orientation == core.Qt__Vertical {
163 | return m.HeaderDataDefault(section, orientation, role)
164 | }
165 | switch section {
166 | case ID:
167 | return core.NewQVariant1("ID")
168 | case Host:
169 | return core.NewQVariant1("Host")
170 | case Method:
171 | return core.NewQVariant1("Method")
172 | case Path:
173 | return core.NewQVariant1("Path")
174 | case Params:
175 | return core.NewQVariant1("Params")
176 | case Edit:
177 | return core.NewQVariant1("Edit")
178 | case Status:
179 | return core.NewQVariant1("Status")
180 | case Length:
181 | return core.NewQVariant1("Length")
182 | case Ip:
183 | return core.NewQVariant1("IP")
184 | }
185 | return core.NewQVariant()
186 | }
187 |
188 | // GetReqResp retursn request, response, edited request and edited response for a given context.ID
189 | func (m *CustomTableModel) GetReqResp(i int64) (*Request, *Request, *Response, *Response) {
190 | if val, ok := HashMapHistory[i]; ok {
191 | return History[val].Req, History[val].EditedReq, History[val].Resp, History[val].EditedResp
192 | }else{
193 | for row, item := range History{
194 | //fmt.Printf("ID: %d\n", item.ID)
195 | //fmt.Printf("i: %d\n", i)
196 | if item.ID == i{
197 | HashMapHistory[i] = row
198 | return History[row].Req, History[row].EditedReq, History[row].Resp, History[row].EditedResp
199 | }
200 | }
201 | }
202 | //fmt.Println("here")
203 | return nil, nil, nil, nil
204 | }
205 |
206 | func (m *CustomTableModel) clearHistory() {
207 | mutex.Lock()
208 | defer mutex.Unlock()
209 | /*m.BeginRemoveRows(core.NewQModelIndex(), 0, len(m.modelData))
210 | m.modelData = []HTTPItem{}
211 | m.hashMap = make(map[int64]*HTTPItem)
212 | m.EndRemoveRows()*/
213 | }
214 |
215 | // AddRequest adds a Request to the history
216 | func (m *CustomTableModel) AddRequest(r *Request, id int64){
217 | mutex.Lock()
218 | defer mutex.Unlock()
219 | m.BeginInsertRows(core.NewQModelIndex(), len(History), len(History))
220 | // create a new row with the request
221 | t := &Row{ID:id, Req:r}
222 | History = append(History, t)
223 | // save the i to a mapping with hasmap
224 | HashMapHistory[id] = len(History)-1
225 | m.EndInsertRows()
226 | }
227 |
228 | // AddEditedRequest adds an edited Request to the history
229 | func (m *CustomTableModel) AddEditedRequest(r *Request, id int64){
230 | mutex.Lock()
231 | defer mutex.Unlock()
232 | row := HashMapHistory[id]
233 | History[row].EditedReq = r
234 | m.DataChanged(m.Index(row, 2, core.NewQModelIndex()), m.Index(row, 2, core.NewQModelIndex()), []int{Edit, Status, Length})
235 | }
236 |
237 | // AddEditedResponse adds an edited Response to the history
238 | func (m *CustomTableModel) AddEditedResponse(r *Response, id int64){
239 | mutex.Lock()
240 | defer mutex.Unlock()
241 | row := HashMapHistory[id]
242 | History[row].EditedResp = r
243 | m.DataChanged(m.Index(row, 2, core.NewQModelIndex()), m.Index(row, 2, core.NewQModelIndex()), []int{Edit, Status, Length})
244 | }
245 |
246 | // AddResponse adds a Response to the history
247 | func (m *CustomTableModel) AddResponse(r *Response, id int64){
248 | mutex.Lock()
249 | defer mutex.Unlock()
250 | row := HashMapHistory[id]
251 | History[row].Resp = r
252 | m.DataChanged(m.Index(row, 2, core.NewQModelIndex()), m.Index(row, 2, core.NewQModelIndex()), []int{Edit, Status, Length})
253 | }
254 |
255 | /*func (m *CustomTableModel) addItem(item *HTTPItem, i int64) {
256 | mutex.Lock()
257 | defer mutex.Unlock()
258 | m.BeginInsertRows(core.NewQModelIndex(), len(m.modelData), len(m.modelData))
259 | m.hashMap[i] = item
260 | m.modelData = append(m.modelData, *item)
261 | m.EndInsertRows()
262 | }
263 |
264 | func (m *CustomTableModel) editItem(item *HTTPItem, i int64) {
265 | mutex.Lock()
266 | defer mutex.Unlock()
267 |
268 | row := m.row(m.hashMap[i])
269 |
270 | m.hashMap[i].Resp = item.Resp
271 | m.hashMap[i].EditedResp = item.EditedResp
272 |
273 | m.modelData[row].Resp = item.Resp
274 | m.modelData[row].EditedResp = item.EditedResp
275 |
276 | m.DataChanged(m.Index(row, 2, core.NewQModelIndex()), m.Index(row, 2, core.NewQModelIndex()), []int{Edit, Status, Length})
277 | }*/
278 |
279 | func (m *CustomTableModel) rowCount(*core.QModelIndex) int {
280 | return len(History)
281 | }
282 |
283 | func (m *CustomTableModel) columnCount(*core.QModelIndex) int {
284 | return 9
285 | }
286 | func (m *CustomTableModel) data(index *core.QModelIndex, role int) *core.QVariant {
287 | if role == int(core.Qt__TextAlignmentRole) &&
288 | (index.Column() == Method ||
289 | index.Column() == Params ||
290 | index.Column() == Edit ||
291 | index.Column() == Length) {
292 | return core.NewQVariant1(int64(core.Qt__AlignCenter))
293 | }
294 | if role != int(core.Qt__DisplayRole) {
295 | return core.NewQVariant()
296 | }
297 |
298 | item := History[index.Row()]
299 | switch index.Column() {
300 | case ID:
301 | return core.NewQVariant1(item.ID)
302 | case Host:
303 | return core.NewQVariant1(fmt.Sprintf("%s://%s",item.Req.URL.Scheme, item.Req.Host))
304 | case Method:
305 | return core.NewQVariant1(item.Req.Method)
306 | case Path:
307 | return core.NewQVariant1(item.Req.URL.Path)
308 | case Params:
309 | if item.Req.Params {
310 | return core.NewQVariant1("✓")
311 | }
312 | return core.NewQVariant1("")
313 | case Edit:
314 | if item.EditedReq != nil || item.EditedResp != nil {
315 | return core.NewQVariant1("✓")
316 | }
317 | return core.NewQVariant1("")
318 | case Status:
319 | if item.Resp != nil {
320 | return core.NewQVariant1(item.Resp.Status)
321 | }
322 | case Length:
323 | if item.Resp != nil {
324 | return core.NewQVariant1(fmt.Sprintf("%d", item.Resp.ContentLength))
325 | }
326 | case Ip:
327 | return core.NewQVariant1(item.Req.IP)
328 | }
329 | return core.NewQVariant()
330 | }
331 |
--------------------------------------------------------------------------------
/modules/coreproxy/model/sormodel.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "fmt"
5 | "regexp"
6 | "strconv"
7 | "strings"
8 | "github.com/therecipe/qt/core"
9 | )
10 |
11 | // SortFilterModel represent a sorted filter model to perform sorting and filtering of the history table
12 | type SortFilterModel struct {
13 | core.QSortFilterProxyModel
14 |
15 | Custom *CustomTableModel
16 |
17 | filter *Filter
18 |
19 | _ func() `constructor:"init"`
20 |
21 | _ func(column string, order core.Qt__SortOrder) `signal:"sortTableView"`
22 | }
23 |
24 | func (m *SortFilterModel) init() {
25 | m.Custom = NewCustomTableModel(nil)
26 |
27 | m.SetSourceModel(m.Custom)
28 | //m.SetSortRole(Time)
29 | //m.Sort(0, core.Qt__DescendingOrder)
30 |
31 | m.ConnectFilterAcceptsRow(m.filterAcceptsRow)
32 | m.ConnectSortTableView(m.sortTableView)
33 | }
34 |
35 | // SetFilter sets a filter on the model
36 | func (m *SortFilterModel) SetFilter(f *Filter) {
37 | m.filter = f
38 | m.InvalidateFilter()
39 | }
40 |
41 | func (m *SortFilterModel) GetRowId(r int) int64{
42 | return int64(m.Index(r, 0, core.NewQModelIndex()).Data(ID).ToInt(nil))
43 | }
44 |
45 | // ResetFilters remove all filters on the model
46 | func (m *SortFilterModel) ResetFilters() {
47 | m.InvalidateFilter()
48 | }
49 |
50 | func (m *SortFilterModel) filterAcceptsRow(sourceRow int, sourceParent *core.QModelIndex) bool {
51 |
52 | if m.filter == nil {
53 | return true
54 | }
55 |
56 | index := m.SourceModel().Index(sourceRow, 0, sourceParent)
57 | idStr := m.SourceModel().Data(index, 0).ToString()
58 | id, _ := strconv.Atoi(idStr)
59 |
60 | req, editedReq, resp, editedResp := m.Custom.GetReqResp(int64(id))
61 |
62 | if req == nil {
63 | return true
64 | }
65 |
66 | scopeCheck := false
67 | // scope
68 | if len(m.filter.Scope) > 0 && m.filter.ScopeOnly {
69 | for _, s := range m.filter.Scope{
70 | reg := fmt.Sprintf("^%s$", s)
71 | r, err := regexp.Compile(reg)
72 | if err != nil {
73 | // ignore if the scope is not a valid regexp
74 | continue
75 | }
76 | if r.MatchString(req.Host) {
77 | scopeCheck = true
78 | break
79 | }
80 | }
81 | if !scopeCheck {
82 | return false
83 | }
84 | }
85 |
86 | // extension
87 | showOnlyCheck := false
88 | if m.filter.Show {
89 | // show only this stuff
90 | for _, k := range m.filter.ShowExt{
91 | if req.Extension == k {
92 | showOnlyCheck = true
93 | break
94 | }
95 | }
96 | if !showOnlyCheck {
97 | return false
98 | }
99 | }
100 |
101 | if m.filter.Hide {
102 | // hide this stuff
103 | for _, k := range m.filter.HideExt{
104 | if req.Extension == k {
105 | return false
106 | }
107 | }
108 | }
109 |
110 |
111 | // response status
112 | next := false //IMP: make me pretier
113 | for _, i := range m.filter.StatusCode {
114 | if resp != nil && ((resp.StatusCode <= i+99 && resp.StatusCode >= i) || resp.StatusCode > 599) {
115 | next = true
116 | break
117 | }
118 | }
119 | if resp != nil && !next {
120 | return false
121 | }
122 |
123 | // text search filter
124 | txt := ""
125 | if req != nil {
126 | txt = req.ToString()
127 | }
128 | if editedReq != nil {
129 | txt = txt + editedReq.ToString()
130 | }
131 | if resp != nil {
132 | txt = txt + resp.ToString()
133 | }
134 | if editedResp != nil {
135 | txt = txt + editedResp.ToString()
136 | }
137 |
138 | if !strings.Contains(txt, m.filter.Search) {
139 | return false
140 | }
141 |
142 | return true
143 |
144 | }
145 |
146 | func (m *SortFilterModel) sortTableView(column string, order core.Qt__SortOrder) {
147 | for k, v := range m.Custom.RoleNames() {
148 | if v.ConstData() == column {
149 | m.SetSortRole(k)
150 | m.Sort(0, order)
151 | }
152 | }
153 | }
154 |
--------------------------------------------------------------------------------
/modules/log/log.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "github.com/rhaidiz/broxy/core"
5 | )
6 |
7 | // Log represents the log module
8 | type Log struct {
9 | core.Module
10 | }
11 |
12 | //var mutex = &sync.Mutex{}
13 |
14 | // NewLog creates a new log module
15 | func NewLog(s *core.Session) *Log {
16 | return &Log{}
17 | }
18 |
19 | // Name returns the name of the current module
20 | func (m *Log) Name() string {
21 | return "Log"
22 | }
23 |
--------------------------------------------------------------------------------
/modules/log/log_controller.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "fmt"
5 | "github.com/rhaidiz/broxy/core"
6 | "github.com/rhaidiz/broxy/modules/log/model"
7 | "github.com/rhaidiz/broxy/core/project/decoder"
8 | )
9 |
10 | // Controller represents the controller of the log module
11 | type Controller struct {
12 | core.ControllerModule
13 | Module *Log
14 | Gui *Gui
15 | Sess *core.Session
16 | encoder *decoder.Encoder
17 |
18 | //model *model.CustomTableModel
19 | modelSort *model.SortFilterModel
20 | }
21 |
22 | // NewController returns a controller of the log module
23 | func NewController(m *Log, g *Gui, s *core.Session) *Controller {
24 | c := &Controller{
25 | Module: m,
26 | Gui: g,
27 | Sess: s,
28 | }
29 |
30 | //c.model = model.NewCustomTableModel(nil)
31 | c.modelSort = model.NewSortFilterModel(nil)
32 |
33 | c.Gui.SetTableModel(c.modelSort)
34 |
35 | decoder, err := c.Sess.PersistentProject.FileDecoder2("logs")
36 | if err != nil {
37 | panic(fmt.Sprintf("Error while loading log file\n%s",err))
38 | }
39 | // load stuff
40 | for {
41 | l := &core.Log{}
42 | if err := decoder.Decode(&l); err != nil {
43 | break
44 | }
45 | c.modelSort.Custom.AddItem(*l)
46 | }
47 |
48 | encoder, err := c.Sess.PersistentProject.FileEncoder2("logs")
49 | if err != nil{
50 | panic(fmt.Sprintf("Error while loading log file\n%s",err))
51 | }
52 | c.encoder = &encoder
53 | go c.logEvent()
54 | return c
55 | }
56 |
57 | // GetGui returns the Gui of the log module
58 | func (c *Controller) GetGui() core.GuiModule {
59 | return c.Gui
60 | }
61 |
62 | // GetModule returns the module of the log module
63 | func (c *Controller) GetModule() core.Module {
64 | return c.Module
65 | }
66 |
67 | // ExecCommand execs commands submitted by other modules
68 | func (c *Controller) ExecCommand(m string, args ...interface{}) {
69 |
70 | }
71 |
72 | func (c *Controller) logEvent() {
73 | for l := range c.Sess.LogEvent {
74 | (*c.encoder).Encode(l)
75 | c.modelSort.Custom.AddItem(l)
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/modules/log/log_gui.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "github.com/rhaidiz/broxy/core"
5 | "github.com/rhaidiz/broxy/modules/log/model"
6 | qtcore "github.com/therecipe/qt/core"
7 | "github.com/therecipe/qt/quick"
8 | "github.com/therecipe/qt/widgets"
9 | )
10 |
11 | // Gui represents the Gui of the log module
12 | type Gui struct {
13 | core.GuiModule
14 |
15 | Sess *core.Session
16 | view *quick.QQuickView
17 | logTableView *widgets.QTableView
18 | }
19 |
20 | // NewGui returns a Gui of the main log module
21 | func NewGui(s *core.Session) *Gui {
22 | return &Gui{
23 | Sess: s,
24 | view: quick.NewQQuickView(nil),
25 | logTableView: widgets.NewQTableView(nil),
26 | }
27 | }
28 |
29 | func (g *Gui) GetSettings() interface{} {
30 | return nil
31 | }
32 | // SetTableModel sets the table model along with some column width to use in the history table
33 | func (g *Gui) SetTableModel(m *model.SortFilterModel) {
34 | g.logTableView.SetModel(m)
35 | g.logTableView.SetColumnWidth(model.Type, 50)
36 | g.logTableView.SetColumnWidth(model.Module, 100)
37 | g.logTableView.SetColumnWidth(model.Time, 150)
38 | g.logTableView.SetColumnWidth(model.Message, 200)
39 | }
40 |
41 | // GetModuleGui returns the Gui for the current module
42 | func (g *Gui) GetModuleGui() interface{} {
43 |
44 | widget := widgets.NewQWidget(nil, 0)
45 | widget.SetLayout(widgets.NewQVBoxLayout())
46 |
47 | g.view.SetTitle("Log table")
48 | g.view.SetResizeMode(quick.QQuickView__SizeRootObjectToView)
49 | g.logTableView.SetShowGrid(false)
50 | g.logTableView.VerticalHeader().Hide()
51 | g.logTableView.SetAlternatingRowColors(true)
52 | g.logTableView.SetEditTriggers(widgets.QAbstractItemView__NoEditTriggers)
53 | g.logTableView.SetSelectionBehavior(widgets.QAbstractItemView__SelectRows)
54 | g.logTableView.SetSelectionMode(widgets.QAbstractItemView__SingleSelection)
55 | g.logTableView.VerticalHeader().SetSectionResizeMode(widgets.QHeaderView__Fixed)
56 | g.logTableView.SetSortingEnabled(true)
57 | g.logTableView.VerticalHeader().SetDefaultSectionSize(10)
58 | g.logTableView.SortByColumn(model.Time, qtcore.Qt__DescendingOrder)
59 |
60 | widget.Layout().AddWidget(g.logTableView)
61 |
62 | return widget
63 | }
64 |
65 | // Title returns the time of this Gui
66 | func (g *Gui) Title() string {
67 | return "Log"
68 | }
69 |
--------------------------------------------------------------------------------
/modules/log/log_module.go:
--------------------------------------------------------------------------------
1 | package log
2 |
3 | import (
4 | "github.com/rhaidiz/broxy/core"
5 | )
6 |
7 | // LoadLogModule loads the log module in the given session
8 | func LoadLogModule(s *core.Session) *Controller {
9 | m := NewLog(s)
10 | g := NewGui(s)
11 | c := NewController(m, g, s)
12 | return c
13 | }
14 |
--------------------------------------------------------------------------------
/modules/log/model/model.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "sync"
5 |
6 | bcore "github.com/rhaidiz/broxy/core"
7 | "github.com/therecipe/qt/core"
8 | )
9 |
10 | const (
11 | Type = iota
12 | Module
13 | Time
14 | Message
15 | )
16 |
17 | // CustomTableModel represents a table model used to populate the log QtTableView
18 | type CustomTableModel struct {
19 | core.QAbstractTableModel
20 |
21 | modelData []bcore.Log
22 |
23 | _ func() `constructor:"init"`
24 |
25 | _ func(item bcore.Log) `signal:"addItem,auto"`
26 | }
27 |
28 | var mutex = &sync.Mutex{}
29 |
30 | func (m *CustomTableModel) init() {
31 | m.modelData = []bcore.Log{}
32 |
33 | m.ConnectRowCount(m.rowCount)
34 | m.ConnectHeaderData(m.headerData)
35 | m.ConnectColumnCount(m.columnCount)
36 | m.ConnectData(m.data)
37 | }
38 |
39 | func (m *CustomTableModel) addItem(item bcore.Log) {
40 | mutex.Lock()
41 | defer mutex.Unlock()
42 | m.BeginInsertRows(core.NewQModelIndex(), len(m.modelData), len(m.modelData))
43 | m.modelData = append(m.modelData, item)
44 | m.EndInsertRows()
45 | }
46 |
47 | func (m *CustomTableModel) rowCount(*core.QModelIndex) int {
48 | return len(m.modelData)
49 | }
50 |
51 | func (m *CustomTableModel) columnCount(*core.QModelIndex) int {
52 | return 4
53 | }
54 |
55 | func (m *CustomTableModel) headerData(section int, orientation core.Qt__Orientation, role int) *core.QVariant {
56 | if role != int(core.Qt__DisplayRole) || orientation == core.Qt__Vertical {
57 | return m.HeaderDataDefault(section, orientation, role)
58 | }
59 | switch section {
60 | case Type:
61 | return core.NewQVariant1("Type")
62 | case Module:
63 | return core.NewQVariant1("Module")
64 | case Time:
65 | return core.NewQVariant1("Time")
66 | case Message:
67 | return core.NewQVariant1("Message")
68 | }
69 | return core.NewQVariant()
70 | }
71 |
72 | func (m *CustomTableModel) data(index *core.QModelIndex, role int) *core.QVariant {
73 | if role == int(core.Qt__TextAlignmentRole) &&
74 | (index.Column() == Type) {
75 | return core.NewQVariant1(int64(core.Qt__AlignCenter))
76 | }
77 | if role != int(core.Qt__DisplayRole) {
78 | return core.NewQVariant()
79 | }
80 | item := m.modelData[index.Row()]
81 | switch index.Column() {
82 | case Type:
83 | return core.NewQVariant1(item.Type)
84 | case Module:
85 | return core.NewQVariant1(item.ModuleName)
86 | case Time:
87 | return core.NewQVariant1(item.Time)
88 | case Message:
89 | return core.NewQVariant1(item.Message)
90 | }
91 | return core.NewQVariant()
92 | }
93 |
--------------------------------------------------------------------------------
/modules/log/model/sortmodel.go:
--------------------------------------------------------------------------------
1 | package model
2 |
3 | import (
4 | "github.com/therecipe/qt/core"
5 | )
6 |
7 | // SortFilterModel represent a sorted filter model to perform sorting and filtering of the log table
8 | type SortFilterModel struct {
9 | core.QSortFilterProxyModel
10 |
11 | Custom *CustomTableModel
12 |
13 | _ func() `constructor:"init"`
14 |
15 | _ func(column string, order core.Qt__SortOrder) `signal:"sortTableView"`
16 | }
17 |
18 | func (m *SortFilterModel) init() {
19 | m.Custom = NewCustomTableModel(nil)
20 |
21 | m.SetSourceModel(m.Custom)
22 | // m.SetSortRole(Time)
23 | // m.Sort(0, core.Qt__DescendingOrder)
24 |
25 | m.ConnectSortTableView(m.sortTableView)
26 | //return SortFilterModel.QAbstractItemModel_PTR()
27 | }
28 |
29 | func (m *SortFilterModel) sortTableView(column string, order core.Qt__SortOrder) {
30 | for k, v := range m.Custom.RoleNames() {
31 | if v.ConstData() == column {
32 | m.SetSortRole(k)
33 | m.Sort(0, order)
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/modules/module.go:
--------------------------------------------------------------------------------
1 | package modules
2 |
3 | import (
4 | "github.com/rhaidiz/broxy/core"
5 | "github.com/rhaidiz/broxy/modules/coreproxy"
6 | "github.com/rhaidiz/broxy/modules/log"
7 | "github.com/rhaidiz/broxy/modules/repeater"
8 | )
9 |
10 | // LoadModules loads all the main modules
11 | func LoadModules(s *core.Session) {
12 | s.LoadModule(log.LoadLogModule(s))
13 | s.LoadModule(repeater.LoadRepeaterModule(s))
14 | s.LoadModule(coreproxy.LoadCoreProxyModule(s))
15 | }
16 |
--------------------------------------------------------------------------------
/modules/repeater/repeater.go:
--------------------------------------------------------------------------------
1 | package repeater
2 |
3 | import (
4 | "crypto/tls"
5 | "net/http"
6 |
7 | "github.com/rhaidiz/broxy/core"
8 | )
9 |
10 | // Repeater represents the repeater module
11 | type Repeater struct {
12 | core.Module
13 |
14 | Gui *core.GuiModule
15 | Sess *core.Session
16 |
17 | client *http.Client
18 | }
19 |
20 | // NewRepeater returns a new repeater module
21 | func NewRepeater(s *core.Session) *Repeater {
22 | // disable x509 certificate check
23 | http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
24 | return &Repeater{Sess: s, client: &http.Client{
25 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
26 | return http.ErrUseLastResponse
27 | },
28 | },
29 | }
30 | }
31 |
32 | // Name returns the name of the current module
33 | func (r *Repeater) Name() string {
34 | return "Repeater"
35 | }
36 |
37 | // Description returns the description of the current module
38 | func (r *Repeater) Description() string {
39 | return "This is the magical repeater"
40 | }
41 |
42 | // RunRequest performs the given HTTP request and return the HTTP response
43 | func (r *Repeater) RunRequest(req *http.Request) (*http.Response, error) {
44 | //TODO: I might need to use the configuration stored in session
45 | return r.client.Do(req)
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/modules/repeater/repeater_controller.go:
--------------------------------------------------------------------------------
1 | package repeater
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "net/http"
7 | "net/url"
8 | "strings"
9 | "time"
10 |
11 | "github.com/rhaidiz/broxy/core"
12 | "github.com/rhaidiz/broxy/core/project/decoder"
13 | "github.com/rhaidiz/broxy/modules/coreproxy/model"
14 | "github.com/rhaidiz/broxy/util"
15 | )
16 |
17 | // Controller represents the controller of the repeater module
18 | type Controller struct {
19 | core.ControllerModule
20 | Module *Repeater
21 | Gui *Gui
22 | Sess *core.Session
23 | Tabs map[int]*Tab
24 | }
25 |
26 | // Tab describes a tab
27 | type Tab struct {
28 | ID int
29 | Title string
30 | Path string
31 | history []*TabContent
32 | encoder *decoder.Encoder
33 | }
34 |
35 | // TabContent describes the content of a tab
36 | type TabContent struct {
37 | Host string
38 | Timestamp int64
39 | Request string
40 | Response string
41 | }
42 |
43 | // Entry describes one entry of the textfile containing the history
44 | type Entry struct {
45 | ID int
46 | Timestamp int64
47 | Type string
48 | Data []byte
49 | Host string
50 | }
51 |
52 | // NewController creates a new controller for the repeater module
53 | func NewController(module *Repeater, gui *Gui, s *core.Session) *Controller {
54 |
55 | c := &Controller{
56 | Module: module,
57 | Gui: gui,
58 | Sess: s,
59 | Tabs: make(map[int]*Tab),
60 | }
61 | tabNum = 1
62 | c.Gui.GoClick = c.GoClick
63 | c.Gui.NewTabEvent = c.NewTab
64 | c.Gui.Load = c.load
65 | c.Gui.RemoveTabEvent = c.removeTab
66 | c.Gui.GetStuff = c.getReqResp
67 | c.Gui.ChangeTabName = c.changeTabName
68 | return c
69 | }
70 |
71 | func (c *Controller) removeTab(id int){
72 | delete(c.Tabs, id)
73 | c.Sess.PersistentProject.SaveSettings("repeater", c.Tabs)
74 | c.Sess.PersistentProject.DeleteFile(fmt.Sprintf("tab_%d", id))
75 | }
76 |
77 | func (c *Controller) load(){
78 | // load settings
79 | var err error
80 | err = c.Sess.PersistentProject.LoadSettings("repeater", &c.Tabs)
81 | if err != nil {
82 | panic(fmt.Sprintf("Error while loading the repeater: %s", err))
83 | }
84 | for _,t := range c.Tabs{
85 | requestDec, err := c.Sess.PersistentProject.FileDecoder2(fmt.Sprintf("tab_%s", t.Path))
86 | if err != nil {
87 | // this if is meant to make sure that if there's an entry in the settings file
88 | // but no file associated, that tab is removed
89 | delete(c.Tabs, t.ID)
90 | err = c.Sess.PersistentProject.SaveSettings("repeater", c.Tabs)
91 | if err != nil {
92 | panic(fmt.Sprintf("Error while loading the repeater: %s", err))
93 | }
94 | continue
95 | }
96 | if t.ID > tabNum {
97 | tabNum = t.ID + 1
98 | }
99 | // load an encoder for this tab
100 | requestsEnc, err := c.Sess.PersistentProject.FileEncoder2(fmt.Sprintf("tab_%s", t.Path))
101 | if err != nil {
102 | panic(fmt.Sprintf("Error while loading the repeater: %s", err))
103 | }
104 | t.encoder = &requestsEnc
105 | for {
106 | e := &Entry{}
107 | if err := requestDec.Decode(&e); err != nil {
108 | break
109 | }
110 | if e.Type == "req"{
111 | // I'm reading a request
112 | if e.ID > len(t.history) - 1 {
113 | // first time I'm seeing this request
114 | tc := &TabContent{}
115 | tc.Host = e.Host
116 | tc.Request = string(e.Data)
117 | tc.Timestamp = e.Timestamp
118 | t.history = append(t.history, tc)
119 | }else{
120 | // second time I'm seeing this request, so overwrite.
121 | // this actually shoudn't happen, it's here just because shit happens
122 | req := string(e.Data)
123 | t.history[e.ID].Request = req
124 | t.history[e.ID].Host = e.Host
125 | }
126 | }else if e.Type == "resp" {
127 | // I'm reading a response
128 | resp := string(e.Data)
129 | t.history[e.ID].Response = resp
130 | }
131 | }
132 | c.new(t)
133 | }
134 | }
135 |
136 | // GetGui returns the Gui of the current controller
137 | func (c *Controller) GetGui() core.GuiModule {
138 | return c.Gui
139 | }
140 |
141 | // GetModule returns the module of the current controller
142 | func (c *Controller) GetModule() core.Module {
143 | return c.Module
144 | }
145 |
146 | func (c *Controller) NewTab(host, request string){
147 | t := &Tab{Title: fmt.Sprintf("%d",tabNum), ID: tabNum, Path: fmt.Sprintf("%d",tabNum)}
148 | tabContent := &TabContent{ Host: host, Request: request, Timestamp: time.Now().Unix()}
149 | t.history = append(t.history, tabContent)
150 | c.Tabs[tabNum] = t
151 | tabNum = tabNum + 1
152 | c.new(t)
153 | }
154 |
155 | // this method creates a new GUI tab based on a Tab struct
156 | func (c *Controller) new(t *Tab){
157 |
158 | if len(t.history) == 0 {
159 | t.history = append(t.history, &TabContent{})
160 | }
161 |
162 | lastItemIndex := len(t.history) - 1
163 | h := t.history[lastItemIndex].Host
164 | rq := t.history[lastItemIndex].Request
165 | rp := t.history[lastItemIndex].Response
166 |
167 | c.Gui.AddNewTab(t.Title, t.ID, h, rq, rp)
168 | for i, _ := range t.history {
169 | //for i := len(t.history)-1; i >= 0; i-- {
170 | tabContent := t.history[i]
171 | timeFormatted := time.Unix(tabContent.Timestamp, 0).Format("2006-01-02 15:04:05")
172 | c.Gui.AddToHistory(t.ID, i, fmt.Sprintf("%d. %s", i, timeFormatted ))
173 | }
174 | }
175 |
176 | func (c *Controller) getReqResp(idTab, idContent int)(string, string, string){
177 | t := c.Tabs[idTab].history[idContent]
178 | return t.Host, t.Request, t.Response
179 | }
180 |
181 |
182 | // ExecCommand execs commands submitted by other modules
183 | func (c *Controller) ExecCommand(m string, args ...interface{}) {
184 | if m == "send-to" {
185 | r := args[0].(*model.Request)
186 | //c.Gui.AddNewTab(fmt.Sprintf("%s://%s", r.URL.Scheme, r.Host), fmt.Sprintf("%s\n", r.ToString()))
187 | c.NewTab(fmt.Sprintf("%s://%s", r.URL.Scheme, r.Host), fmt.Sprintf("%s\n", r.ToString()))
188 |
189 | }
190 | }
191 |
192 | func (c *Controller) changeTabName(id int,s string){
193 | c.Tabs[id].Title = s
194 | c.Sess.PersistentProject.SaveSettings("repeater", c.Tabs)
195 | }
196 |
197 | // GoClick is the event fired when clicking the Go button in a repeater tab
198 | //func (c *Controller) GoClick(t *TabGui) {
199 | func (c *Controller) GoClick(id int, host, request string, ch chan string) {
200 | t := c.Tabs[id]
201 |
202 | rRaw := util.NormalizeRequest(request)
203 |
204 | r := strings.NewReader(rRaw)
205 | buf := bufio.NewReader(r)
206 |
207 | req, err := http.ReadRequest(buf)
208 | if err != nil {
209 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("ReadRequest %v", err))
210 | return
211 | }
212 |
213 | var tabContent *TabContent
214 | tabContent = &TabContent{ Host: host, Request: rRaw }
215 |
216 | timestamp := time.Now().Unix()
217 | timeFormatted := time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
218 |
219 | if t.history[0].Response == "" {
220 | // the tab has no history so it's a new thing to save to file
221 | // save c.Tabs to file as settings
222 | c.Sess.PersistentProject.SaveSettings("repeater", c.Tabs)
223 |
224 | requestsEnc, err := c.Sess.PersistentProject.FileEncoder2(fmt.Sprintf("tab_%d", t.ID))
225 | if err != nil {
226 | panic("Error while saving repeater history")
227 | }
228 | t.encoder = &requestsEnc
229 |
230 | t.history[0] = tabContent
231 | }else{
232 | t.history = append(t.history, tabContent)
233 | // I'm duplicating this part but whatever
234 | entryId := len(t.history) - 1
235 | c.Gui.AddToHistory(t.ID, entryId, fmt.Sprintf("%d. %s", entryId, timeFormatted))
236 | }
237 |
238 | entryId := len(t.history) - 1
239 | e := &Entry{ID: entryId, Type:"req", Host: host, Data: []byte(rRaw), Timestamp: timestamp}
240 | (*t.encoder).Encode(e)
241 |
242 | c.Sess.Debug(c.Module.Name(), req.Host)
243 |
244 | url, err := url.Parse(host)
245 | req.URL.Scheme = url.Scheme
246 | req.URL.Host = url.Host
247 | req.RequestURI = ""
248 |
249 | go func(i int, t *Tab, ch chan string) {
250 | resp, err := c.Module.RunRequest(req)
251 | var respRaw string
252 | if err != nil {
253 | c.Sess.Err(c.Module.Name(), fmt.Sprintf("RunRequest %v", err))
254 | } else {
255 | respRaw = util.ResponseToString(resp, false)
256 | ch <- respRaw
257 | }
258 | t.history[i].Response = respRaw
259 |
260 | entry := &Entry{ID: i, Data: []byte(respRaw), Type: "resp" }
261 | (*t.encoder).Encode(entry)
262 |
263 | }(entryId, t, ch)
264 |
265 | }
266 |
--------------------------------------------------------------------------------
/modules/repeater/repeater_gui.go:
--------------------------------------------------------------------------------
1 | package repeater
2 |
3 | import (
4 | "strconv"
5 | "fmt"
6 | "regexp"
7 | "github.com/rhaidiz/broxy/core"
8 | qtcore "github.com/therecipe/qt/core"
9 | "github.com/therecipe/qt/widgets"
10 | )
11 |
12 | var tabNum int
13 |
14 | // Gui represents the Gui of the repeater module
15 | type Gui struct {
16 | core.GuiModule
17 | Sess *core.Session
18 |
19 | repeaterTabs *widgets.QTabWidget
20 | tabs map[int]*TabGui
21 | tabsMapping map[int]int
22 | tabNum int
23 | tabRemoved bool
24 |
25 | //GoClick func(*TabGui)
26 | GoClick func(int, string, string, chan string)
27 | ChangeTabName func(int, string)
28 | NewTabEvent func(string, string)
29 | RemoveTabEvent func(int)
30 | Load func()
31 | GetStuff func(int, int)(string, string, string)
32 | _ func(i int) `signal:"changedTab"`
33 | }
34 |
35 | // Tab represents a tab in the repeater module
36 | type TabGui struct {
37 | id int
38 | goBtn *widgets.QPushButton
39 | cancelBtn *widgets.QPushButton
40 | historyPrev *widgets.QPushButton
41 | historyNext *widgets.QPushButton
42 | changeTabName *widgets.QPushButton
43 | HostLine *widgets.QLineEdit
44 | TabLine *widgets.QLineEdit
45 | RequestEditor *widgets.QPlainTextEdit
46 | ResponseEditor *widgets.QPlainTextEdit
47 | ComboHistory *widgets.QComboBox
48 | history []*tabHistory
49 | }
50 |
51 | type tabHistory struct {
52 | id int
53 | }
54 |
55 | // NewGui creates a new Gui for the repeater module
56 | func NewGui(s *core.Session) *Gui {
57 | tabNum = 1
58 | return &Gui{Sess: s, tabNum: 1, tabRemoved: false, tabs: make(map[int]*TabGui), tabsMapping: make(map[int]int) }
59 | }
60 |
61 | func (g *Gui) GetSettings() interface{} {
62 | return nil
63 | }
64 |
65 | // GetModuleGui returns the Gui for the current module
66 | func (g *Gui) GetModuleGui() interface{} {
67 |
68 | g.repeaterTabs = widgets.NewQTabWidget(nil)
69 | g.Load()
70 | g.repeaterTabs.SetDocumentMode(true)
71 | g.repeaterTabs.SetTabsClosable(true)
72 | g.repeaterTabs.ConnectTabCloseRequested(g.handleClose)
73 | g.repeaterTabs.ConnectCurrentChanged(g.changedTab)
74 | //g.repeaterTabs.AddTab(g.NewTab(), strconv.Itoa(g.tabNum))
75 | g.repeaterTabs.AddTab(widgets.NewQWidget(nil, 0), "+")
76 | // the following line is to remove the closable button from the last tab
77 | g.repeaterTabs.TabBar().SetTabButton(g.repeaterTabs.Count()-1, widgets.QTabBar__LeftSide, nil) //.Hide()
78 |
79 | return g.repeaterTabs
80 |
81 | }
82 |
83 | func (g *Gui) handleClose(index int) {
84 | w := g.repeaterTabs.Widget(index)
85 | idLabel := widgets.NewQLabelFromPointer(w.FindChild("mylabel", qtcore.Qt__FindChildrenRecursively).Pointer())
86 | id, _ := strconv.Atoi(idLabel.Text())
87 |
88 | delete(g.tabs, id)
89 | g.tabRemoved = true
90 | g.RemoveTabEvent(id)
91 | g.repeaterTabs.RemoveTab(index)
92 |
93 | }
94 |
95 | func (g *Gui) changedTab(i int) {
96 | if i == g.repeaterTabs.Count()-1 && g.tabRemoved && g.repeaterTabs.Count() > 1 {
97 | g.repeaterTabs.SetCurrentIndex(i - 1)
98 | } else if i == g.repeaterTabs.Count()-1 {
99 | // This branch runs only when a new tab is added with the + button
100 | // or the first time I load the interface
101 | g.NewTabEvent("","")
102 | }
103 | g.tabRemoved = false
104 | }
105 |
106 | // AddNewTab adds a new repeater tab
107 | func (g *Gui) AddNewTab(title string, id int, host, request, response string) {
108 | g.repeaterTabs.InsertTab(g.repeaterTabs.Count()-1, g.NewTab(title, id, host, request, response), title)
109 | g.repeaterTabs.SetCurrentIndex(g.repeaterTabs.Count() - 2)
110 | }
111 |
112 | // NewTab adds a new tab
113 | func (g *Gui) NewTab(title string, id int, host, request, response string) widgets.QWidget_ITF {
114 | t := &TabGui{id: id}
115 | g.tabs[id] = t
116 |
117 | var label = widgets.NewQLabel(nil, 0)
118 | label.SetText(fmt.Sprintf("%d", id))
119 | label.SetObjectName("mylabel")
120 | label.SetVisible(false)
121 |
122 | mainWidget := widgets.NewQWidget(nil, 0)
123 | vlayout := widgets.NewQVBoxLayout()
124 | vlayout.SetContentsMargins(11, 11, 11, 11)
125 |
126 | vlayout.AddWidget(label, 0, 0)
127 | mainWidget.SetLayout(vlayout)
128 |
129 | hlayout_tab_name := widgets.NewQHBoxLayout()
130 |
131 | t.changeTabName = widgets.NewQPushButton2("Change", nil)
132 | t.changeTabName.ConnectClicked(func(b bool) {
133 | newTabName := t.TabLine.Text()
134 | // delete(g.tabs, tabLabel)
135 | // g.tabs[newTabName] = t
136 | g.repeaterTabs.SetTabText(g.repeaterTabs.CurrentIndex(), newTabName)
137 | g.ChangeTabName(id, newTabName)
138 | } )
139 |
140 | t.TabLine = widgets.NewQLineEdit(nil)
141 |
142 | hlayout_tab_name.AddWidget(t.changeTabName, 0, 0)
143 | hlayout_tab_name.AddWidget(t.TabLine, 0, 0)
144 |
145 | vlayout.AddLayout(hlayout_tab_name, 0)
146 |
147 | hlayout := widgets.NewQHBoxLayout()
148 |
149 | t.goBtn = widgets.NewQPushButton2("Go", nil)
150 | t.cancelBtn = widgets.NewQPushButton2("Cancel", nil)
151 | t.goBtn.ConnectClicked(func(b bool) {
152 | c := make(chan string)
153 | request := t.RequestEditor.ToPlainText()
154 | var re = regexp.MustCompile(`(?mi)[\r\n]+^accept-encoding:.*$`)
155 | s := re.ReplaceAllString(request, ``)
156 | t.RequestEditor.SetPlainText(s)
157 | host := t.HostLine.Text()
158 | go g.GoClick(id, host, s, c)
159 | go func(){
160 | for resp := range c{
161 | t.ResponseEditor.SetPlainText(resp)
162 | }
163 | }()
164 | })
165 | hlayout.AddWidget(t.goBtn, 0, 0)
166 | hlayout.AddWidget(t.cancelBtn, 0, 0)
167 |
168 | t.HostLine = widgets.NewQLineEdit(nil)
169 | t.HostLine.SetText(host)
170 | hlayout.AddWidget(t.HostLine, 0, 0)
171 |
172 | t.ComboHistory = widgets.NewQComboBox(nil)
173 | t.ComboHistory.AddItems([]string{
174 | })
175 | t.ComboHistory.ConnectCurrentIndexChanged(func(i int){
176 | if len(t.history) > 0 {
177 | id := t.history[i].id
178 | host, req, resp := g.GetStuff(t.id, id)
179 | t.HostLine.SetText(host)
180 | t.RequestEditor.SetPlainText(req)
181 | t.ResponseEditor.SetPlainText(resp)
182 | }
183 | })
184 |
185 | t.historyPrev = widgets.NewQPushButton2("<", nil)
186 | t.historyNext = widgets.NewQPushButton2(">", nil)
187 |
188 | t.historyPrev.ConnectClicked(func(b bool) {
189 | newIndex := t.ComboHistory.CurrentIndex() - 1
190 | if newIndex >= 0 {
191 | t.ComboHistory.SetCurrentIndex(newIndex)
192 | }
193 | })
194 | t.historyNext.ConnectClicked(func(b bool) {
195 | newIndex := t.ComboHistory.CurrentIndex() + 1
196 | total := t.ComboHistory.Count()
197 | if newIndex < total {
198 | t.ComboHistory.SetCurrentIndex(newIndex)
199 | }
200 | })
201 |
202 | hlayout.AddWidget(t.historyPrev, 0, 0)
203 | hlayout.AddWidget(t.historyNext, 0, 0)
204 | hlayout.AddWidget(t.ComboHistory, 0, 0)
205 |
206 | vlayout.AddLayout(hlayout, 0)
207 |
208 | splitter := widgets.NewQSplitter(nil)
209 | splitter.SetOrientation(qtcore.Qt__Horizontal)
210 |
211 | t.RequestEditor = widgets.NewQPlainTextEdit(nil)
212 | t.RequestEditor.SetPlainText(request)
213 | t.ResponseEditor = widgets.NewQPlainTextEdit(nil)
214 | t.ResponseEditor.SetReadOnly(true)
215 | t.ResponseEditor.SetPlainText(response)
216 | splitter.AddWidget(t.RequestEditor)
217 | splitter.AddWidget(t.ResponseEditor)
218 |
219 | vlayout.AddWidget(splitter, 0, 0)
220 | return mainWidget
221 | }
222 |
223 | func (g *Gui) AddToHistory(tabId int, idTabContent int, label string) {
224 | t := g.tabs[tabId]
225 | t.ComboHistory.AddItem(label, qtcore.NewQVariant())
226 | h := &tabHistory{ id: idTabContent }
227 | t.history = append(t.history, h)
228 | newIndex := t.ComboHistory.Count() - 1
229 | t.ComboHistory.SetCurrentIndex(newIndex)
230 | }
231 |
232 | // Title returns the time of this Gui
233 | func (g *Gui) Title() string {
234 | return "Repeater"
235 | }
236 |
--------------------------------------------------------------------------------
/modules/repeater/repeater_module.go:
--------------------------------------------------------------------------------
1 | package repeater
2 |
3 | import (
4 | "github.com/rhaidiz/broxy/core"
5 | )
6 |
7 | // LoadRepeaterModule loads the repeater module in the given session
8 | func LoadRepeaterModule(s *core.Session) *Controller {
9 | m := NewRepeater(s)
10 | g := NewGui(s)
11 | c := NewController(m, g, s)
12 | return c
13 | }
14 |
--------------------------------------------------------------------------------
/util/util.go:
--------------------------------------------------------------------------------
1 | package util
2 |
3 | import (
4 | "os"
5 | "bytes"
6 | "fmt"
7 | "io"
8 | "io/ioutil"
9 | "net/http"
10 | "os/user"
11 | "path/filepath"
12 | "reflect"
13 | "regexp"
14 | "runtime"
15 | "strings"
16 | )
17 |
18 | // RequestsEquals returns if two requests are equal
19 | func RequestsEquals(r1 *http.Request, r2 *http.Request) bool {
20 | if r1 == nil || r2 == nil {
21 | return false
22 | }
23 | if r1.Method != r2.Method || r1.URL.Path != r2.URL.Path || r1.Host != r2.Host {
24 | return false
25 | }
26 | if !reflect.DeepEqual(r1.Header, r2.Header) {
27 | return false
28 | }
29 |
30 | return bodyEquals(&r1.Body, &r2.Body)
31 |
32 | }
33 |
34 | // ResponsesEquals returns if two responses are equal
35 | func ResponsesEquals(r1 *http.Response, r2 *http.Response) bool {
36 | if r1 == nil || r2 == nil {
37 | return false
38 | }
39 | if r1.Status != r2.Status || r1.StatusCode != r2.StatusCode || r1.Proto != r2.Proto {
40 | return false
41 | }
42 | if !reflect.DeepEqual(r1.Header, r2.Header) {
43 | return false
44 | }
45 |
46 | return bodyEquals(&r1.Body, &r2.Body)
47 | }
48 |
49 | func bodyEquals(r1 *io.ReadCloser, r2 *io.ReadCloser) bool {
50 |
51 | var bodyBytes1 []byte
52 | var bodyBytes2 []byte
53 |
54 | bodyBytes1, _ = ioutil.ReadAll(*r1)
55 | *r1 = ioutil.NopCloser(bytes.NewBuffer(bodyBytes1))
56 | body1 := string(bodyBytes1)
57 |
58 | bodyBytes2, _ = ioutil.ReadAll(*r2)
59 | *r2 = ioutil.NopCloser(bytes.NewBuffer(bodyBytes2))
60 | body2 := string(bodyBytes2)
61 |
62 | return body1 == body2
63 | }
64 |
65 | // NormalizeRequest adds missing headers to a request
66 | func NormalizeRequest(rawReq string) string {
67 | a := regexp.MustCompile(`\n\n`)
68 | s := a.Split(rawReq, 2)
69 | if len(s) == 2 {
70 | cL := len(s[1])
71 | if cL == 0 {
72 | return rawReq
73 | }
74 | h := strings.Split(s[0], "\n")
75 | newHeader := ""
76 | for _, v := range h {
77 | if !strings.HasPrefix(v, "Content-Length") {
78 | newHeader = newHeader + v + "\n"
79 | }
80 | }
81 | newReqRaw := fmt.Sprintf("%s%s%d\n\n%s", newHeader, "Content-Length: ", cL, s[1])
82 | return newReqRaw
83 | }
84 | return rawReq
85 | }
86 |
87 | // RequestToString returns a string representation of a given HTTP request
88 | func RequestToString(r *http.Request) string {
89 | if r == nil {
90 | return ""
91 | }
92 | ret := fmt.Sprintf("%s %s %s\nHost: %s\n", r.Method, r.URL.Path, r.Proto, r.Host)
93 | for k, v := range r.Header {
94 | values := ""
95 | for _, s := range v {
96 | values = values + s
97 | }
98 | ret = ret + fmt.Sprintf("%s: %s\n", k, values)
99 | }
100 | bodyBytes, _ := ioutil.ReadAll(r.Body)
101 | r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
102 | if len(bodyBytes) > 0 {
103 | ret = ret + fmt.Sprintf("\n%s", string(bodyBytes))
104 | }
105 | return ret
106 | }
107 |
108 | // ResponseToString returns a string representation of a given HTTP response
109 | func ResponseToString(r *http.Response, responseBodyBytes bool) string {
110 | if r == nil {
111 | return ""
112 | }
113 | ret := fmt.Sprintf("%s %s\n", r.Proto, r.Status)
114 | for k, v := range r.Header {
115 | values := ""
116 | for _, s := range v {
117 | values = values + s
118 | }
119 | ret = ret + fmt.Sprintf("%s: %s\n", k, values)
120 | }
121 | //ret = ret + fmt.Sprintf("Content-Length: %v\n", r.ContentLength)
122 | bodyBytes, _ := ioutil.ReadAll(r.Body)
123 | r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
124 |
125 | if len(bodyBytes) > 0 && !responseBodyBytes {
126 | ret = ret + fmt.Sprintf("\n%s", string(bodyBytes))
127 | } else {
128 | ret = ret + fmt.Sprintf("\n%x", bodyBytes)
129 | }
130 | return ret
131 | }
132 |
133 | // GetSettingsDir returns the path to the settings folder
134 | func GetSettingsDir() string {
135 |
136 | usr, err := user.Current()
137 | if err != nil {
138 | return "./"
139 | }
140 |
141 | if runtime.GOOS == "linux" {
142 | return filepath.Join(usr.HomeDir, ".config/broxy/")
143 | }
144 |
145 | if runtime.GOOS == "darwin" {
146 | return filepath.Join(usr.HomeDir, ".config/broxy/")
147 | }
148 |
149 | if runtime.GOOS == "windows" {
150 | return filepath.Join(usr.HomeDir, ".\\broxy\\")
151 | }
152 |
153 | return "./"
154 |
155 | }
156 |
157 | // GetTmpDir returns the path to a temporary folder
158 | func GetTmpDir() string {
159 | return os.TempDir()
160 | }
161 |
162 | func IsNil(i interface{}) bool {
163 | if i == nil {
164 | return true
165 | }
166 | switch reflect.TypeOf(i).Kind() {
167 | case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
168 | return reflect.ValueOf(i).IsNil()
169 | }
170 | return false
171 | }
172 |
--------------------------------------------------------------------------------