├── .circleci
└── config.yml
├── .dockerignore
├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── cmd
└── root.go
├── docker
├── Dockerfile.build
├── Dockerfile.development
├── Dockerfile.example
├── Dockerfile.testing
├── entrypoint-development.sh
├── entrypoint-example.sh
├── entrypoint-testing.sh
├── etc
│ └── cron.d
│ │ └── changepwds
├── root
│ └── scripts
│ │ └── password_reset.py
└── var
│ └── spool
│ └── cron
│ └── crontabs
│ └── root
├── go.mod
├── go.sum
├── images
├── demo.gif
└── logo.svg
├── internal
├── config
│ └── config.go
├── fswatcher
│ ├── fswatcher.go
│ ├── fswatcher_test.go
│ ├── inotify
│ │ ├── event.go
│ │ ├── inotify.go
│ │ ├── inotify_test.go
│ │ └── testdata
│ │ │ └── folder
│ │ │ └── .keep
│ └── walker
│ │ ├── testdata
│ │ ├── f11.txt
│ │ ├── f12.txt
│ │ └── subdir
│ │ │ ├── f21.txt
│ │ │ └── subsubdir
│ │ │ └── f31.txt
│ │ ├── walker.go
│ │ └── walker_test.go
├── logging
│ ├── logging.go
│ └── logging_test.go
├── pspy
│ ├── pspy.go
│ └── pspy_test.go
└── psscanner
│ ├── proclist.go
│ ├── proclist_test.go
│ ├── psscanner.go
│ └── psscanner_test.go
└── main.go
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | docker:
5 | - image: docker:17.05.0-ce-git
6 | steps:
7 | - checkout
8 | - setup_remote_docker
9 | - run: docker build -f ./docker/Dockerfile.testing -t local/pspy-testing:latest .
10 | - run: docker run -it -e CC_TEST_REPORTER_ID=$CC_TEST_REPORTER_ID local/pspy-testing:latest
11 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .gitignore
2 | images/
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/*
2 |
3 |
4 | # Binaries for programs and plugins
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, build with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
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 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | PROJECT_DIR = $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
2 |
3 | BUILD_IMAGE = local/pspy-build:latest
4 | BUILD_DOCKERFILE = $(PROJECT_DIR)/docker/Dockerfile.build
5 |
6 | DEV_IMAGE = local/pspy-development:latest
7 | DEV_DOCKERFILE = $(PROJECT_DIR)/docker/Dockerfile.development
8 |
9 | TEST_IMAGE = local/pspy-testing:latest
10 | TEST_DOCKERFILE = $(PROJECT_DIR)/docker/Dockerfile.testing
11 |
12 | VERSION = `git describe --tags --always || echo "unknown"`
13 | BUILD_SHA = `git rev-parse HEAD || echo "unknown"`
14 |
15 | # Run unit test and integration test inside container
16 | test:
17 | docker build -f $(TEST_DOCKERFILE) -t $(TEST_IMAGE) .
18 | docker run -it --rm $(TEST_IMAGE)
19 |
20 | # Drops you into a shell in the development container and mounts the source code
21 | # You can edit to source on your host, then run go commans (e.g., `go test ./...`) inside the container
22 | dev:
23 | sh -c "if ! docker image ls | grep '$(DEV_IMAGE)' | cut -d ':' -f1; then echo 'building dev image'; docker build -f $(DEV_DOCKERFILE) -t $(DEV_IMAGE) .; fi"
24 | docker run -it \
25 | --rm \
26 | -v $(PROJECT_DIR):/go/src/github.com/dominicbreuker/pspy \
27 | -w "/go/src/github.com/dominicbreuker/pspy" \
28 | $(DEV_IMAGE)
29 |
30 | EXAMPLE_IMAGE = local/pspy-example:latest
31 | EXAMPLE_DOCKERFILE = $(PROJECT_DIR)/docker/Dockerfile.example
32 |
33 | # Run the example demonstrating what pspy does
34 | example:
35 | docker build -t $(EXAMPLE_IMAGE) -f $(EXAMPLE_DOCKERFILE) .
36 | docker run -it --rm $(EXAMPLE_IMAGE)
37 |
38 |
39 | # Build different binaries
40 | # builds binaries for both 32bit and 64bit systems
41 | # builds one set of static binaries that should work on any system without dependencies, but are huge
42 | # builds another set of binaries that are as small as possible, but may not work
43 | build:
44 | # sh -c "if ! docker image ls | grep '$(BUILD_IMAGE)' | cut -d ':' -f1; then echo 'building build image'; docker build -f $(BUILD_DOCKERFILE) -t $(BUILD_IMAGE) .; fi"
45 |
46 | mkdir -p $(PROJECT_DIR)/bin
47 | docker run -it \
48 | --rm \
49 | -v $(PROJECT_DIR):/go/src/github.com/dominicbreuker/pspy \
50 | -w "/go/src/github.com/dominicbreuker/pspy" \
51 | --env CGO_ENABLED=0 \
52 | --env GOOS=linux \
53 | --env GOARCH=386 \
54 | $(BUILD_IMAGE) /bin/sh -c "go build -a -ldflags '-s -w -X main.version=${VERSION} -X main.commit=${BUILD_SHA} -extldflags \"-static\"' -o bin/pspy32 main.go"
55 | docker run -it \
56 | --rm \
57 | -v $(PROJECT_DIR):/go/src/github.com/dominicbreuker/pspy \
58 | -w "/go/src/github.com/dominicbreuker/pspy" \
59 | --env CGO_ENABLED=0 \
60 | --env GOOS=linux \
61 | --env GOARCH=amd64 \
62 | $(BUILD_IMAGE) /bin/sh -c "go build -a -ldflags '-s -w -X main.version=${VERSION} -X main.commit=${BUILD_SHA} -extldflags \"-static\"' -o bin/pspy64 main.go"
63 | docker run -it \
64 | --rm \
65 | -v $(PROJECT_DIR):/go/src/github.com/dominicbreuker/pspy \
66 | -w "/go/src/github.com/dominicbreuker/pspy" \
67 | --env GOOS=linux \
68 | --env GOARCH=386 \
69 | $(BUILD_IMAGE) /bin/sh -c "go build -ldflags '-w -s -X main.version=${VERSION} -X main.commit=${BUILD_SHA}' -o bin/pspy32s main.go && upx bin/pspy32s"
70 | docker run -it \
71 | --rm \
72 | -v $(PROJECT_DIR):/go/src/github.com/dominicbreuker/pspy \
73 | -w "/go/src/github.com/dominicbreuker/pspy" \
74 | --env GOOS=linux \
75 | --env GOARCH=amd64 \
76 | $(BUILD_IMAGE) /bin/sh -c "go build -ldflags '-w -s -X main.version=${VERSION} -X main.commit=${BUILD_SHA}' -o bin/pspy64s main.go && upx bin/pspy64s"
77 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # pspy - unprivileged Linux process snooping
4 |
5 | [](https://goreportcard.com/report/github.com/DominicBreuker/pspy)
6 | [](https://codeclimate.com/github/DominicBreuker/pspy/maintainability)
7 | [](https://codeclimate.com/github/DominicBreuker/pspy/test_coverage)
8 | [](https://circleci.com/gh/DominicBreuker/pspy)
9 |
10 | pspy is a command line tool designed to snoop on processes without need for root permissions.
11 | It allows you to see commands run by other users, cron jobs, etc. as they execute.
12 | Great for enumeration of Linux systems in CTFs.
13 | Also great to demonstrate your colleagues why passing secrets as arguments on the command line is a bad idea.
14 |
15 | The tool gathers the info from procfs scans.
16 | Inotify watchers placed on selected parts of the file system trigger these scans to catch short-lived processes.
17 |
18 | ## Getting started
19 |
20 | ### Download
21 |
22 | Get the tool onto the Linux machine you want to inspect.
23 | First get the binaries. Download the released binaries here:
24 | - 32 bit big, static version: `pspy32` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy32)
25 | - 64 bit big, static version: `pspy64` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy64)
26 | - 32 bit small version: `pspy32s` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy32s)
27 | - 64 bit small version: `pspy64s` [download](https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy64s)
28 |
29 | The statically compiled files should work on any Linux system but are quite huge (~4MB).
30 | If size is an issue, try the smaller versions which depend on libc and are compressed with UPX (~1MB).
31 |
32 | ### Build
33 |
34 | Either use Go installed on your system or run the Docker-based build process which ran to create the release.
35 | For the latter, ensure Docker is installed, and then run `make build-build-image` to build a Docker image, followed by `make build` to build the binaries with it.
36 |
37 | You can run `pspy --help` to learn about the flags and their meaning.
38 | The summary is as follows:
39 | - -p: enables printing commands to stdout (enabled by default)
40 | - -f: enables printing file system events to stdout (disabled by default)
41 | - -r: list of directories to watch with Inotify. pspy will watch all subdirectories recursively (by default, watches /usr, /tmp, /etc, /home, /var, and /opt).
42 | - -d: list of directories to watch with Inotify. pspy will watch these directories only, not the subdirectories (empty by default).
43 | - -i: interval in milliseconds between procfs scans. pspy scans regularly for new processes regardless of Inotify events, just in case some events are not received.
44 | - -c: print commands in different colors. File system events are not colored anymore, commands have different colors based on process UID.
45 | - --debug: prints verbose error messages which are otherwise hidden.
46 |
47 | The default settings should be fine for most applications.
48 | Watching files inside `/usr` is most important since many tools will access libraries inside it.
49 |
50 | Some more complex examples:
51 |
52 | ```bash
53 | # print both commands and file system events and scan procfs every 1000 ms (=1sec)
54 | ./pspy64 -pf -i 1000
55 |
56 | # place watchers recursively in two directories and non-recursively into a third
57 | ./pspy64 -r /path/to/first/recursive/dir -r /path/to/second/recursive/dir -d /path/to/the/non-recursive/dir
58 |
59 | # disable printing discovered commands but enable file system events
60 | ./pspy64 -p=false -f
61 | ```
62 |
63 | ### Examples
64 |
65 | ### Cron job watching
66 |
67 | To see the tool in action, just clone the repo and run `make example` (Docker needed).
68 | It is known passing passwords as command line arguments is not safe, and the example can be used to demonstrate it.
69 | The command starts a Debian container in which a secret cron job, run by root, changes a user password every minute.
70 | pspy run in foreground, as user myuser, and scans for processes.
71 | You should see output similar to this:
72 |
73 | ```console
74 | ~/pspy (master) $ make example
75 | [...]
76 | docker run -it --rm local/pspy-example:latest
77 | [+] cron started
78 | [+] Running as user uid=1000(myuser) gid=1000(myuser) groups=1000(myuser),27(sudo)
79 | [+] Starting pspy now...
80 | Watching recursively : [/usr /tmp /etc /home /var /opt] (6)
81 | Watching non-recursively: [] (0)
82 | Printing: processes=true file-system events=false
83 | 2018/02/18 21:00:03 Inotify watcher limit: 524288 (/proc/sys/fs/inotify/max_user_watches)
84 | 2018/02/18 21:00:03 Inotify watchers set up: Watching 1030 directories - watching now
85 | 2018/02/18 21:00:03 CMD: UID=0 PID=9 | cron -f
86 | 2018/02/18 21:00:03 CMD: UID=0 PID=7 | sudo cron -f
87 | 2018/02/18 21:00:03 CMD: UID=1000 PID=14 | pspy
88 | 2018/02/18 21:00:03 CMD: UID=1000 PID=1 | /bin/bash /entrypoint.sh
89 | 2018/02/18 21:01:01 CMD: UID=0 PID=20 | CRON -f
90 | 2018/02/18 21:01:01 CMD: UID=0 PID=21 | CRON -f
91 | 2018/02/18 21:01:01 CMD: UID=0 PID=22 | python3 /root/scripts/password_reset.py
92 | 2018/02/18 21:01:01 CMD: UID=0 PID=25 |
93 | 2018/02/18 21:01:01 CMD: UID=??? PID=24 | ???
94 | 2018/02/18 21:01:01 CMD: UID=0 PID=23 | /bin/sh -c /bin/echo -e "KI5PZQ2ZPWQXJKEL\nKI5PZQ2ZPWQXJKEL" | passwd myuser
95 | 2018/02/18 21:01:01 CMD: UID=0 PID=26 | /usr/sbin/sendmail -i -FCronDaemon -B8BITMIME -oem root
96 | 2018/02/18 21:01:01 CMD: UID=101 PID=27 |
97 | 2018/02/18 21:01:01 CMD: UID=8 PID=28 | /usr/sbin/exim4 -Mc 1enW4z-00000Q-Mk
98 | ```
99 |
100 | First, pspy prints all currently running processes, each with PID, UID and the command line.
101 | When pspy detects a new process, it adds a line to this log.
102 | In this example, you find a process with PID 23 which seems to change the password of myuser.
103 | This is the result of a Python script used in roots private crontab `/var/spool/cron/crontabs/root`, which executes this shell command (check [crontab](docker/var/spool/cron/crontabs/root) and [script](docker/root/scripts/password_reset.py)).
104 | Note that myuser can neither see the crontab nor the Python script.
105 | With pspy, it can see the commands nevertheless.
106 |
107 | ### CTF example from Hack The Box
108 |
109 | Below is an example from the machine Shrek from [Hack The Box](https://www.hackthebox.eu/).
110 | In this CTF challenge, the task is to exploit a hidden cron job that's changing ownership of all files in a folder.
111 | The vulnerability is the insecure use of a wildcard together with chmod ([details](https://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt) for the interested reader).
112 | It requires substantial guesswork to find and exploit it.
113 | With pspy though, the cron job is easy to find and analyse:
114 |
115 | 
116 |
117 | ## How it works
118 |
119 | Tools exist to list all processes executed on Linux systems, including those that have finished.
120 | For instance there is [forkstat](http://smackerelofopinion.blogspot.de/2014/03/forkstat-new-tool-to-trace-process.html).
121 | It receives notifications from the kernel on process-related events such as fork and exec.
122 |
123 | These tools require root privileges, but that should not give you a false sense of security.
124 | Nothing stops you from snooping on the processes running on a Linux system.
125 | A lot of information is visible in procfs as long as a process is running.
126 | The only problem is you have to catch short-lived processes in the very short time span in which they are alive.
127 | Scanning the `/proc` directory for new PIDs in an infinite loop does the trick but consumes a lot of CPU.
128 |
129 | A stealthier way is to use the following trick.
130 | Process tend to access files such as libraries in `/usr`, temporary files in `/tmp`, log files in `/var`, ...
131 | Using the [inotify](http://man7.org/linux/man-pages/man7/inotify.7.html) API, you can get notifications whenever these files are created, modified, deleted, accessed, etc.
132 | Linux does not require priviledged users for this API since it is needed for many innocent applications (such as text editors showing you an up-to-date file explorer).
133 | Thus, while non-root users cannot monitor processes directly, they can monitor the effects of processes on the file system.
134 |
135 | We can use the file system events as a trigger to scan `/proc`, hoping that we can do it fast enough to catch the processes.
136 | This is what pspy does.
137 | There is no guarantee you won't miss one, but chances seem to be good in my experiments.
138 | In general, the longer the processes run, the bigger the chance of catching them is.
139 |
140 | # Misc
141 |
142 | Logo: "By Creative Tail [CC BY 4.0 (http://creativecommons.org/licenses/by/4.0)], via Wikimedia Commons" ([link](https://commons.wikimedia.org/wiki/File%3ACreative-Tail-People-spy.svg))
143 |
--------------------------------------------------------------------------------
/cmd/root.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | "os/signal"
8 | "syscall"
9 | "time"
10 |
11 | "github.com/dominicbreuker/pspy/internal/config"
12 | "github.com/dominicbreuker/pspy/internal/fswatcher"
13 | "github.com/dominicbreuker/pspy/internal/logging"
14 | "github.com/dominicbreuker/pspy/internal/pspy"
15 | "github.com/dominicbreuker/pspy/internal/psscanner"
16 | "github.com/spf13/cobra"
17 | )
18 |
19 | var banner = `
20 |
21 | ██▓███ ██████ ██▓███ ▓██ ██▓
22 | ▓██░ ██▒▒██ ▒ ▓██░ ██▒▒██ ██▒
23 | ▓██░ ██▓▒░ ▓██▄ ▓██░ ██▓▒ ▒██ ██░
24 | ▒██▄█▓▒ ▒ ▒ ██▒▒██▄█▓▒ ▒ ░ ▐██▓░
25 | ▒██▒ ░ ░▒██████▒▒▒██▒ ░ ░ ░ ██▒▓░
26 | ▒▓▒░ ░ ░▒ ▒▓▒ ▒ ░▒▓▒░ ░ ░ ██▒▒▒
27 | ░▒ ░ ░ ░▒ ░ ░░▒ ░ ▓██ ░▒░
28 | ░░ ░ ░ ░ ░░ ▒ ▒ ░░
29 | ░ ░ ░
30 | ░ ░
31 |
32 | `
33 |
34 | var helpText = `
35 | pspy monitors the system for file system events and new processes.
36 | It prints these envents to the console.
37 | File system events are monitored with inotify.
38 | Processes are monitored by scanning /proc, using file system events as triggers.
39 | pspy does not require root permissions do operate.
40 | Check out https://github.com/dominicbreuker/pspy for more information.
41 | `
42 |
43 | var rootCmd = &cobra.Command{
44 | Use: "pspy",
45 | Short: "pspy can watch your system for new processes and file system events",
46 | Long: banner,
47 | Run: root,
48 | }
49 |
50 | var logPS, logFS bool
51 | var rDirs, dirs []string
52 | var defaultRDirs = []string{
53 | "/usr",
54 | "/tmp",
55 | "/etc",
56 | "/home",
57 | "/var",
58 | "/opt",
59 | }
60 | var defaultDirs = []string{}
61 | var triggerInterval int
62 | var colored bool
63 | var debug bool
64 | var ppid bool
65 | var cmdLength int
66 |
67 | func init() {
68 | rootCmd.PersistentFlags().BoolVarP(&logPS, "procevents", "p", true, "print new processes to stdout")
69 | rootCmd.PersistentFlags().BoolVarP(&logFS, "fsevents", "f", false, "print file system events to stdout")
70 | rootCmd.PersistentFlags().StringArrayVarP(&rDirs, "recursive_dirs", "r", defaultRDirs, "watch these dirs recursively")
71 | rootCmd.PersistentFlags().StringArrayVarP(&dirs, "dirs", "d", defaultDirs, "watch these dirs")
72 | rootCmd.PersistentFlags().IntVarP(&triggerInterval, "interval", "i", 100, "scan every 'interval' milliseconds for new processes")
73 | rootCmd.PersistentFlags().BoolVarP(&colored, "color", "c", true, "color the printed events")
74 | rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "", false, "print detailed error messages")
75 | rootCmd.PersistentFlags().BoolVarP(&ppid, "ppid", "", false, "record process ppids")
76 | rootCmd.PersistentFlags().IntVarP(&cmdLength, "truncate", "t", 2048, "truncate process cmds longer than this")
77 |
78 | log.SetOutput(os.Stdout)
79 | }
80 |
81 | func root(cmd *cobra.Command, args []string) {
82 | logger := logging.NewLogger(debug)
83 |
84 | logger.Infof("%s", banner)
85 |
86 | cfg := &config.Config{
87 | RDirs: rDirs,
88 | Dirs: dirs,
89 | LogPS: logPS,
90 | LogFS: logFS,
91 | DrainFor: 1 * time.Second,
92 | TriggerEvery: time.Duration(triggerInterval) * time.Millisecond,
93 | Colored: colored,
94 | }
95 | fsw := fswatcher.NewFSWatcher()
96 | defer fsw.Close()
97 |
98 | pss := psscanner.NewPSScanner(ppid, cmdLength)
99 |
100 | sigCh := make(chan os.Signal)
101 | signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
102 |
103 | b := &pspy.Bindings{
104 | Logger: logger,
105 | FSW: fsw,
106 | PSS: pss,
107 | }
108 | exit := pspy.Start(cfg, b, sigCh)
109 | <-exit
110 | os.Exit(0)
111 | }
112 |
113 | func Execute() {
114 | if err := rootCmd.Execute(); err != nil {
115 | fmt.Println(err)
116 | os.Exit(1)
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/docker/Dockerfile.build:
--------------------------------------------------------------------------------
1 | FROM golang:1.19-bullseye
2 |
3 | RUN apt-get update && apt-get install -y upx && rm -rf /var/lib/apt/lists/*
4 |
--------------------------------------------------------------------------------
/docker/Dockerfile.development:
--------------------------------------------------------------------------------
1 | FROM golang:1.19-bullseye
2 |
3 | RUN apt-get update && apt-get -y install cron python3 sudo procps
4 |
5 | # install root cronjob
6 | COPY docker/var/spool/cron/crontabs /var/spool/cron/crontabs
7 | RUN chmod 600 /var/spool/cron/crontabs/root
8 | COPY docker/root/scripts /root/scripts
9 |
10 | # set up unpriviledged user
11 | # allows passwordless sudo to start cron as root on startup
12 | RUN useradd -ms /bin/bash myuser && \
13 | adduser myuser sudo && \
14 | echo 'myuser ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
15 | USER myuser
16 |
17 | # drop into bash shell
18 | COPY docker/entrypoint-development.sh /entrypoint.sh
19 | RUN sudo chmod +x /entrypoint.sh
20 | CMD ["/entrypoint.sh"]
21 |
--------------------------------------------------------------------------------
/docker/Dockerfile.example:
--------------------------------------------------------------------------------
1 | FROM debian:stretch
2 |
3 | RUN apt-get update && apt-get -y install cron python3 sudo procps
4 |
5 | # install root cronjob
6 | COPY docker/var/spool/cron/crontabs /var/spool/cron/crontabs
7 | RUN chmod 600 /var/spool/cron/crontabs/root
8 | COPY docker/root/scripts /root/scripts
9 |
10 | # install pspy
11 | COPY bin/pspy64 /usr/bin/pspy
12 |
13 | # set up unpriviledged user
14 | # allows passwordless sudo to start cron as root on startup
15 | RUN useradd -ms /bin/bash myuser && \
16 | adduser myuser sudo && \
17 | echo 'myuser ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
18 | USER myuser
19 |
20 | # deploy startup script
21 | COPY docker/entrypoint-example.sh /entrypoint.sh
22 | RUN sudo chmod +x /entrypoint.sh
23 | CMD ["/entrypoint.sh"]
24 |
25 |
26 |
--------------------------------------------------------------------------------
/docker/Dockerfile.testing:
--------------------------------------------------------------------------------
1 | FROM golang:1.19-bullseye
2 |
3 | RUN apt-get update && apt-get -y install cron python3 sudo procps
4 |
5 | ### Test and build ###
6 |
7 | # copy source code
8 | COPY main.go /go/src/github.com/dominicbreuker/pspy/main.go
9 | COPY cmd /go/src/github.com/dominicbreuker/pspy/cmd
10 | COPY internal /go/src/github.com/dominicbreuker/pspy/internal
11 | COPY go.mod /go/src/github.com/dominicbreuker/pspy/go.mod
12 | COPY go.sum /go/src/github.com/dominicbreuker/pspy/go.sum
13 | COPY .git /go/src/github.com/dominicbreuker/pspy/.git
14 |
15 | # run tests
16 | WORKDIR /go/src/github.com/dominicbreuker/pspy
17 | RUN go test ./...
18 | # build executable
19 | RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -ldflags '-extldflags "-static"' -o bin/pspy main.go
20 |
21 | ### Prepare integration test ###
22 | # install root cronjob
23 | COPY docker/var/spool/cron/crontabs /var/spool/cron/crontabs
24 | RUN chmod 600 /var/spool/cron/crontabs/root
25 | COPY docker/root/scripts /root/scripts
26 |
27 | # set up unpriviledged user
28 | # allows passwordless sudo to start cron as root on startup
29 | RUN useradd -ms /bin/bash myuser && \
30 | adduser myuser sudo && \
31 | echo 'myuser ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
32 | USER myuser
33 | RUN sudo chown -R myuser:myuser /go/*
34 |
35 | # drop into bash shell
36 | COPY docker/entrypoint-testing.sh /entrypoint.sh
37 | RUN sudo chmod +x /entrypoint.sh
38 | CMD ["/entrypoint.sh"]
39 |
--------------------------------------------------------------------------------
/docker/entrypoint-development.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | sudo cron -f &
6 | sleep 1
7 | sudo ps | grep cron 1>/dev/null
8 | echo "[+] cron started"
9 |
10 | echo "[+] Running as user `id`"
11 |
12 | echo "[+] Dropping into shell..."
13 | exec /bin/bash
14 |
--------------------------------------------------------------------------------
/docker/entrypoint-example.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | sudo cron -f &
6 | sleep 1
7 | sudo ps | grep cron 1>/dev/null
8 | echo "[+] cron started"
9 |
10 | echo "[+] Running as user `id`"
11 |
12 | echo "[+] Starting pspy now..."
13 | pspy 2>/dev/null
14 |
--------------------------------------------------------------------------------
/docker/entrypoint-testing.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ### test covereage
4 |
5 | if [ -z ${CC_TEST_REPORTER_ID+x} ]; then
6 | echo "[+] skipping test coverage"
7 | else
8 | echo "[+] reporting test coverage"
9 | curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
10 | chmod +x ./cc-test-reporter
11 |
12 | # git config --global user.email "dummy@example.com"
13 | # git config --global user.name "Mr Robot"
14 | # git init
15 | # git add .
16 | # git commit -m 'commit that makes cc test reporter happy'
17 |
18 | ./cc-test-reporter before-build
19 |
20 | for pkg in $(go list ./... | grep -v main); do
21 | go test -coverprofile=$(echo $pkg | tr / -).cover $pkg
22 | done
23 | echo "mode: set" > c.out
24 | grep -h -v "^mode:" ./*.cover >> c.out
25 | rm -f *.cover
26 |
27 | ./cc-test-reporter after-build
28 |
29 | rm c.out
30 |
31 | rm ./cc-test-reporter
32 | fi
33 |
34 | ### integration test
35 |
36 | sudo cron -f &
37 | sleep 1
38 | sudo ps | grep cron 1>/dev/null
39 | echo "[+] cron started"
40 |
41 | echo "[+] Running as user `id`"
42 |
43 | echo "[+] Executing test"
44 | # exec /bin/bash
45 | rm /home/myuser/log.txt
46 | bin/pspy > /home/myuser/log.txt &
47 |
48 | for i in `seq 1 25`; do
49 | echo "Waiting for cron job detection..."
50 | sleep 5;
51 |
52 | QUERY_RESULT=$(grep ' | passwd myuser' /home/myuser/log.txt | grep -v grep)
53 | if [ "'$QUERY_RESULT'" != "''" ]; then
54 | echo "Cron job execution detected!"
55 | echo "Complete log of pspy (may contain commands run in this test):"
56 | cat /home/myuser/log.txt
57 | exit 0
58 | fi
59 | done
60 | echo "Failed to detect cron job..."
61 | exit 1
62 |
--------------------------------------------------------------------------------
/docker/etc/cron.d/changepwds:
--------------------------------------------------------------------------------
1 | * * * * * root python /root/scripts/password_reset.py
2 |
--------------------------------------------------------------------------------
/docker/root/scripts/password_reset.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | import string
3 | import random
4 | from subprocess import call
5 |
6 | new_password = ''.join(random.SystemRandom()
7 | .choice(string.ascii_uppercase + string.digits)
8 | for _ in range(16))
9 |
10 | call("/bin/echo -e \"{}\\n{}\" | passwd myuser"
11 | .format(new_password, new_password), shell=True)
12 |
13 |
--------------------------------------------------------------------------------
/docker/var/spool/cron/crontabs/root:
--------------------------------------------------------------------------------
1 | * * * * * python3 /root/scripts/password_reset.py
2 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/dominicbreuker/pspy
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/spf13/cobra v1.4.0
7 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a
8 | )
9 |
10 | require (
11 | github.com/inconshreveable/mousetrap v1.0.0 // indirect
12 | github.com/spf13/pflag v1.0.5 // indirect
13 | )
14 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
2 | github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
3 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
4 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
5 | github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q=
6 | github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
7 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
8 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
9 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k=
10 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
11 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
12 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
13 |
--------------------------------------------------------------------------------
/images/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DominicBreuker/pspy/f9e6a1590a4312b9faa093d8dc84e19567977a6d/images/demo.gif
--------------------------------------------------------------------------------
/images/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
58 |
--------------------------------------------------------------------------------
/internal/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | type Config struct {
9 | RDirs []string
10 | Dirs []string
11 | LogFS bool
12 | LogPS bool
13 | DrainFor time.Duration
14 | TriggerEvery time.Duration
15 | Colored bool
16 | }
17 |
18 | func (c Config) String() string {
19 | return fmt.Sprintf("Printing events (colored=%t): processes=%t | file-system-events=%t ||| Scanning for processes every %v and on inotify events ||| Watching directories: %+v (recursive) | %+v (non-recursive)", c.Colored, c.LogPS, c.LogFS, c.TriggerEvery, c.RDirs, c.Dirs)
20 | }
21 |
--------------------------------------------------------------------------------
/internal/fswatcher/fswatcher.go:
--------------------------------------------------------------------------------
1 | package fswatcher
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/dominicbreuker/pspy/internal/fswatcher/inotify"
7 | "github.com/dominicbreuker/pspy/internal/fswatcher/walker"
8 | )
9 |
10 | type Inotify interface {
11 | Init() error
12 | Watch(dir string) error
13 | NumWatchers() int
14 | Read(buf []byte) (int, error)
15 | ParseNextEvent(buf []byte) (*inotify.Event, uint32, error)
16 | Close() error
17 | }
18 |
19 | type Walker interface {
20 | Walk(dir string, depth int) (chan string, chan error, chan struct{})
21 | }
22 |
23 | type FSWatcher struct {
24 | i Inotify
25 | w Walker
26 | maxWatchers int
27 | eventSize int
28 | drain bool
29 | }
30 |
31 | func NewFSWatcher() *FSWatcher {
32 | return &FSWatcher{
33 | i: inotify.NewInotify(),
34 | w: walker.NewWalker(),
35 | maxWatchers: inotify.MaxWatchers,
36 | eventSize: inotify.EventSize,
37 | drain: true,
38 | }
39 | }
40 |
41 | func (fs *FSWatcher) Enable() {
42 | fs.drain = false
43 | }
44 |
45 | func (fs *FSWatcher) Close() {
46 | fs.i.Close()
47 | }
48 |
49 | func (fs *FSWatcher) Init(rdirs, dirs []string) (chan error, chan struct{}) {
50 | errCh := make(chan error)
51 | doneCh := make(chan struct{})
52 |
53 | go func() {
54 | defer close(doneCh)
55 |
56 | err := fs.i.Init()
57 | if err != nil {
58 | errCh <- fmt.Errorf("setting up inotify: %v", err)
59 | return
60 | }
61 |
62 | fs.addWatchers(rdirs, dirs, errCh)
63 | }()
64 |
65 | return errCh, doneCh
66 | }
67 |
68 | func (fs *FSWatcher) addWatchers(rdirs, dirs []string, errCh chan error) {
69 | for _, dir := range rdirs {
70 | fs.addWatchersToDir(dir, -1, errCh)
71 | }
72 | for _, dir := range dirs {
73 | fs.addWatchersToDir(dir, 0, errCh)
74 | }
75 | }
76 |
77 | func (fs *FSWatcher) addWatchersToDir(dir string, depth int, errCh chan error) {
78 | dirCh, walkErrCh, doneCh := fs.w.Walk(dir, depth)
79 |
80 | for {
81 | if fs.maximumWatchersExceeded() {
82 | close(doneCh)
83 | return
84 | }
85 |
86 | if done := fs.handleNextWalkerResult(dirCh, walkErrCh, errCh); done {
87 | return
88 | }
89 | }
90 | }
91 |
92 | func (fs *FSWatcher) maximumWatchersExceeded() bool {
93 | return fs.maxWatchers > 0 && fs.i.NumWatchers() >= fs.maxWatchers
94 | }
95 |
96 | func (fs *FSWatcher) handleNextWalkerResult(dirCh chan string, walkErrCh chan error, errCh chan error) bool {
97 | select {
98 | case err := <-walkErrCh:
99 | errCh <- fmt.Errorf("adding inotify watchers: %v", err)
100 | case dir, ok := <-dirCh:
101 | if !ok {
102 | return true
103 | }
104 | if err := fs.i.Watch(dir); err != nil {
105 | errCh <- fmt.Errorf("can't create watcher: %v", err)
106 | }
107 | }
108 | return false
109 | }
110 |
111 | func (fs *FSWatcher) Run() (chan struct{}, chan string, chan error) {
112 | triggerCh, dataCh, eventCh, errCh := make(chan struct{}), make(chan []byte), make(chan string), make(chan error)
113 |
114 | go fs.observe(triggerCh, dataCh, errCh)
115 | go fs.parseEvents(dataCh, eventCh, errCh)
116 |
117 | return triggerCh, eventCh, errCh
118 | }
119 |
120 | func (fs *FSWatcher) observe(triggerCh chan struct{}, dataCh chan []byte, errCh chan error) {
121 | buf := make([]byte, 5*fs.eventSize)
122 |
123 | for {
124 | n, err := fs.i.Read(buf)
125 | if fs.drain {
126 | continue
127 | }
128 |
129 | triggerCh <- struct{}{}
130 | if err != nil {
131 | errCh <- fmt.Errorf("reading inotify buffer: %v", err)
132 | continue
133 | }
134 | bufCopy := make([]byte, n)
135 | copy(bufCopy, buf)
136 | dataCh <- bufCopy
137 | }
138 | }
139 |
140 | func (fs *FSWatcher) parseEvents(dataCh chan []byte, eventCh chan string, errCh chan error) {
141 | for buf := range dataCh {
142 | fs.handleChunk(buf, eventCh, errCh)
143 | }
144 | }
145 |
146 | func (fs *FSWatcher) handleChunk(buf []byte, eventCh chan string, errCh chan error) {
147 | var ptr uint32
148 | for len(buf[ptr:]) > 0 {
149 | event, size, err := fs.i.ParseNextEvent(buf[ptr:])
150 | ptr += size
151 | if err != nil {
152 | errCh <- fmt.Errorf("parsing events: %v", err)
153 | continue
154 | }
155 | eventCh <- fmt.Sprintf("%20s | %s", event.Op, event.Name)
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/internal/fswatcher/fswatcher_test.go:
--------------------------------------------------------------------------------
1 | package fswatcher
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "reflect"
7 | "strings"
8 | "testing"
9 | "time"
10 |
11 | "github.com/dominicbreuker/pspy/internal/fswatcher/inotify"
12 | )
13 |
14 | func initObjs() (*MockInotify, *MockWalker, *FSWatcher) {
15 | i := NewMockInotify()
16 | w := &MockWalker{
17 | subdirs: map[string][]string{
18 | "mydir1": []string{"dir1", "dir2"},
19 | "mydir2": []string{"dir3"},
20 | "dir1": []string{"another-dir"},
21 | },
22 | }
23 | fs := &FSWatcher{
24 | i: i,
25 | w: w,
26 | maxWatchers: 999,
27 | eventSize: 11,
28 | }
29 | return i, w, fs
30 | }
31 |
32 | func TestInit(t *testing.T) {
33 | i, _, fs := initObjs()
34 | rdirs := []string{"mydir1"}
35 | dirs := []string{"mydir2"}
36 |
37 | errCh, doneCh := fs.Init(rdirs, dirs)
38 |
39 | loop:
40 | for {
41 | select {
42 | case <-doneCh:
43 | break loop
44 | case err := <-errCh:
45 | t.Errorf("Unexpected error: %v", err)
46 | case <-time.After(1 * time.Second):
47 | t.Fatalf("Test timeout")
48 | }
49 | }
50 |
51 | if !reflect.DeepEqual(i.watching, []string{"mydir1", "dir1", "another-dir", "dir2", "mydir2"}) {
52 | t.Fatalf("Watching wrong directories: %+v", i.watching)
53 | }
54 | }
55 |
56 | func TestRun(t *testing.T) {
57 | i, _, fs := initObjs()
58 | triggerCh, eventCh, errCh := fs.Run()
59 |
60 | // send data (len=11)
61 | go func() {
62 | sendInotifyData(t, i.bufReads, "name:type__") // single event
63 | sendInotifyData(t, i.bufReads, "error:read_") // read error
64 | sendInotifyData(t, i.bufReads, "error:parse") // parse error
65 | sendInotifyData(t, i.bufReads, "name1:type1name2:type2") // 2 events
66 | }()
67 |
68 | // parse first datum
69 | expectTrigger(t, triggerCh)
70 | expectEvent(t, eventCh, "type__ | name")
71 |
72 | // parse second datum
73 | expectTrigger(t, triggerCh)
74 | expectError(t, errCh, "reading inotify buffer: error-inotify-read")
75 |
76 | // parse third datum
77 | expectTrigger(t, triggerCh)
78 | expectError(t, errCh, "parsing events: parse-event-error")
79 |
80 | // parse fourth datum
81 | expectTrigger(t, triggerCh)
82 | expectEvent(t, eventCh, "type1 | name1")
83 | expectEvent(t, eventCh, "type2 | name2")
84 | }
85 |
86 | const timeout = 500 * time.Millisecond
87 |
88 | func sendInotifyData(t *testing.T, dataCh chan []byte, s string) {
89 | select {
90 | case dataCh <- []byte(s):
91 | case <-time.After(timeout):
92 | t.Fatalf("Could not send data in time: %s", s)
93 | }
94 | }
95 |
96 | func expectTrigger(t *testing.T, triggerCh chan struct{}) {
97 | select {
98 | case <-triggerCh:
99 | case <-time.After(timeout):
100 | t.Fatalf("Timeout: did not receive trigger in time")
101 | }
102 | }
103 |
104 | func expectEvent(t *testing.T, eventCh chan string, exp string) {
105 | select {
106 | case e := <-eventCh:
107 | if strings.TrimSpace(e) != exp {
108 | t.Errorf("Wrong event: %+v", e)
109 | }
110 | case <-time.After(timeout):
111 | t.Fatalf("Timeout: did not receive event in time")
112 | }
113 | }
114 |
115 | func expectError(t *testing.T, errCh chan error, exp string) {
116 | select {
117 | case err := <-errCh:
118 | if err.Error() != exp {
119 | t.Errorf("Wrong error: %v", err)
120 | }
121 | case <-time.After(timeout):
122 | t.Fatalf("Timeout: did not receive error in time")
123 | }
124 | }
125 |
126 | // mocks
127 |
128 | // Mock Inotify
129 |
130 | type MockInotify struct {
131 | initialized bool
132 | watching []string
133 | bufReads chan []byte
134 | }
135 |
136 | func NewMockInotify() *MockInotify {
137 | return &MockInotify{
138 | initialized: false,
139 | watching: make([]string, 0),
140 | bufReads: make(chan []byte),
141 | }
142 | }
143 |
144 | func (i *MockInotify) Init() error {
145 | i.initialized = true
146 | return nil
147 | }
148 |
149 | func (i *MockInotify) Watch(dir string) error {
150 | if !i.initialized {
151 | return errors.New("Not yet initialized")
152 | }
153 | i.watching = append(i.watching, dir)
154 | return nil
155 | }
156 |
157 | func (i *MockInotify) NumWatchers() int {
158 | return len(i.watching)
159 | }
160 |
161 | func (i *MockInotify) Read(buf []byte) (int, error) {
162 | b := <-i.bufReads
163 | t := strings.Split(string(b), ":")
164 | if t[0] == "error" && t[1] == "read_" {
165 | return -1, fmt.Errorf("error-inotify-read")
166 | }
167 | copy(buf, b)
168 | return len(b), nil
169 | }
170 |
171 | func (i *MockInotify) ParseNextEvent(buf []byte) (*inotify.Event, uint32, error) {
172 | s := string(buf[:11])
173 | t := strings.Split(s, ":")
174 | if t[0] == "error" && t[1] == "parse" {
175 | return nil, uint32(len(buf)), fmt.Errorf("parse-event-error")
176 | }
177 | return &inotify.Event{Name: t[0], Op: t[1]}, 11, nil
178 | }
179 |
180 | func (i *MockInotify) Close() error {
181 | if !i.initialized {
182 | return errors.New("Not yet initialized")
183 | }
184 | return nil
185 | }
186 |
187 | // Mock Walker
188 |
189 | type MockWalker struct {
190 | subdirs map[string][]string
191 | }
192 |
193 | func (w *MockWalker) Walk(dir string, depth int) (chan string, chan error, chan struct{}) {
194 | dirCh := make(chan string)
195 | errCh := make(chan error)
196 | doneCh := make(chan struct{})
197 |
198 | go func() {
199 | defer close(dirCh)
200 | sendDir(w, depth, dir, dirCh)
201 | }()
202 |
203 | return dirCh, errCh, doneCh
204 | }
205 |
206 | func sendDir(w *MockWalker, depth int, dir string, dirCh chan string) {
207 | dirCh <- dir
208 | if depth == 0 {
209 | return
210 | }
211 | subdirs, ok := w.subdirs[dir]
212 | if !ok {
213 | return
214 | }
215 | for _, sdir := range subdirs {
216 | sendDir(w, depth-1, sdir, dirCh)
217 | }
218 | }
219 |
--------------------------------------------------------------------------------
/internal/fswatcher/inotify/event.go:
--------------------------------------------------------------------------------
1 | package inotify
2 |
3 | import "golang.org/x/sys/unix"
4 |
5 | var InotifyEvents = map[uint32]string{
6 | unix.IN_ACCESS: "ACCESS",
7 | unix.IN_ATTRIB: "ATTRIB",
8 | unix.IN_CLOSE_NOWRITE: "CLOSE_NOWRITE",
9 | unix.IN_CLOSE_WRITE: "CLOSE_WRITE",
10 | unix.IN_CREATE: "CREATE",
11 | unix.IN_DELETE: "DELETE",
12 | unix.IN_DELETE_SELF: "DELETE_SELF",
13 | unix.IN_MODIFY: "MODIFY",
14 | unix.IN_MOVED_FROM: "MOVED_FROM",
15 | unix.IN_MOVED_TO: "MOVED_TO",
16 | unix.IN_MOVE_SELF: "MOVE_SELF",
17 | unix.IN_OPEN: "OPEN",
18 | (unix.IN_ACCESS | unix.IN_ISDIR): "ACCESS DIR",
19 | (unix.IN_ATTRIB | unix.IN_ISDIR): "ATTRIB DIR",
20 | (unix.IN_CLOSE_NOWRITE | unix.IN_ISDIR): "CLOSE_NOWRITE DIR",
21 | (unix.IN_CLOSE_WRITE | unix.IN_ISDIR): "CLOSE_WRITE DIR",
22 | (unix.IN_CREATE | unix.IN_ISDIR): "CREATE DIR",
23 | (unix.IN_DELETE | unix.IN_ISDIR): "DELETE DIR",
24 | (unix.IN_DELETE_SELF | unix.IN_ISDIR): "DELETE_SELF DIR",
25 | (unix.IN_MODIFY | unix.IN_ISDIR): "MODIFY DIR",
26 | (unix.IN_MOVED_FROM | unix.IN_ISDIR): "MOVED_FROM DIR",
27 | (unix.IN_MOVE_SELF | unix.IN_ISDIR): "MODE_SELF DIR",
28 | (unix.IN_OPEN | unix.IN_ISDIR): "OPEN DIR",
29 | }
30 |
--------------------------------------------------------------------------------
/internal/fswatcher/inotify/inotify.go:
--------------------------------------------------------------------------------
1 | package inotify
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "io/ioutil"
7 | "os"
8 | "strconv"
9 | "strings"
10 | "unsafe"
11 |
12 | "golang.org/x/sys/unix"
13 | )
14 |
15 | const maximumWatchersFile = "/proc/sys/fs/inotify/max_user_watches"
16 |
17 | // MaxWatchers is the maximum number of inotify watches supported by the Kernel
18 | // set to -1 if the number cannot be determined
19 | var MaxWatchers int = -1
20 |
21 | // sizeof(struct inotify_event) + NAME_MAX + 1
22 | const EventSize int = unix.SizeofInotifyEvent + 255 + 1
23 |
24 | func init() {
25 | mw, err := getMaxWatchers()
26 | if err == nil {
27 | MaxWatchers = mw
28 | }
29 | }
30 |
31 | type Inotify struct {
32 | FD int
33 | Watchers map[int]*Watcher
34 | }
35 |
36 | type Watcher struct {
37 | WD int
38 | Dir string
39 | }
40 |
41 | type Event struct {
42 | Name string
43 | Op string
44 | }
45 |
46 | func NewInotify() *Inotify {
47 | return &Inotify{
48 | FD: 0,
49 | Watchers: make(map[int]*Watcher),
50 | }
51 | }
52 |
53 | func (i *Inotify) Init() error {
54 | fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC)
55 | if fd < 0 {
56 | return fmt.Errorf("initializing inotify: errno: %d", errno)
57 | }
58 | i.FD = fd
59 | return nil
60 | }
61 |
62 | func (i *Inotify) Watch(dir string) error {
63 | wd, errno := unix.InotifyAddWatch(i.FD, dir, unix.IN_ALL_EVENTS)
64 | if wd < 0 {
65 | return fmt.Errorf("adding watch to %s: errno: %d", dir, errno)
66 | }
67 | i.Watchers[wd] = &Watcher{
68 | WD: wd,
69 | Dir: dir,
70 | }
71 | return nil
72 | }
73 |
74 | var errno22Counter = 0
75 |
76 | func (i *Inotify) Read(buf []byte) (int, error) {
77 | n, errno := unix.Read(i.FD, buf)
78 | if n < 1 {
79 | if errno.Error() == "invalid argument" {
80 | errno22Counter += 1
81 | if errno22Counter > 20 {
82 | fmt.Printf("Unrecoverable inotify error (%s, errno %d). Exiting program...\n", errno, errno)
83 | os.Exit(22)
84 | }
85 | } else {
86 | errno22Counter = 0
87 | }
88 | return n, fmt.Errorf("reading from inotify fd %d: errno: %d", i.FD, errno)
89 | }
90 | return n, nil
91 | }
92 |
93 | func (i *Inotify) ParseNextEvent(buf []byte) (*Event, uint32, error) {
94 | n := len(buf)
95 | if n < unix.SizeofInotifyEvent {
96 | return nil, uint32(n), fmt.Errorf("incomplete read: n=%d", n)
97 | }
98 | sys := (*unix.InotifyEvent)(unsafe.Pointer(&buf[0]))
99 | offset := unix.SizeofInotifyEvent + sys.Len
100 |
101 | if sys.Wd == -1 {
102 | // watch descriptors should never be negative, yet there appears to be an unfixed bug causing them to be:
103 | // https://rachelbythebay.com/w/2014/11/24/touch/
104 | // https://code.launchpad.net/~jamesodhunt/libnih/libnih-inotify-overflow-fix-for-777093/+merge/65372
105 | return nil, offset, fmt.Errorf("possible inotify event overflow")
106 | }
107 |
108 | watcher, ok := i.Watchers[int(sys.Wd)]
109 | if !ok {
110 | return nil, offset, fmt.Errorf("unknown watcher ID: %d", sys.Wd)
111 | }
112 |
113 | return &Event{
114 | Name: getEventName(watcher, sys, buf, offset),
115 | Op: getEventOp(sys),
116 | }, offset, nil
117 | }
118 |
119 | func getEventName(watcher *Watcher, sys *unix.InotifyEvent, buf []byte, offset uint32) string {
120 | name := watcher.Dir + "/"
121 | if sys.Len > 0 && len(buf) >= int(offset) {
122 | name += string(bytes.TrimRight(buf[unix.SizeofInotifyEvent:offset], "\x00"))
123 | }
124 | return name
125 | }
126 |
127 | func getEventOp(sys *unix.InotifyEvent) string {
128 | op, ok := InotifyEvents[sys.Mask]
129 | if !ok {
130 | op = strconv.FormatInt(int64(sys.Mask), 2)
131 | }
132 | return op
133 | }
134 |
135 | func (i *Inotify) Close() error {
136 | if err := unix.Close(i.FD); err != nil {
137 | return fmt.Errorf("closing inotify fd: %v", err)
138 | }
139 | return nil
140 | }
141 |
142 | func (i *Inotify) NumWatchers() int {
143 | return len(i.Watchers)
144 | }
145 |
146 | func getMaxWatchers() (int, error) {
147 | b, err := ioutil.ReadFile(maximumWatchersFile)
148 | if err != nil {
149 | return 0, fmt.Errorf("reading from %s: %v", maximumWatchersFile, err)
150 | }
151 |
152 | s := strings.TrimSpace(string(b))
153 | m, err := strconv.Atoi(s)
154 | if err != nil {
155 | return 0, fmt.Errorf("converting to integer: %v", err)
156 | }
157 |
158 | return m, nil
159 | }
160 |
--------------------------------------------------------------------------------
/internal/fswatcher/inotify/inotify_test.go:
--------------------------------------------------------------------------------
1 | package inotify
2 |
3 | import (
4 | "fmt"
5 | "io/ioutil"
6 | "os"
7 | "strings"
8 | "testing"
9 |
10 | "golang.org/x/sys/unix"
11 | )
12 |
13 | func TestInotify(t *testing.T) {
14 | // init
15 |
16 | i := NewInotify()
17 |
18 | err := i.Init()
19 | expectNoError(t, err)
20 |
21 | // add watchers
22 |
23 | err = i.Watch("testdata/folder")
24 | expectNoError(t, err)
25 |
26 | err = i.Watch("testdata/non-existing-folder")
27 | if fmt.Sprintf("%v", err) != "adding watch to testdata/non-existing-folder: errno: 2" {
28 | t.Errorf("Wrong error for non-existing-folder: got %v", err)
29 | }
30 |
31 | numW := i.NumWatchers()
32 | if numW != 1 {
33 | t.Errorf("Expected 1 watcher but have %d", numW)
34 | }
35 |
36 | // create and parse events
37 |
38 | err = ioutil.WriteFile("testdata/folder/f1", []byte("file content"), 0644)
39 | expectNoError(t, err)
40 | defer os.Remove("testdata/folder/f1")
41 |
42 | buf := make([]byte, 5*unix.SizeofInotifyEvent)
43 | _, err = i.Read(buf)
44 | expectNoError(t, err)
45 |
46 | e, offset, err := i.ParseNextEvent(buf[0:])
47 | expectNoError(t, err)
48 | if e.Name != "testdata/folder/f1" {
49 | t.Fatalf("Wrong event name: %s", e.Name)
50 | }
51 | if e.Op != "CREATE" {
52 | t.Fatalf("Wrong op: %s", e.Op)
53 | }
54 | if offset != 32 {
55 | t.Fatalf("Wrong offset: %d", offset)
56 | }
57 |
58 | // finish
59 |
60 | err = i.Close()
61 | expectNoError(t, err)
62 |
63 | _, err = i.Read(buf)
64 | if !strings.HasSuffix(fmt.Sprintf("%v", err), "errno: 9") {
65 | t.Errorf("Wrong error for reading after close: got %v", err)
66 | }
67 | }
68 |
69 | func expectNoError(t *testing.T, err error) {
70 | if err != nil {
71 | t.Fatalf("Unexpected error: %v", err)
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/internal/fswatcher/inotify/testdata/folder/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DominicBreuker/pspy/f9e6a1590a4312b9faa093d8dc84e19567977a6d/internal/fswatcher/inotify/testdata/folder/.keep
--------------------------------------------------------------------------------
/internal/fswatcher/walker/testdata/f11.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DominicBreuker/pspy/f9e6a1590a4312b9faa093d8dc84e19567977a6d/internal/fswatcher/walker/testdata/f11.txt
--------------------------------------------------------------------------------
/internal/fswatcher/walker/testdata/f12.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DominicBreuker/pspy/f9e6a1590a4312b9faa093d8dc84e19567977a6d/internal/fswatcher/walker/testdata/f12.txt
--------------------------------------------------------------------------------
/internal/fswatcher/walker/testdata/subdir/f21.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DominicBreuker/pspy/f9e6a1590a4312b9faa093d8dc84e19567977a6d/internal/fswatcher/walker/testdata/subdir/f21.txt
--------------------------------------------------------------------------------
/internal/fswatcher/walker/testdata/subdir/subsubdir/f31.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DominicBreuker/pspy/f9e6a1590a4312b9faa093d8dc84e19567977a6d/internal/fswatcher/walker/testdata/subdir/subsubdir/f31.txt
--------------------------------------------------------------------------------
/internal/fswatcher/walker/walker.go:
--------------------------------------------------------------------------------
1 | package walker
2 |
3 | import (
4 | "fmt"
5 | "io/ioutil"
6 | "os"
7 | "path/filepath"
8 | )
9 |
10 | type Walker struct {
11 | }
12 |
13 | func NewWalker() *Walker {
14 | return &Walker{}
15 | }
16 |
17 | type chans struct {
18 | dirCh chan string
19 | errCh chan error
20 | doneCh chan struct{}
21 | }
22 |
23 | func newChans() *chans {
24 | return &chans{
25 | dirCh: make(chan string),
26 | errCh: make(chan error),
27 | doneCh: make(chan struct{}),
28 | }
29 | }
30 |
31 | const maxInt = int(^uint(0) >> 1)
32 |
33 | func (w *Walker) Walk(root string, depth int) (dirCh chan string, errCh chan error, doneCh chan struct{}) {
34 | if depth < 0 {
35 | depth = maxInt
36 | }
37 | c := newChans()
38 |
39 | go func() {
40 | defer close(dirCh)
41 | descent(root, depth-1, c)
42 | }()
43 | return c.dirCh, c.errCh, c.doneCh
44 | }
45 |
46 | func descent(dir string, depth int, c *chans) {
47 | if done := emitDir(dir, depth, c); done {
48 | return
49 | }
50 |
51 | handleSubDirs(dir, depth, c)
52 | }
53 |
54 | func emitDir(dir string, depth int, c *chans) bool {
55 | _, err := os.Stat(dir)
56 | if err != nil {
57 | c.errCh <- fmt.Errorf("visiting %s: %v", dir, err)
58 | return true
59 | }
60 | select {
61 | case c.dirCh <- dir:
62 | case <-c.doneCh:
63 | return true
64 | }
65 | if depth < 0 {
66 | return true
67 | }
68 |
69 | return false
70 | }
71 |
72 | func handleSubDirs(dir string, depth int, c *chans) {
73 | ls, err := ioutil.ReadDir(dir)
74 | if err != nil {
75 | c.errCh <- fmt.Errorf("opening dir %s: %v", dir, err)
76 | }
77 |
78 | for _, e := range ls {
79 | if e.IsDir() {
80 | newDir := filepath.Join(dir, e.Name())
81 | descent(newDir, depth-1, c)
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/internal/fswatcher/walker/walker_test.go:
--------------------------------------------------------------------------------
1 | package walker
2 |
3 | import (
4 | "reflect"
5 | "strings"
6 | "testing"
7 | )
8 |
9 | func TestWalk(t *testing.T) {
10 | tests := []struct {
11 | root string
12 | depth int
13 | errCh chan error
14 | result []string
15 | errs []string
16 | }{
17 | {root: "testdata", depth: 999, errCh: newErrCh(), result: []string{
18 | "testdata",
19 | "testdata/subdir",
20 | "testdata/subdir/subsubdir",
21 | }, errs: make([]string, 0)},
22 | {root: "testdata", depth: -1, errCh: newErrCh(), result: []string{
23 | "testdata",
24 | "testdata/subdir",
25 | "testdata/subdir/subsubdir",
26 | }, errs: []string{}},
27 | {root: "testdata", depth: 1, errCh: newErrCh(), result: []string{
28 | "testdata",
29 | "testdata/subdir",
30 | }, errs: []string{}},
31 | {root: "testdata", depth: 0, errCh: newErrCh(), result: []string{
32 | "testdata",
33 | }, errs: []string{}},
34 | {root: "testdata/subdir", depth: 1, errCh: newErrCh(), result: []string{
35 | "testdata/subdir",
36 | "testdata/subdir/subsubdir",
37 | }, errs: []string{}},
38 | {root: "testdata/non-existing-dir", depth: 1, errCh: newErrCh(), result: []string{}, errs: []string{"visiting testdata/non-existing-dir"}},
39 | }
40 |
41 | for i, tt := range tests {
42 | w := NewWalker()
43 | dirCh, errCh, doneCh := w.Walk(tt.root, tt.depth)
44 | dirs, errs := getAllDirsAndErrors(dirCh, errCh)
45 |
46 | if !reflect.DeepEqual(dirs, tt.result) {
47 | t.Fatalf("[%d] Wrong number of dirs found: %+v", i, dirs)
48 | }
49 | if !reflect.DeepEqual(errs, tt.errs) {
50 | t.Fatalf("[%d] Wrong number of errs found: %+v vs %+v", i, errs, tt.errs)
51 | }
52 | close(doneCh)
53 | }
54 |
55 | }
56 |
57 | func getAllDirsAndErrors(dirCh chan string, errCh chan error) ([]string, []string) {
58 | dirs := make([]string, 0)
59 | errs := make([]string, 0)
60 |
61 | doneDirsCh := make(chan struct{})
62 | go func() {
63 | defer close(doneDirsCh)
64 | defer close(errCh)
65 | for d := range dirCh {
66 | dirs = append(dirs, d)
67 | }
68 | }()
69 |
70 | doneErrsCh := make(chan struct{})
71 | go func() {
72 | defer close(doneErrsCh)
73 | for err := range errCh {
74 | tokens := strings.SplitN(err.Error(), ":", 2)
75 | errs = append(errs, tokens[0])
76 | }
77 | }()
78 | <-doneDirsCh
79 | <-doneErrsCh
80 | return dirs, errs
81 | }
82 |
83 | func newErrCh() chan error {
84 | return make(chan error)
85 | }
86 |
--------------------------------------------------------------------------------
/internal/logging/logging.go:
--------------------------------------------------------------------------------
1 | package logging
2 |
3 | import (
4 | "fmt"
5 | "hash/fnv"
6 | "log"
7 | "os"
8 | "strconv"
9 | )
10 |
11 | const (
12 | ColorNone = iota
13 | ColorRed
14 | ColorGreen
15 | ColorYellow
16 | ColorBlue
17 | ColorPurple
18 | ColorTeal
19 | )
20 |
21 | type Logger struct {
22 | infoLogger *log.Logger
23 | errorLogger *log.Logger
24 | eventLogger *log.Logger
25 | debug bool
26 | }
27 |
28 | func NewLogger(debug bool) *Logger {
29 | return &Logger{
30 | infoLogger: log.New(os.Stdout, "", 0),
31 | errorLogger: log.New(os.Stderr, "", 0),
32 | eventLogger: log.New(os.Stdout, "", log.Ldate|log.Ltime),
33 | debug: debug,
34 | }
35 | }
36 |
37 | // Infof writes an info message to stdout
38 | func (l *Logger) Infof(format string, v ...interface{}) {
39 | l.infoLogger.Printf(format, v...)
40 | }
41 |
42 | // Errorf writes an error message to stderr
43 | func (l *Logger) Errorf(debug bool, format string, v ...interface{}) {
44 | if l.debug == debug {
45 | l.errorLogger.Printf(format, v...)
46 | }
47 | }
48 |
49 | // Eventf writes an event with timestamp to stdout
50 | func (l *Logger) Eventf(color int, format string, v ...interface{}) {
51 | msg := fmt.Sprintf(format, v...)
52 | if color != ColorNone {
53 | msg = fmt.Sprintf("\x1b[%d;1m%s\x1b[0m", 30+color, msg)
54 | }
55 |
56 | l.eventLogger.Printf("%s", msg)
57 | }
58 |
59 | func GetColorByUID(uid int) int {
60 | h := fnv.New32a()
61 | h.Write([]byte(strconv.Itoa(uid)))
62 | return (int(h.Sum32()) % (ColorTeal)) + 1
63 | }
64 |
--------------------------------------------------------------------------------
/internal/logging/logging_test.go:
--------------------------------------------------------------------------------
1 | package logging
2 |
3 | import (
4 | "bytes"
5 | "log"
6 | "reflect"
7 | "regexp"
8 | "testing"
9 | )
10 |
11 | const dateFormatPattern = `[\d]{4}/[\d]{2}/[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}`
12 | const ansiPattern = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
13 |
14 | var ansiMatcher = regexp.MustCompile(ansiPattern)
15 |
16 | var l = NewLogger(true)
17 |
18 | var logTests = []struct {
19 | logger *log.Logger
20 | test func()
21 | expectation string
22 | colors [][]byte
23 | }{
24 | {l.infoLogger, func() { l.Infof("Info message no. %d", 1) }, "Info message no. 1\n", nil},
25 | {l.infoLogger, func() { l.Infof("Info message no. %d with a string %s\n", 2, "appended to it") }, "Info message no. 2 with a string appended to it\n", nil},
26 | {l.errorLogger, func() { l.Errorf(true, "Error message") }, "Error message\n", nil},
27 | {l.errorLogger, func() { l.Errorf(true, "Error message\n") }, "Error message\n", nil},
28 | {l.eventLogger, func() { l.Eventf(ColorNone, "Event message") }, dateFormatPattern + " Event message\n", nil},
29 | {l.eventLogger, func() { l.Eventf(ColorRed, "Event message") }, dateFormatPattern + " Event message\n", [][]byte{[]byte("\x1b[31;1m"), []byte("\x1b[0m")}},
30 | {l.eventLogger, func() { l.Eventf(ColorGreen, "Event message") }, dateFormatPattern + " Event message\n", [][]byte{[]byte("\x1b[32;1m"), []byte("\x1b[0m")}},
31 | }
32 |
33 | func TestLogging(t *testing.T) {
34 | for i, tt := range logTests {
35 | actual := captureOutput(tt.logger, tt.test)
36 | log.Printf("OUT: %s", actual)
37 |
38 | // check colors and remove afterwards
39 | colors := ansiMatcher.FindAll(actual, 2)
40 | if !reflect.DeepEqual(colors, tt.colors) {
41 | t.Errorf("[%d] Wrong colors: got %+v but want %+v", i, colors, tt.colors)
42 | }
43 | actual = ansiMatcher.ReplaceAll(actual, []byte(""))
44 |
45 | // check contents
46 | matcher := regexp.MustCompile(tt.expectation)
47 | if !matcher.Match(actual) {
48 | t.Errorf("[%d] Wrong message logged!: got %s but wanted %v", i, actual, matcher)
49 | }
50 | }
51 | }
52 |
53 | func captureOutput(logger *log.Logger, f func()) []byte {
54 | var buf bytes.Buffer
55 | logger.SetOutput(&buf)
56 | f()
57 | return buf.Bytes()
58 | }
59 |
60 | func TestGetColorByUID(t *testing.T) {
61 | tests := []struct {
62 | uid int
63 | color int
64 | }{
65 | {uid: 0, color: 4},
66 | {uid: 1, color: 5},
67 | {uid: 2, color: 2},
68 | {uid: 3, color: 3},
69 | {uid: 99999999999, color: 5},
70 | }
71 |
72 | for _, tt := range tests {
73 | color := GetColorByUID(tt.uid)
74 | if color != tt.color {
75 | t.Errorf("GetColorByUID(%d)=%d but want %d", tt.uid, color, tt.color)
76 | }
77 | }
78 |
79 | minColor := 9999999
80 | maxColor := -9999999
81 | for i := 0; i < 1000; i++ {
82 | color := GetColorByUID(i)
83 | if color < 1 || color > ColorTeal {
84 | t.Fatalf("GetColorByUID(%d)=%d but this is out of range [%d, %d]", i, color, ColorRed, ColorTeal)
85 | }
86 |
87 | if color < minColor {
88 | minColor = color
89 | }
90 | if color > maxColor {
91 | maxColor = color
92 | }
93 | }
94 |
95 | if minColor != 1 {
96 | t.Errorf("GetColorByUID returned minimum color %d, not %d, on 1000 trials, which is extremely unlikely", minColor, 1)
97 | }
98 | if maxColor != ColorTeal {
99 | t.Errorf("GetColorByUID returned maximum color %d, not %d, on 1000 trials, which is extremely unlikely", maxColor, ColorTeal)
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/internal/pspy/pspy.go:
--------------------------------------------------------------------------------
1 | package pspy
2 |
3 | import (
4 | "os"
5 | "time"
6 |
7 | "github.com/dominicbreuker/pspy/internal/config"
8 | "github.com/dominicbreuker/pspy/internal/logging"
9 | "github.com/dominicbreuker/pspy/internal/psscanner"
10 | )
11 |
12 | type Bindings struct {
13 | Logger Logger
14 | FSW FSWatcher
15 | PSS PSScanner
16 | }
17 |
18 | type Logger interface {
19 | Infof(format string, v ...interface{})
20 | Errorf(debug bool, format string, v ...interface{})
21 | Eventf(color int, format string, v ...interface{})
22 | }
23 |
24 | type FSWatcher interface {
25 | Init(rdirs, dirs []string) (chan error, chan struct{})
26 | Run() (chan struct{}, chan string, chan error)
27 | Enable()
28 | }
29 |
30 | type PSScanner interface {
31 | Run(triggerCh chan struct{}) (chan psscanner.PSEvent, chan error)
32 | }
33 |
34 | type chans struct {
35 | sigCh chan os.Signal
36 | fsEventCh chan string
37 | psEventCh chan psscanner.PSEvent
38 | }
39 |
40 | func Start(cfg *config.Config, b *Bindings, sigCh chan os.Signal) chan struct{} {
41 | b.Logger.Infof("Config: %+v", cfg)
42 | abort := make(chan struct{}, 1)
43 | abort <- struct{}{}
44 |
45 | if !initFSW(b.FSW, cfg.RDirs, cfg.Dirs, b.Logger, sigCh) {
46 | return abort
47 | }
48 | triggerCh, fsEventCh, ok := startFSW(b.FSW, b.Logger, cfg.DrainFor, sigCh)
49 | if !ok {
50 | return abort
51 | }
52 |
53 | psEventCh := startPSS(b.PSS, b.Logger, triggerCh)
54 |
55 | triggerEvery(100*time.Millisecond, triggerCh)
56 |
57 | chans := &chans{
58 | sigCh: sigCh,
59 | fsEventCh: fsEventCh,
60 | psEventCh: psEventCh,
61 | }
62 | exit := printOutput(cfg, b, chans)
63 | return exit
64 | }
65 |
66 | func printOutput(cfg *config.Config, b *Bindings, chans *chans) chan struct{} {
67 | exit := make(chan struct{})
68 | // fsEventColor, psEventColor := getColors(cfg.Colored)
69 |
70 | go func() {
71 | for {
72 | select {
73 | case se := <-chans.sigCh:
74 | b.Logger.Infof("Exiting program... (%s)", se)
75 | exit <- struct{}{}
76 | case fe := <-chans.fsEventCh:
77 | if cfg.LogFS {
78 | b.Logger.Eventf(logging.ColorNone, "FS: %+v", fe)
79 | }
80 | case pe := <-chans.psEventCh:
81 | if cfg.LogPS {
82 | color := logging.ColorNone
83 | if cfg.Colored {
84 | color = logging.GetColorByUID(pe.UID)
85 | }
86 | b.Logger.Eventf(color, "CMD: %+v", pe)
87 | }
88 | }
89 | }
90 | }()
91 | return exit
92 | }
93 |
94 | func initFSW(fsw FSWatcher, rdirs, dirs []string, logger Logger, sigCh <-chan os.Signal) bool {
95 | errCh, doneCh := fsw.Init(rdirs, dirs)
96 | for {
97 | select {
98 | case <-sigCh:
99 | return false
100 | case <-doneCh:
101 | return true
102 | case err := <-errCh:
103 | logger.Errorf(true, "initializing fs watcher: %v", err)
104 | }
105 | }
106 | }
107 |
108 | func startFSW(fsw FSWatcher, logger Logger, drainFor time.Duration, sigCh <-chan os.Signal) (triggerCh chan struct{}, fsEventCh chan string, ok bool) {
109 | triggerCh, fsEventCh, errCh := fsw.Run()
110 | go logErrors(errCh, logger)
111 |
112 | // ignore all file system events created on startup
113 | logger.Infof("Draining file system events due to startup...")
114 | ok = drainEventsFor(triggerCh, fsEventCh, drainFor, sigCh, fsw)
115 | logger.Infof("done")
116 | return
117 | }
118 |
119 | func startPSS(pss PSScanner, logger Logger, triggerCh chan struct{}) (psEventCh chan psscanner.PSEvent) {
120 | psEventCh, errCh := pss.Run(triggerCh)
121 | go logErrors(errCh, logger)
122 | return psEventCh
123 | }
124 |
125 | func triggerEvery(d time.Duration, triggerCh chan struct{}) {
126 | go func() {
127 | for {
128 | <-time.After(d)
129 | triggerCh <- struct{}{}
130 | }
131 | }()
132 | }
133 |
134 | func logErrors(errCh chan error, logger Logger) {
135 | for {
136 | err := <-errCh
137 | logger.Errorf(true, "ERROR: %v", err)
138 | }
139 | }
140 |
141 | func drainEventsFor(triggerCh chan struct{}, eventCh chan string, d time.Duration, sigCh <-chan os.Signal, fsw FSWatcher) bool {
142 | for {
143 | select {
144 | case <-sigCh:
145 | return false
146 | case <-time.After(d):
147 | fsw.Enable()
148 | return true
149 | }
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/internal/pspy/pspy_test.go:
--------------------------------------------------------------------------------
1 | package pspy
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "os"
7 | "testing"
8 | "time"
9 |
10 | "github.com/dominicbreuker/pspy/internal/config"
11 | "github.com/dominicbreuker/pspy/internal/logging"
12 | "github.com/dominicbreuker/pspy/internal/psscanner"
13 | )
14 |
15 | func TestInitFSW(t *testing.T) {
16 | l := newMockLogger()
17 | fsw := newMockFSWatcher()
18 | rdirs := make([]string, 0)
19 | dirs := make([]string, 0)
20 | sigCh := make(chan os.Signal)
21 | go func() {
22 | fsw.initErrCh <- errors.New("error1")
23 | fsw.initErrCh <- errors.New("error2")
24 | close(fsw.initDoneCh)
25 | }()
26 |
27 | if !initFSW(fsw, rdirs, dirs, l, sigCh) {
28 | t.Error("unexpected return value")
29 | }
30 |
31 | expectMessage(t, l.Error, "initializing fs watcher: error1")
32 | expectMessage(t, l.Error, "initializing fs watcher: error2")
33 | expectClosed(t, fsw.initDoneCh)
34 | }
35 |
36 | func TestInitFSWInterrupt(t *testing.T) {
37 | l := newMockLogger()
38 | fsw := newMockFSWatcher()
39 | rdirs := make([]string, 0)
40 | dirs := make([]string, 0)
41 | sigCh := make(chan os.Signal, 0)
42 | done := make(chan struct{})
43 |
44 | go func() {
45 | <-time.After(100 * time.Millisecond)
46 | sigCh <- os.Interrupt
47 | }()
48 |
49 | go func() {
50 | if initFSW(fsw, rdirs, dirs, l, sigCh) {
51 | t.Error("unexpected return value")
52 | }
53 | done <- struct{}{}
54 | }()
55 |
56 | select {
57 | case <-done:
58 | case <-time.After(1 * time.Second):
59 | t.Error("timout")
60 | }
61 | }
62 |
63 | // very flaky test... refactor code!
64 | func TestStartFSW(t *testing.T) {
65 | l := newMockLogger()
66 | fsw := newMockFSWatcher()
67 | drainFor := 100 * time.Millisecond
68 | sigCh := make(chan os.Signal)
69 |
70 | go func() {
71 | fsw.runErrCh <- errors.New("error sent while draining")
72 | <-time.After(drainFor) // ensure draining is over
73 | fsw.runTriggerCh <- struct{}{}
74 | fsw.runEventCh <- "event sent after draining"
75 | fsw.runErrCh <- errors.New("error sent after draining")
76 | }()
77 |
78 | // sends no events and triggers from the drain phase
79 | triggerCh, fsEventCh, ok := startFSW(fsw, l, drainFor, sigCh)
80 | if !ok {
81 | t.Error("unexpected return value")
82 | }
83 | expectMessage(t, l.Info, "Draining file system events due to startup...")
84 | expectMessage(t, l.Error, "ERROR: error sent while draining")
85 | expectMessage(t, l.Info, "done")
86 | expectTrigger(t, triggerCh)
87 | expectMessage(t, fsEventCh, "event sent after draining")
88 | }
89 |
90 | func TestStartFSWInterrupt(t *testing.T) {
91 | l := newMockLogger()
92 | fsw := newMockFSWatcher()
93 | drainFor := 500 * time.Millisecond
94 | sigCh := make(chan os.Signal)
95 | done := make(chan struct{})
96 |
97 | go func() {
98 | <-time.After(100 * time.Millisecond)
99 | sigCh <- os.Interrupt
100 | }()
101 |
102 | go func() {
103 | if _, _, ok := startFSW(fsw, l, drainFor, sigCh); ok {
104 | t.Error("unexpected return value")
105 | }
106 | done <- struct{}{}
107 | }()
108 |
109 | select {
110 | case <-done:
111 | case <-time.After(2 * time.Second):
112 | t.Error("timout")
113 | }
114 | }
115 |
116 | func TestStartPSS(t *testing.T) {
117 | pss := newMockPSScanner()
118 | l := newMockLogger()
119 | triggerCh := make(chan struct{})
120 |
121 | go func() {
122 | pss.runErrCh <- errors.New("error during refresh")
123 | }()
124 | startPSS(pss, l, triggerCh)
125 |
126 | expectMessage(t, l.Error, "ERROR: error during refresh")
127 | }
128 |
129 | func TestStart(t *testing.T) {
130 | drainFor := 10 * time.Millisecond
131 | triggerEvery := 999 * time.Second
132 | l := newMockLogger()
133 | fsw := newMockFSWatcher()
134 | pss := newMockPSScanner()
135 |
136 | b := &Bindings{
137 | Logger: l,
138 | FSW: fsw,
139 | PSS: pss,
140 | }
141 | cfg := &config.Config{
142 | RDirs: []string{"rdir1", "rdir2"},
143 | Dirs: []string{"dir1", "dir2"},
144 | LogFS: true,
145 | LogPS: true,
146 | DrainFor: drainFor,
147 | TriggerEvery: triggerEvery,
148 | Colored: true,
149 | }
150 | sigCh := make(chan os.Signal)
151 |
152 | go func() {
153 | close(fsw.initDoneCh)
154 | <-time.After(2 * drainFor)
155 | fsw.runTriggerCh <- struct{}{}
156 | pss.runEventCh <- psscanner.PSEvent{UID: 1000, PID: 12345, PPID: 54321, CMD: "pss event"}
157 | pss.runErrCh <- errors.New("pss error")
158 | fsw.runEventCh <- "fsw event"
159 | fsw.runErrCh <- errors.New("fsw error")
160 | sigCh <- os.Interrupt
161 | }()
162 |
163 | exitCh := Start(cfg, b, sigCh)
164 | expectMessage(t, l.Info, "Config: Printing events (colored=true): processes=true | file-system-events=true ||| Scanning for processes every 16m39s and on inotify events ||| Watching directories: [rdir1 rdir2] (recursive) | [dir1 dir2] (non-recursive)")
165 | expectMessage(t, l.Info, "Draining file system events due to startup...")
166 | <-time.After(2 * drainFor)
167 | expectMessage(t, l.Info, "done")
168 | expectTrigger(t, pss.runTriggerCh) // pss receives triggers from fsw
169 | expectMessage(t, l.Event, fmt.Sprintf("%d CMD: UID=1000 PID=12345 PPID=54321 | pss event", logging.ColorPurple))
170 | expectMessage(t, l.Error, "ERROR: pss error")
171 | expectMessage(t, l.Event, fmt.Sprintf("%d FS: fsw event", logging.ColorNone))
172 | expectMessage(t, l.Error, "ERROR: fsw error")
173 | expectMessage(t, l.Info, "Exiting program... (interrupt)")
174 |
175 | expectExit(t, exitCh)
176 | }
177 |
178 | // #### Helpers ####
179 |
180 | var timeout = 100 * time.Millisecond
181 | var errTimeout = errors.New("timeout")
182 |
183 | func expectMessage(t *testing.T, ch chan string, expected string) {
184 | select {
185 | case actual := <-ch:
186 | if actual != expected {
187 | t.Fatalf("Wrong message: got '%s' but wanted '%s'", actual, expected)
188 | }
189 | case <-time.After(timeout):
190 | t.Fatalf("Did not get message in time: %s", expected)
191 | }
192 | }
193 |
194 | func expectTrigger(t *testing.T, ch chan struct{}) {
195 | if err := expectChanMsg(ch); err != nil {
196 | t.Fatalf("triggering: %v", err)
197 | }
198 | }
199 |
200 | func expectExit(t *testing.T, ch chan struct{}) {
201 | if err := expectChanMsg(ch); err != nil {
202 | t.Fatalf("exiting: %v", err)
203 | }
204 | }
205 |
206 | func expectChanMsg(ch chan struct{}) error {
207 | select {
208 | case <-ch:
209 | return nil
210 | case <-time.After(timeout):
211 | return fmt.Errorf("did not get message in time")
212 | }
213 | }
214 |
215 | func expectClosed(t *testing.T, ch chan struct{}) {
216 | select {
217 | case _, ok := <-ch:
218 | if ok {
219 | t.Fatalf("Channel not closed: got ok=%t", ok)
220 | }
221 | case <-time.After(timeout):
222 | t.Fatalf("Channel not closed: timeout!")
223 | }
224 | }
225 |
226 | // ##### Mocks #####
227 |
228 | // Logger
229 |
230 | type mockLogger struct {
231 | Info chan string
232 | Error chan string
233 | Event chan string
234 | Debug bool
235 | }
236 |
237 | func newMockLogger() *mockLogger {
238 | return &mockLogger{
239 | Info: make(chan string, 10),
240 | Error: make(chan string, 10),
241 | Event: make(chan string, 10),
242 | Debug: true,
243 | }
244 | }
245 |
246 | func (l *mockLogger) Infof(format string, v ...interface{}) {
247 | l.Info <- fmt.Sprintf(format, v...)
248 | }
249 |
250 | func (l *mockLogger) Errorf(debug bool, format string, v ...interface{}) {
251 | if l.Debug == debug {
252 | l.Error <- fmt.Sprintf(format, v...)
253 | }
254 | }
255 |
256 | func (l *mockLogger) Eventf(color int, format string, v ...interface{}) {
257 | m := fmt.Sprintf(format, v...)
258 | l.Event <- fmt.Sprintf("%d %s", color, m)
259 | }
260 |
261 | // FSWatcher
262 |
263 | type mockFSWatcher struct {
264 | rdirs []string
265 | dirs []string
266 | initErrCh chan error
267 | initDoneCh chan struct{}
268 | runTriggerCh chan struct{}
269 | runEventCh chan string
270 | runErrCh chan error
271 | }
272 |
273 | func newMockFSWatcher() *mockFSWatcher {
274 | return &mockFSWatcher{
275 | rdirs: make([]string, 0),
276 | dirs: make([]string, 0),
277 | initErrCh: make(chan error),
278 | initDoneCh: make(chan struct{}),
279 | runTriggerCh: make(chan struct{}),
280 | runEventCh: make(chan string),
281 | runErrCh: make(chan error),
282 | }
283 | }
284 |
285 | func (fsw *mockFSWatcher) Init(rdirs, dirs []string) (chan error, chan struct{}) {
286 | fsw.rdirs = rdirs
287 | fsw.dirs = dirs
288 | return fsw.initErrCh, fsw.initDoneCh
289 | }
290 |
291 | func (fsw *mockFSWatcher) Run() (chan struct{}, chan string, chan error) {
292 | return fsw.runTriggerCh, fsw.runEventCh, fsw.runErrCh
293 | }
294 |
295 | func (fsw *mockFSWatcher) Enable() {
296 | return
297 | }
298 |
299 | // PSScanner
300 |
301 | type mockPSScanner struct {
302 | runTriggerCh chan struct{}
303 | runEventCh chan psscanner.PSEvent
304 | runErrCh chan error
305 | numRefreshes int
306 | }
307 |
308 | func newMockPSScanner() *mockPSScanner {
309 | return &mockPSScanner{}
310 | }
311 |
312 | func (pss *mockPSScanner) Run(triggerCh chan struct{}) (chan psscanner.PSEvent, chan error) {
313 | pss.runTriggerCh = triggerCh
314 | pss.runEventCh = make(chan psscanner.PSEvent)
315 | pss.runErrCh = make(chan error)
316 |
317 | go func() {
318 | <-pss.runTriggerCh
319 | pss.numRefreshes++ // count number of times we refreshed
320 | }()
321 |
322 | return pss.runEventCh, pss.runErrCh
323 | }
324 |
--------------------------------------------------------------------------------
/internal/psscanner/proclist.go:
--------------------------------------------------------------------------------
1 | package psscanner
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "os"
7 | "strconv"
8 | )
9 |
10 | type procList map[int]struct{}
11 |
12 | type pidProcessor interface {
13 | processNewPid(pid int)
14 | }
15 |
16 | func (pl procList) refresh(p pidProcessor) error {
17 | pids, err := getPIDs()
18 | if err != nil {
19 | return err
20 | }
21 |
22 | for i := len(pids) - 1; i >= 0; i-- {
23 | pid := pids[i]
24 | _, ok := pl[pid]
25 | if !ok {
26 | p.processNewPid(pid)
27 | pl[pid] = struct{}{}
28 | }
29 | }
30 |
31 | return nil
32 | }
33 |
34 | func getPIDs() ([]int, error) {
35 | f, err := dirOpen("/proc")
36 | if err != nil {
37 | return nil, fmt.Errorf("opening proc dir: %v", err)
38 | }
39 | defer f.Close()
40 |
41 | names, err := f.Readdirnames(-1)
42 | if err != nil {
43 | return nil, fmt.Errorf("reading proc dir: %v", err)
44 | }
45 |
46 | pids := make([]int, 0)
47 | for _, f := range names {
48 | pid, err := strconv.Atoi(f)
49 | if err != nil || pid <= 0 {
50 | continue
51 | }
52 | pids = append(pids, pid)
53 | }
54 | return pids, nil
55 | }
56 |
57 | type readDirNamesCloser interface {
58 | Readdirnames(n int) (names []string, err error)
59 | io.Closer
60 | }
61 |
62 | var dirOpen func(string) (readDirNamesCloser, error) = func(s string) (readDirNamesCloser, error) {
63 | return os.Open(s)
64 | }
65 |
--------------------------------------------------------------------------------
/internal/psscanner/proclist_test.go:
--------------------------------------------------------------------------------
1 | package psscanner
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "reflect"
7 | "strings"
8 | "testing"
9 | )
10 |
11 | // GetPIDs
12 |
13 | func TestGetPIDs(t *testing.T) {
14 | tests := []struct {
15 | name string
16 | proc []string
17 | procErrOpen error
18 | procErrRead error
19 | pids []int
20 | err string
21 | }{
22 | {
23 | name: "numbers-only",
24 | proc: []string{"42", "somedir"},
25 | procErrOpen: nil,
26 | procErrRead: nil,
27 | pids: []int{42},
28 | err: "",
29 | },
30 | {
31 | name: "multiple-entries",
32 | proc: []string{"42", "13"},
33 | procErrOpen: nil,
34 | procErrRead: nil,
35 | pids: []int{42, 13},
36 | err: "",
37 | },
38 | {
39 | name: "ignores-lte-0",
40 | proc: []string{"0", "-1"},
41 | procErrOpen: nil,
42 | procErrRead: nil,
43 | pids: []int{},
44 | err: "",
45 | },
46 | {
47 | name: "empty-procfs",
48 | proc: []string{},
49 | procErrOpen: nil,
50 | procErrRead: nil,
51 | pids: []int{},
52 | err: "",
53 | },
54 | {
55 | name: "handle-open-error",
56 | proc: []string{},
57 | procErrOpen: errors.New("file-system-error"),
58 | procErrRead: nil,
59 | pids: nil,
60 | err: "opening proc dir: file-system-error",
61 | },
62 | {
63 | name: "handle-read-error",
64 | proc: []string{},
65 | procErrOpen: nil,
66 | procErrRead: errors.New("file-system-error"),
67 | pids: nil,
68 | err: "reading proc dir: file-system-error",
69 | },
70 | }
71 |
72 | for _, tt := range tests {
73 | t.Run(tt.name, func(t *testing.T) {
74 | defer mockDir("/proc", tt.proc, tt.procErrRead, tt.procErrOpen, t)()
75 | pids, err := getPIDs()
76 | if !reflect.DeepEqual(pids, tt.pids) {
77 | t.Errorf("Wrong pids returned: got %v but want %v", pids, tt.pids)
78 | }
79 | if (err != nil || tt.err != "") && fmt.Sprintf("%v", err) != tt.err {
80 | t.Errorf("Wrong error returned: got %v but want %s", err, tt.err)
81 | }
82 | })
83 | }
84 | }
85 |
86 | type MockDir struct {
87 | names []string
88 | err error
89 | }
90 |
91 | func (f *MockDir) Close() error {
92 | return nil
93 | }
94 |
95 | func min(a, b int) int {
96 | if a > b {
97 | return b
98 | }
99 | return a
100 | }
101 |
102 | func (f *MockDir) Readdirnames(n int) (names []string, err error) {
103 | if n < 0 {
104 | return f.names, f.err
105 | }
106 | return f.names[:min(n, len(f.names))], f.err
107 | }
108 |
109 | // Hook/chain a mocked file into the "open" variable
110 | func mockDir(name string, names []string, errRead error, errOpen error, t *testing.T) func() {
111 | oldopen := dirOpen
112 | dirOpen = func(n string) (readDirNamesCloser, error) {
113 | if name == n {
114 | if testing.Verbose() {
115 | t.Logf("opening mocked dir: %s", n)
116 | }
117 | return &MockDir{
118 | names: names,
119 | err: errRead,
120 | }, errOpen
121 | }
122 | return oldopen(n)
123 | }
124 | return func() {
125 | dirOpen = oldopen
126 | }
127 | }
128 |
129 | type mockPidProcessor struct {
130 | t *testing.T
131 | pids []int
132 | }
133 |
134 | func (m *mockPidProcessor) processNewPid(pid int) {
135 | if testing.Verbose() {
136 | m.t.Logf("proc %d processed", pid)
137 | }
138 | m.pids = append(m.pids, pid)
139 | }
140 |
141 | var unit = struct{}{}
142 |
143 | func TestRefresh(t *testing.T) {
144 | tests := []struct {
145 | name string
146 | pl procList
147 | newPids []int
148 | plAfter procList
149 | pidsProcessed []int
150 | }{
151 | {
152 | name: "nominal",
153 | pl: procList{},
154 | newPids: []int{1, 2, 3},
155 | plAfter: procList{1: unit, 2: unit, 3: unit},
156 | pidsProcessed: []int{3, 2, 1},
157 | },
158 | {
159 | name: "merge",
160 | pl: procList{1: unit},
161 | newPids: []int{1, 2, 3},
162 | plAfter: procList{1: unit, 2: unit, 3: unit},
163 | pidsProcessed: []int{3, 2},
164 | },
165 | {
166 | name: "nothing-new",
167 | pl: procList{1: unit, 2: unit, 3: unit},
168 | newPids: []int{1, 2, 3},
169 | plAfter: procList{1: unit, 2: unit, 3: unit},
170 | pidsProcessed: []int{},
171 | },
172 | }
173 |
174 | for _, tt := range tests {
175 | t.Run(tt.name, func(t *testing.T) {
176 | defer mockPidList(tt.newPids, t)()
177 |
178 | m := &mockPidProcessor{t, []int{}}
179 | tt.pl.refresh(m)
180 |
181 | if !reflect.DeepEqual(m.pids, tt.pidsProcessed) {
182 | t.Errorf("Unexpected pids got processed: got %v but want %v", m.pids, tt.pidsProcessed)
183 | }
184 | if !reflect.DeepEqual(tt.pl, tt.plAfter) {
185 | t.Errorf("Unexpected pids stored in procList: got %v but want %v", tt.pl, tt.plAfter)
186 | }
187 | })
188 | }
189 | }
190 |
191 | // separate test for failing, only one case where getPids fails
192 | func TestRefreshFail(t *testing.T) {
193 | e := errors.New("file-system-error")
194 | for _, tt := range []struct {
195 | name string
196 | errRead error
197 | errOpen error
198 | }{
199 | {
200 | name: "open-dir-fail",
201 | errRead: nil,
202 | errOpen: e,
203 | },
204 | {
205 | name: "read-dir-fail",
206 | errRead: e,
207 | errOpen: nil,
208 | },
209 | } {
210 | t.Run(tt.name, func(t *testing.T) {
211 | defer mockDir("/proc", []string{}, tt.errRead, tt.errOpen, t)()
212 | m := &mockPidProcessor{t, []int{}}
213 | pl := procList{1: unit}
214 | err := pl.refresh(m)
215 | if err == nil {
216 | t.Errorf("Expected an error")
217 | } else {
218 | if strings.Index(err.Error(), e.Error()) == -1 {
219 | t.Errorf("Unexpected error: %v", err)
220 | }
221 | }
222 |
223 | })
224 | }
225 | }
226 |
227 | func mockPidList(pids []int, t *testing.T) func() {
228 | dirs := make([]string, 0)
229 | for _, pid := range pids {
230 | dirs = append(dirs, fmt.Sprintf("%d", pid))
231 | }
232 | return mockDir("/proc", dirs, nil, nil, t)
233 | }
234 |
--------------------------------------------------------------------------------
/internal/psscanner/psscanner.go:
--------------------------------------------------------------------------------
1 | package psscanner
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "io"
7 | "os"
8 | "regexp"
9 | "strconv"
10 | "syscall"
11 | )
12 |
13 | type PSScanner struct {
14 | enablePpid bool
15 | eventCh chan<- PSEvent
16 | maxCmdLength int
17 | }
18 |
19 | type PSEvent struct {
20 | UID int
21 | PID int
22 | PPID int
23 | CMD string
24 | }
25 |
26 | func (evt PSEvent) String() string {
27 | uid := strconv.Itoa(evt.UID)
28 | if evt.UID == -1 {
29 | uid = "???"
30 | }
31 |
32 | if evt.PPID == -1 {
33 | return fmt.Sprintf("UID=%-5s PID=%-6d | %s", uid, evt.PID, evt.CMD)
34 | }
35 |
36 | return fmt.Sprintf(
37 | "UID=%-5s PID=%-6d PPID=%-6d | %s", uid, evt.PID, evt.PPID, evt.CMD)
38 | }
39 |
40 | var (
41 | // identify ppid in stat file
42 | ppidRegex, _ = regexp.Compile("\\d+ \\(.*\\) [[:alpha:]] (\\d+)")
43 | // hook for testing, directly use Lstat syscall as os.Lstat hides data in Sys member
44 | lstat = syscall.Lstat
45 | // hook for testing
46 | open = func(s string) (io.ReadCloser, error) {
47 | return os.Open(s)
48 | }
49 | )
50 |
51 | func NewPSScanner(ppid bool, cmdLength int) *PSScanner {
52 | return &PSScanner{
53 | enablePpid: ppid,
54 | eventCh: nil,
55 | maxCmdLength: cmdLength,
56 | }
57 | }
58 |
59 | func (p *PSScanner) Run(triggerCh chan struct{}) (chan PSEvent, chan error) {
60 | eventCh := make(chan PSEvent, 100)
61 | p.eventCh = eventCh
62 | errCh := make(chan error)
63 | pl := make(procList)
64 |
65 | go func() {
66 | for {
67 | <-triggerCh
68 | pl.refresh(p)
69 | }
70 | }()
71 | return eventCh, errCh
72 | }
73 |
74 | func (p *PSScanner) processNewPid(pid int) {
75 | statInfo := syscall.Stat_t{}
76 | errStat := lstat(fmt.Sprintf("/proc/%d", pid), &statInfo)
77 | cmdLine, errCmdLine := readFile(fmt.Sprintf("/proc/%d/cmdline", pid), p.maxCmdLength)
78 | ppid, _ := p.getPpid(pid)
79 |
80 | cmd := "???" // process probably terminated
81 | if errCmdLine == nil {
82 | for i := 0; i < len(cmdLine); i++ {
83 | if cmdLine[i] == 0 {
84 | cmdLine[i] = 32
85 | }
86 | }
87 | cmd = string(cmdLine)
88 | }
89 |
90 | uid := -1
91 | if errStat == nil {
92 | uid = int(statInfo.Uid)
93 | }
94 |
95 | p.eventCh <- PSEvent{UID: uid, PID: pid, PPID: ppid, CMD: cmd}
96 | }
97 |
98 | func (p *PSScanner) getPpid(pid int) (int, error) {
99 | if !p.enablePpid {
100 | return -1, nil
101 | }
102 |
103 | stat, err := readFile(fmt.Sprintf("/proc/%d/stat", pid), 512)
104 | if err != nil {
105 | return -1, err
106 | }
107 |
108 | if m := ppidRegex.FindStringSubmatch(string(stat)); m != nil {
109 | return strconv.Atoi(m[1])
110 | }
111 | return -1, errors.New("corrupt stat file")
112 | }
113 |
114 | // no nonsense file reading
115 | func readFile(filename string, maxlen int) ([]byte, error) {
116 | file, err := open(filename)
117 | if err != nil {
118 | return nil, err
119 | }
120 | defer file.Close()
121 |
122 | buffer := make([]byte, maxlen)
123 | n, err := file.Read(buffer)
124 | if err != io.EOF && err != nil {
125 | return nil, err
126 | }
127 | return buffer[:n], nil
128 | }
129 |
--------------------------------------------------------------------------------
/internal/psscanner/psscanner_test.go:
--------------------------------------------------------------------------------
1 | package psscanner
2 |
3 | import (
4 | //"encoding/hex"
5 | "errors"
6 | "fmt"
7 | "io"
8 | "reflect"
9 | "syscall"
10 | "testing"
11 | "time"
12 | )
13 |
14 | const timeout = 100 * time.Millisecond
15 |
16 | func TestRun(t *testing.T) {
17 | tests := []struct {
18 | name string
19 | pids []int
20 | events []string
21 | }{
22 | {
23 | name: "nominal",
24 | pids: []int{1, 2, 3},
25 | events: []string{
26 | "UID=??? PID=3 | the-command",
27 | "UID=??? PID=2 | the-command",
28 | "UID=??? PID=1 | the-command",
29 | },
30 | },
31 | }
32 |
33 | for _, tt := range tests {
34 | t.Run(tt.name, func(t *testing.T) {
35 | defer mockPidList(tt.pids, t)()
36 | for _, pid := range tt.pids {
37 | defer mockPidCmdLine(pid, []byte("the-command"), nil, nil, t)()
38 | defer mockPidUid(pid, 0, errors.New("file not found"), t)()
39 | }
40 |
41 | pss := NewPSScanner(false, 2048)
42 | triggerCh := make(chan struct{})
43 | eventCh, errCh := pss.Run(triggerCh)
44 |
45 | // does nothing without triggering
46 | select {
47 | case e := <-eventCh:
48 | t.Errorf("Received event before trigger: %s", e)
49 | case err := <-errCh:
50 | t.Errorf("Received error before trigger: %v", err)
51 | case <-time.After(timeout):
52 | // ok
53 | }
54 |
55 | triggerCh <- struct{}{}
56 |
57 | // received event after the trigger
58 | for i := 0; i < 3; i++ {
59 | select {
60 | case <-time.After(timeout):
61 | t.Errorf("did not receive event in time")
62 | case e := <-eventCh:
63 | if e.String() != tt.events[i] {
64 | t.Errorf("Wrong event received: got '%s' but wanted '%s'", e, tt.events[i])
65 | }
66 | case err := <-errCh:
67 | t.Errorf("Received unexpected error: %v", err)
68 | }
69 | }
70 | })
71 | }
72 | }
73 |
74 | var (
75 | completeStat = []byte("1314 (some proc with) odd chars)) in name) R 5560 1314 5560 34821 1314 4194304 82 0 0 0 0 0 0 0 20 0 1 0 15047943 7790592 196 18446744073709551615 94260770430976 94260770462160 140725974097504 0 0 0 0 0 0 0 0 0 17 1 0 0 0 0 0 94260772559472 94260772561088 94260783992832 140725974106274 140725974106294 140725974106294 140725974110191 0\n")
76 | partialStat = []byte("1314 (ps) ")
77 | invalidPpid = []byte("1314 (ps) R XYZ 1314 5560 34821 1314 4194304 82 0 0 0 0 0 0 0 20 0 1 0 15047943 7790592 196 18446744073709551615 94260770430976 94260770462160 140725974097504 0 0 0 0 0 0 0 0 0 17 1 0 0 0 0 0 94260772559472 94260772561088 94260783992832 140725974106274 140725974106294 140725974106294 140725974110191 0\n")
78 | )
79 |
80 | func TestProcessNewPid(t *testing.T) {
81 | tests := []struct {
82 | name string
83 | enablePpid bool
84 | truncate int
85 | pid int
86 | cmdLine []byte
87 | cmdLineErrRead error
88 | cmdLineErrOpen error
89 | stat []byte
90 | statErrRead error
91 | statErrOpen error
92 | lstatUid uint32
93 | lstatErr error
94 | expected PSEvent
95 | }{
96 | {
97 | name: "nominal-no-ppid",
98 | enablePpid: false,
99 | truncate: 100,
100 | pid: 1,
101 | cmdLine: []byte("abc\x00123"),
102 | cmdLineErrRead: nil,
103 | cmdLineErrOpen: nil,
104 | stat: completeStat,
105 | statErrRead: nil,
106 | statErrOpen: nil,
107 | lstatUid: 0,
108 | lstatErr: nil,
109 | expected: PSEvent{
110 | UID: 0,
111 | PID: 1,
112 | PPID: -1,
113 | CMD: "abc 123",
114 | },
115 | },
116 | {
117 | name: "nominal-ppid",
118 | enablePpid: true,
119 | truncate: 100,
120 | pid: 1,
121 | cmdLine: []byte("abc\x00123"),
122 | cmdLineErrRead: nil,
123 | cmdLineErrOpen: nil,
124 | stat: completeStat,
125 | statErrRead: nil,
126 | statErrOpen: nil,
127 | lstatUid: 999,
128 | lstatErr: nil,
129 | expected: PSEvent{
130 | UID: 999,
131 | PID: 1,
132 | PPID: 5560,
133 | CMD: "abc 123",
134 | },
135 | },
136 | {
137 | name: "empty-cmd-ok",
138 | enablePpid: true,
139 | truncate: 100,
140 | pid: 1,
141 | cmdLine: []byte{},
142 | cmdLineErrRead: nil,
143 | cmdLineErrOpen: nil,
144 | stat: completeStat,
145 | statErrRead: nil,
146 | statErrOpen: nil,
147 | lstatUid: 0,
148 | lstatErr: nil,
149 | expected: PSEvent{
150 | UID: 0,
151 | PID: 1,
152 | PPID: 5560,
153 | CMD: "",
154 | },
155 | },
156 | {
157 | name: "cmd-truncate",
158 | enablePpid: false,
159 | truncate: 10,
160 | pid: 1,
161 | cmdLine: []byte("abc\x00123\x00alpha"),
162 | cmdLineErrRead: nil,
163 | cmdLineErrOpen: nil,
164 | stat: completeStat,
165 | statErrRead: nil,
166 | statErrOpen: nil,
167 | lstatUid: 0,
168 | lstatErr: nil,
169 | expected: PSEvent{
170 | UID: 0,
171 | PID: 1,
172 | PPID: -1,
173 | CMD: "abc 123 al",
174 | },
175 | },
176 | {
177 | name: "cmd-io-error",
178 | enablePpid: true,
179 | truncate: 100,
180 | pid: 2,
181 | cmdLine: nil,
182 | cmdLineErrRead: errors.New("file-system-error"),
183 | cmdLineErrOpen: nil,
184 | stat: completeStat,
185 | statErrRead: nil,
186 | statErrOpen: nil,
187 | lstatUid: 0,
188 | lstatErr: nil,
189 | expected: PSEvent{
190 | UID: 0,
191 | PID: 2,
192 | PPID: 5560,
193 | CMD: "???",
194 | },
195 | },
196 | {
197 | name: "cmd-io-error2",
198 | enablePpid: true,
199 | truncate: 100,
200 | pid: 2,
201 | cmdLine: nil,
202 | cmdLineErrRead: nil,
203 | cmdLineErrOpen: errors.New("file-system-error"),
204 | stat: completeStat,
205 | statErrRead: nil,
206 | statErrOpen: nil,
207 | lstatUid: 0,
208 | lstatErr: nil,
209 | expected: PSEvent{
210 | UID: 0,
211 | PID: 2,
212 | PPID: 5560,
213 | CMD: "???",
214 | },
215 | },
216 | {
217 | name: "stat-io-error",
218 | enablePpid: true,
219 | truncate: 100,
220 | pid: 2,
221 | cmdLine: []byte("some\x00cmd\x00123"),
222 | cmdLineErrRead: nil,
223 | cmdLineErrOpen: nil,
224 | stat: nil,
225 | statErrRead: errors.New("file-system-error"),
226 | statErrOpen: nil,
227 | lstatUid: 321,
228 | lstatErr: nil,
229 | expected: PSEvent{
230 | UID: 321,
231 | PID: 2,
232 | PPID: -1,
233 | CMD: "some cmd 123",
234 | },
235 | },
236 | {
237 | name: "stat-io-error2",
238 | enablePpid: true,
239 | truncate: 100,
240 | pid: 2,
241 | cmdLine: []byte("some\x00cmd\x00123"),
242 | cmdLineErrRead: nil,
243 | cmdLineErrOpen: nil,
244 | stat: nil,
245 | statErrRead: nil,
246 | statErrOpen: errors.New("file-system-error"),
247 | lstatUid: 4454,
248 | lstatErr: nil,
249 | expected: PSEvent{
250 | UID: 4454,
251 | PID: 2,
252 | PPID: -1,
253 | CMD: "some cmd 123",
254 | },
255 | },
256 | {
257 | name: "lstat-fail",
258 | enablePpid: false,
259 | truncate: 100,
260 | pid: 3,
261 | cmdLine: []byte("some\x00cmd\x00123"),
262 | cmdLineErrRead: nil,
263 | cmdLineErrOpen: nil,
264 | stat: completeStat,
265 | statErrRead: nil,
266 | statErrOpen: nil,
267 | lstatUid: 0,
268 | lstatErr: errors.New("file not found"),
269 | expected: PSEvent{
270 | UID: -1,
271 | PID: 3,
272 | PPID: -1,
273 | CMD: "some cmd 123",
274 | },
275 | },
276 | {
277 | name: "lstat-with-ppid",
278 | enablePpid: true,
279 | truncate: 100,
280 | pid: 3,
281 | cmdLine: []byte("some\x00cmd\x00123"),
282 | cmdLineErrRead: nil,
283 | cmdLineErrOpen: nil,
284 | stat: completeStat,
285 | statErrRead: nil,
286 | statErrOpen: nil,
287 | lstatUid: 0,
288 | lstatErr: errors.New("file not found"),
289 | expected: PSEvent{
290 | UID: -1,
291 | PID: 3,
292 | PPID: 5560,
293 | CMD: "some cmd 123",
294 | },
295 | },
296 | {
297 | name: "stat-too-short",
298 | enablePpid: true,
299 | truncate: 100,
300 | pid: 3,
301 | cmdLine: []byte("some\x00cmd\x00123"),
302 | cmdLineErrRead: nil,
303 | cmdLineErrOpen: nil,
304 | stat: partialStat,
305 | statErrRead: nil,
306 | statErrOpen: nil,
307 | lstatUid: 66,
308 | lstatErr: nil,
309 | expected: PSEvent{
310 | UID: 66,
311 | PID: 3,
312 | PPID: -1,
313 | CMD: "some cmd 123",
314 | },
315 | },
316 | {
317 | name: "stat-bad-ppid",
318 | enablePpid: true,
319 | truncate: 100,
320 | pid: 3,
321 | cmdLine: []byte("some\x00cmd\x00123"),
322 | cmdLineErrRead: nil,
323 | cmdLineErrOpen: nil,
324 | stat: invalidPpid,
325 | statErrRead: nil,
326 | statErrOpen: nil,
327 | lstatUid: 66,
328 | lstatErr: nil,
329 | expected: PSEvent{
330 | UID: 66,
331 | PID: 3,
332 | PPID: -1,
333 | CMD: "some cmd 123",
334 | },
335 | },
336 | {
337 | name: "stat-empty",
338 | enablePpid: true,
339 | truncate: 100,
340 | pid: 3,
341 | cmdLine: []byte("some\x00cmd\x00123"),
342 | cmdLineErrRead: nil,
343 | cmdLineErrOpen: nil,
344 | stat: []byte{},
345 | statErrRead: nil,
346 | statErrOpen: nil,
347 | lstatUid: 88,
348 | lstatErr: nil,
349 | expected: PSEvent{
350 | UID: 88,
351 | PID: 3,
352 | PPID: -1,
353 | CMD: "some cmd 123",
354 | },
355 | },
356 | /*{
357 | name: "uid-line-too-short",
358 | enablePpid: true,
359 | truncate: 100,
360 | pid: 3,
361 | cmdLine: []byte("some\x00cmd\x00123"),
362 | cmdLineErrRead: nil,
363 | cmdLineErrOpen: nil,
364 | stat: uidLineBroken,
365 | statErrRead: nil,
366 | statErrOpen: nil,
367 | lstatUid: 0,
368 | lstatErr: nil,
369 | expected: PSEvent{
370 | UID: -1,
371 | PID: 3,
372 | PPID: -1,
373 | CMD: "some cmd 123",
374 | },
375 | },
376 | {
377 | name: "uid-parse-error",
378 | enablePpid: true,
379 | truncate: 100,
380 | pid: 3,
381 | cmdLine: []byte("some\x00cmd\x00123"),
382 | cmdLineErrRead: nil,
383 | cmdLineErrOpen: nil,
384 | stat: uidNaN,
385 | statErrRead: nil,
386 | statErrOpen: nil,
387 | lstatUid: 0,
388 | lstatErr: nil,
389 | expected: PSEvent{
390 | UID: -1,
391 | PID: 3,
392 | PPID: -1,
393 | CMD: "some cmd 123",
394 | },
395 | },
396 | {
397 | name: "ppid-line-too-short",
398 | enablePpid: true,
399 | truncate: 100,
400 | pid: 3,
401 | cmdLine: []byte("some\x00cmd\x00123"),
402 | cmdLineErrRead: nil,
403 | cmdLineErrOpen: nil,
404 | stat: ppidLineShort,
405 | statErrRead: nil,
406 | statErrOpen: nil,
407 | lstatUid: 0,
408 | lstatErr: nil,
409 | expected: PSEvent{
410 | UID: -1,
411 | PID: 3,
412 | PPID: -1,
413 | CMD: "some cmd 123",
414 | },
415 | },
416 | {
417 | name: "ppid-parse-error",
418 | enablePpid: true,
419 | truncate: 100,
420 | pid: 3,
421 | cmdLine: []byte("some\x00cmd\x00123"),
422 | cmdLineErrRead: nil,
423 | cmdLineErrOpen: nil,
424 | stat: ppidNaN,
425 | statErrRead: nil,
426 | statErrOpen: nil,
427 | lstatUid: 0,
428 | lstatErr: nil,
429 | expected: PSEvent{
430 | UID: -1,
431 | PID: 3,
432 | PPID: -1,
433 | CMD: "some cmd 123",
434 | },
435 | },
436 | {
437 | name: "no-ppid-line-too-short",
438 | enablePpid: false,
439 | truncate: 100,
440 | pid: 3,
441 | cmdLine: []byte("some\x00cmd\x00123"),
442 | cmdLineErrRead: nil,
443 | cmdLineErrOpen: nil,
444 | stat: ppidLineShort,
445 | statErrRead: nil,
446 | statErrOpen: nil,
447 | lstatUid: 0,
448 | lstatErr: nil,
449 | expected: PSEvent{
450 | UID: 0,
451 | PID: 3,
452 | PPID: -1,
453 | CMD: "some cmd 123",
454 | },
455 | },
456 | {
457 | name: "no-ppid-parse-error",
458 | enablePpid: false,
459 | truncate: 100,
460 | pid: 3,
461 | cmdLine: []byte("some\x00cmd\x00123"),
462 | cmdLineErrRead: nil,
463 | cmdLineErrOpen: nil,
464 | stat: ppidNaN,
465 | statErrRead: nil,
466 | statErrOpen: nil,
467 | lstatUid: 0,
468 | lstatErr: nil,
469 | expected: PSEvent{
470 | UID: 0,
471 | PID: 3,
472 | PPID: -1,
473 | CMD: "some cmd 123",
474 | },
475 | },*/
476 | }
477 |
478 | for _, tt := range tests {
479 | t.Run(tt.name, func(t *testing.T) {
480 | defer mockPidCmdLine(tt.pid, tt.cmdLine, tt.cmdLineErrRead, tt.cmdLineErrOpen, t)()
481 | defer mockPidStat(tt.pid, tt.stat, tt.statErrRead, tt.statErrOpen, t)()
482 | defer mockPidUid(tt.pid, tt.lstatUid, tt.lstatErr, t)()
483 |
484 | results := make(chan PSEvent, 1)
485 |
486 | scanner := &PSScanner{
487 | enablePpid: tt.enablePpid,
488 | eventCh: results,
489 | maxCmdLength: tt.truncate,
490 | }
491 |
492 | go func() {
493 | scanner.processNewPid(tt.pid)
494 | }()
495 |
496 | select {
497 | case <-time.After(timeout):
498 | t.Error("Timeout waiting for event")
499 | case event := <-results:
500 | close(results)
501 | if testing.Verbose() {
502 | t.Logf("received event: %#v", event)
503 | }
504 | if !reflect.DeepEqual(event, tt.expected) {
505 | t.Errorf("Event received but format is has unexpected values: got %#v but want %#v", event, tt.expected)
506 | }
507 | }
508 | })
509 | }
510 | }
511 |
512 | func mockPidStat(pid int, stat []byte, errRead error, errOpen error, t *testing.T) func() {
513 | return mockFile(fmt.Sprintf("/proc/%d/stat", pid), stat, errRead, errOpen, t)
514 | }
515 |
516 | func mockPidCmdLine(pid int, cmdline []byte, errRead error, errOpen error, t *testing.T) func() {
517 | return mockFile(fmt.Sprintf("/proc/%d/cmdline", pid), cmdline, errRead, errOpen, t)
518 | }
519 |
520 | type MockFile struct {
521 | content []byte
522 | err error
523 | }
524 |
525 | func (f *MockFile) Close() error {
526 | return nil
527 | }
528 |
529 | func (f *MockFile) Read(p []byte) (int, error) {
530 | return copy(p, f.content), f.err
531 | }
532 |
533 | // Hook/chain a mocked file into the "open" variable
534 | func mockFile(name string, content []byte, errRead error, errOpen error, t *testing.T) func() {
535 | oldopen := open
536 | open = func(n string) (io.ReadCloser, error) {
537 | if name == n {
538 | if testing.Verbose() {
539 | t.Logf("opening mocked file: %s", n)
540 | }
541 | return &MockFile{
542 | content: content,
543 | err: errRead,
544 | }, errOpen
545 | }
546 | return oldopen(n)
547 | }
548 | return func() {
549 | open = oldopen
550 | }
551 | }
552 |
553 | func mockPidUid(pid int, uid uint32, err error, t *testing.T) func() {
554 | return mockLStat(fmt.Sprintf("/proc/%d", pid), uid, err, t)
555 | }
556 |
557 | func mockLStat(name string, uid uint32, err error, t *testing.T) func() {
558 | oldlstat := lstat
559 | lstat = func(path string, stat *syscall.Stat_t) error {
560 | if path == name {
561 | if testing.Verbose() {
562 | t.Logf("mocking lstat for %s", name)
563 | }
564 | stat.Uid = uid
565 | return err
566 | }
567 | return oldlstat(path, stat)
568 | }
569 | return func() {
570 | lstat = oldlstat
571 | }
572 | }
573 |
574 | func TestNewPSScanner(t *testing.T) {
575 | for _, tt := range []struct {
576 | name string
577 | ppid bool
578 | cmdlen int
579 | }{
580 | {
581 | name: "without-ppid",
582 | ppid: false,
583 | cmdlen: 30,
584 | },
585 | {
586 | name: "with-ppid",
587 | ppid: true,
588 | cmdlen: 5000,
589 | },
590 | } {
591 | t.Run(tt.name, func(t *testing.T) {
592 | expected := &PSScanner{
593 | enablePpid: tt.ppid,
594 | eventCh: nil,
595 | maxCmdLength: tt.cmdlen,
596 | }
597 | new := NewPSScanner(tt.ppid, tt.cmdlen)
598 |
599 | if !reflect.DeepEqual(new, expected) {
600 | t.Errorf("Unexpected scanner initialisation state: got %#v but want %#v", new, expected)
601 | }
602 |
603 | })
604 | }
605 | }
606 |
607 | func TestPSEvent(t *testing.T) {
608 | tests := []struct {
609 | name string
610 | uid int
611 | pid int
612 | ppid int
613 | cmd string
614 | expected string
615 | }{
616 | {
617 | name: "nominal-with-ppid",
618 | uid: 999,
619 | pid: 123,
620 | ppid: 321,
621 | cmd: "some cmd",
622 | expected: "UID=999 PID=123 PPID=321 | some cmd",
623 | },
624 | {
625 | name: "nominal-without-ppid",
626 | uid: 999,
627 | pid: 123,
628 | ppid: -1,
629 | cmd: "some cmd",
630 | expected: "UID=999 PID=123 | some cmd",
631 | },
632 | {
633 | name: "nocmd-without-ppid",
634 | uid: 999,
635 | pid: 123,
636 | ppid: -1,
637 | cmd: "",
638 | expected: "UID=999 PID=123 | ",
639 | },
640 | {
641 | name: "nocmd-with-ppid",
642 | uid: 999,
643 | pid: 123,
644 | ppid: 321,
645 | cmd: "",
646 | expected: "UID=999 PID=123 PPID=321 | ",
647 | },
648 | {
649 | name: "nouid",
650 | uid: -1,
651 | pid: 123,
652 | ppid: 321,
653 | cmd: "some cmd",
654 | expected: "UID=??? PID=123 PPID=321 | some cmd",
655 | },
656 | }
657 |
658 | for _, tt := range tests {
659 | t.Run(tt.name, func(t *testing.T) {
660 | ps := PSEvent{
661 | UID: tt.uid,
662 | PID: tt.pid,
663 | PPID: tt.ppid,
664 | CMD: tt.cmd,
665 | }
666 | if ps.String() != tt.expected {
667 | t.Errorf("Expecting \"%s\", got \"%s\"", tt.expected, ps.String())
668 | }
669 | })
670 | }
671 | }
672 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/dominicbreuker/pspy/cmd"
7 | )
8 |
9 | var version string
10 | var commit string
11 |
12 | func main() {
13 | fmt.Printf("pspy - version: %s - Commit SHA: %s\n", version, commit)
14 | cmd.Execute()
15 | }
16 |
--------------------------------------------------------------------------------