├── .bzrignore
├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── AUTHORS
├── BUILD_CONFIG
├── COPYING
├── INSTALL
├── LICENSE.md
├── NOTES
├── README.md
├── build-deb.sh
├── build-installers.sh
├── build-source.sh
├── build.sh
├── debian
├── changelog
├── compat
├── control
├── copyright
├── docs
├── rules
└── source
│ └── format
├── images
└── options.png
├── makefile
├── release
└── sanity.config
└── src
├── Console
├── CryptTabEntry.vala
├── FsTabEntry.vala
├── GrootConsole.vala
├── LinuxDistro.vala
└── MountEntryManager.vala
├── Messages.vala
├── README
├── Utility
├── Console
│ ├── Device.vala
│ ├── MountEntry.vala
│ ├── TeeJee.FileSystem.vala
│ ├── TeeJee.Logging.vala
│ ├── TeeJee.Misc.vala
│ ├── TeeJee.Process.vala
│ └── TeeJee.System.vala
└── TeeJee.JsonHelper.vala
├── makefile
└── share
└── polkit-1
└── actions
└── in.teejeetech.pkexec.groot.policy
/.bzrignore:
--------------------------------------------------------------------------------
1 | src/groot
2 | designs/
3 | release/source
4 | release/amd64
5 | release/i386
6 | release/armel
7 | release/armhf
8 | release/*.deb
9 | release/*.run
10 | *.geany
11 | .git
12 | *.c
13 | *.o
14 | *~
15 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 |
5 | ---
6 |
7 | **Describe the bug**
8 | A clear and concise description of what the bug is.
9 |
10 | **To Reproduce**
11 | Steps to reproduce the behavior:
12 | 1. Go to '...'
13 | 2. Click on '....'
14 | 3. Error message
15 |
16 | **Expected behavior**
17 | A clear and concise description of what you expected to happen.
18 |
19 | **Screenshots**
20 | If applicable, add screenshots to help explain your problem.
21 |
22 | **System:**
23 | - Linux Distribution Name and Version: [e.g. Ubuntu 16.04]
24 | - Desktop [e.g. MATE, XFCE]
25 | - Application Version [e.g. v18.8]
26 |
27 | ***This is a free application created in my spare time. Consider making a donation if you need support for an issue.***
28 |
29 | [](https://www.paypal.com/cgi-bin/webscr?business=teejeetech@gmail.com&cmd=_xclick¤cy_code=USD&item_name=Groot%20Donation)
30 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem? Please describe.**
8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
9 |
10 | **Describe the solution you'd like**
11 | A clear and concise description of what you want to happen.
12 |
13 | **Describe alternatives you've considered**
14 | A clear and concise description of any alternative solutions or features you've considered.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
19 | ***This is a free application created in my spare time. Consider making a donation to sponsor the work for your request.***
20 |
21 | [](https://www.paypal.com/cgi-bin/webscr?business=teejeetech@gmail.com&cmd=_xclick¤cy_code=USD&item_name=Groot%20Donation)
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | src/groot
2 | designs/
3 | release/source
4 | release/amd64
5 | release/i386
6 | release/armel
7 | release/armhf
8 | release/*.deb
9 | release/*.run
10 | *.geany
11 | .bzr
12 | *.c
13 | *.o
14 | *~
15 |
--------------------------------------------------------------------------------
/AUTHORS:
--------------------------------------------------------------------------------
1 |
2 | Copyright (C) 2017 Tony George (teejeetech@gmail.com)
3 |
4 |
--------------------------------------------------------------------------------
/BUILD_CONFIG:
--------------------------------------------------------------------------------
1 |
2 | app_fullname="GRoot"
3 | app_name="groot"
4 | pkg_name="groot"
5 | pkg_version=$(dpkg-parsechangelog --show-field Version)
6 | git_origin=""
7 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/INSTALL:
--------------------------------------------------------------------------------
1 |
2 | # build
3 | make all
4 |
5 | # install
6 | sudo make install
7 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 |
2 | GNU LESSER GENERAL PUBLIC LICENSE
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 |
10 | This version of the GNU Lesser General Public License incorporates
11 | the terms and conditions of version 3 of the GNU General Public
12 | License, supplemented by the additional permissions listed below.
13 |
14 | 0. Additional Definitions.
15 |
16 | As used herein, "this License" refers to version 3 of the GNU Lesser
17 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
18 | General Public License.
19 |
20 | "The Library" refers to a covered work governed by this License,
21 | other than an Application or a Combined Work as defined below.
22 |
23 | An "Application" is any work that makes use of an interface provided
24 | by the Library, but which is not otherwise based on the Library.
25 | Defining a subclass of a class defined by the Library is deemed a mode
26 | of using an interface provided by the Library.
27 |
28 | A "Combined Work" is a work produced by combining or linking an
29 | Application with the Library. The particular version of the Library
30 | with which the Combined Work was made is also called the "Linked
31 | Version".
32 |
33 | The "Minimal Corresponding Source" for a Combined Work means the
34 | Corresponding Source for the Combined Work, excluding any source code
35 | for portions of the Combined Work that, considered in isolation, are
36 | based on the Application, and not on the Linked Version.
37 |
38 | The "Corresponding Application Code" for a Combined Work means the
39 | object code and/or source code for the Application, including any data
40 | and utility programs needed for reproducing the Combined Work from the
41 | Application, but excluding the System Libraries of the Combined Work.
42 |
43 | 1. Exception to Section 3 of the GNU GPL.
44 |
45 | You may convey a covered work under sections 3 and 4 of this License
46 | without being bound by section 3 of the GNU GPL.
47 |
48 | 2. Conveying Modified Versions.
49 |
50 | If you modify a copy of the Library, and, in your modifications, a
51 | facility refers to a function or data to be supplied by an Application
52 | that uses the facility (other than as an argument passed when the
53 | facility is invoked), then you may convey a copy of the modified
54 | version:
55 |
56 | a) under this License, provided that you make a good faith effort to
57 | ensure that, in the event an Application does not supply the
58 | function or data, the facility still operates, and performs
59 | whatever part of its purpose remains meaningful, or
60 |
61 | b) under the GNU GPL, with none of the additional permissions of
62 | this License applicable to that copy.
63 |
64 | 3. Object Code Incorporating Material from Library Header Files.
65 |
66 | The object code form of an Application may incorporate material from
67 | a header file that is part of the Library. You may convey such object
68 | code under terms of your choice, provided that, if the incorporated
69 | material is not limited to numerical parameters, data structure
70 | layouts and accessors, or small macros, inline functions and templates
71 | (ten or fewer lines in length), you do both of the following:
72 |
73 | a) Give prominent notice with each copy of the object code that the
74 | Library is used in it and that the Library and its use are
75 | covered by this License.
76 |
77 | b) Accompany the object code with a copy of the GNU GPL and this license
78 | document.
79 |
80 | 4. Combined Works.
81 |
82 | You may convey a Combined Work under terms of your choice that,
83 | taken together, effectively do not restrict modification of the
84 | portions of the Library contained in the Combined Work and reverse
85 | engineering for debugging such modifications, if you also do each of
86 | the following:
87 |
88 | a) Give prominent notice with each copy of the Combined Work that
89 | the Library is used in it and that the Library and its use are
90 | covered by this License.
91 |
92 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
93 | document.
94 |
95 | c) For a Combined Work that displays copyright notices during
96 | execution, include the copyright notice for the Library among
97 | these notices, as well as a reference directing the user to the
98 | copies of the GNU GPL and this license document.
99 |
100 | d) Do one of the following:
101 |
102 | 0) Convey the Minimal Corresponding Source under the terms of this
103 | License, and the Corresponding Application Code in a form
104 | suitable for, and under terms that permit, the user to
105 | recombine or relink the Application with a modified version of
106 | the Linked Version to produce a modified Combined Work, in the
107 | manner specified by section 6 of the GNU GPL for conveying
108 | Corresponding Source.
109 |
110 | 1) Use a suitable shared library mechanism for linking with the
111 | Library. A suitable mechanism is one that (a) uses at run time
112 | a copy of the Library already present on the user's computer
113 | system, and (b) will operate properly with a modified version
114 | of the Library that is interface-compatible with the Linked
115 | Version.
116 |
117 | e) Provide Installation Information, but only if you would otherwise
118 | be required to provide such information under section 6 of the
119 | GNU GPL, and only to the extent that such information is
120 | necessary to install and execute a modified version of the
121 | Combined Work produced by recombining or relinking the
122 | Application with a modified version of the Linked Version. (If
123 | you use option 4d0, the Installation Information must accompany
124 | the Minimal Corresponding Source and Corresponding Application
125 | Code. If you use option 4d1, you must provide the Installation
126 | Information in the manner specified by section 6 of the GNU GPL
127 | for conveying Corresponding Source.)
128 |
129 | 5. Combined Libraries.
130 |
131 | You may place library facilities that are a work based on the
132 | Library side by side in a single library together with other library
133 | facilities that are not Applications and are not covered by this
134 | License, and convey such a combined library under terms of your
135 | choice, if you do both of the following:
136 |
137 | a) Accompany the combined library with a copy of the same work based
138 | on the Library, uncombined with any other library facilities,
139 | conveyed under the terms of this License.
140 |
141 | b) Give prominent notice with the combined library that part of it
142 | is a work based on the Library, and explaining where to find the
143 | accompanying uncombined form of the same work.
144 |
145 | 6. Revised Versions of the GNU Lesser General Public License.
146 |
147 | The Free Software Foundation may publish revised and/or new versions
148 | of the GNU Lesser General Public License from time to time. Such new
149 | versions will be similar in spirit to the present version, but may
150 | differ in detail to address new problems or concerns.
151 |
152 | Each version is given a distinguishing version number. If the
153 | Library as you received it specifies that a certain numbered version
154 | of the GNU Lesser General Public License "or any later version"
155 | applies to it, you have the option of following the terms and
156 | conditions either of that published version or of any later version
157 | published by the Free Software Foundation. If the Library as you
158 | received it does not specify a version number of the GNU Lesser
159 | General Public License, you may choose any version of the GNU Lesser
160 | General Public License ever published by the Free Software Foundation.
161 |
162 | If the Library as you received it specifies that a proxy can decide
163 | whether future versions of the GNU Lesser General Public License shall
164 | apply, that proxy's public statement of acceptance of any version is
165 | permanent authorization for you to choose that version for the
166 | Library.
167 |
--------------------------------------------------------------------------------
/NOTES:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teejee2008/groot/ab40dab12b041477ccd53e71c8766e0032d6265b/NOTES
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Groot
2 |
3 | Groot is a tiny utility for chrooting into an installed Linux system. It is similar to the **arch-chroot** command available on Arch Linux, and is based on the same script. It can be used on any Linux distribution.
4 |
5 | ### Chroot Basics
6 |
7 | A chroot session changes the effective root directory to a specified path where another Linux system is installed. Applications running inside the chroot will only affect the chrooted system and cannot access or modify files outside the chroot jail.
8 |
9 | This is useful for maintenance activities. You can add/remove software and run commands for updating the chrooted system. You can fix boot issues, and execute GUI applications without any worry of the applications affecting your current system.
10 |
11 | Chroot requires root access. The current system (host) and the chrooted system (guest) must have the same architecture (i686, x86_64, etc). The host kernel is shared with guest system. Kernel modules required by the guest must be loaded on the host.
12 |
13 | ## Usage
14 |
15 | 
16 |
17 | To chroot into a system, open a terminal window, **cd** to path where root filesystem is mounted and run the **groot** command.
18 |
19 | ```
20 | cd /media/usbdrive
21 | sudo groot
22 | ```
23 |
24 | This will mount `/dev`, `/run`, `/sys` and other system directories; and chroot to the current directory.
25 |
26 | You can also specify root path as an optional argument.
27 |
28 | ```
29 | sudo groot /mnt/usbdrive
30 | ```
31 |
32 | Type **exit** when you are done, to exit the session cleanly. *This is important*. If you don’t exit the session properly, the system subdirectories will remain mounted, and you may have to reboot the system.
33 |
34 | **Internet Sharing**
35 |
36 | Internet connection sharing is enabled by default. You can run commands that access the internet. Use option `--no-internet` if internet sharing is not required.
37 |
38 | **Display Sharing**
39 |
40 | Display sharing is enabled by default. You can run GUI applications that are installed on chrooted system. Use option `--no-display` if display sharing is not required.
41 |
42 | ## Features
43 |
44 | * Automatic mounting and unmounting of /dev, /run, /proc, /sys and other system directories
45 | * Enables internet sharing to allow applications to connect to internet from chroot session
46 | * Enables display sharing to allow GUI applications to run from chroot session
47 |
48 | **Planned features:**
49 |
50 | * Repairing boot issues on BIOS and EFI systems
51 | * Re-install GRUB, rebuild initramfs, update grub menu, etc
52 |
53 | ## Installation
54 |
55 | Binary installers are available on the [Releases](https://github.com/teejee2008/groot/releases) page.
56 |
57 | You can download and install the latest release of groot on any Linux distribution, using the following one-line commands:
58 |
59 | ```sh
60 | # 64-bit
61 | cd /tmp && curl -s -L https://github.com/teejee2008/groot/releases/latest | egrep -o 'teejee2008/groot/releases/download/.*/groot-v[0-9.]*-amd64.run' | wget --base=http://github.com/ -i - -O groot-latest-amd64.run && sudo chmod a+x ./groot-latest-amd64.run && sudo ./groot-latest-amd64.run
62 | ```
63 | ```sh
64 | # 32-bit
65 | cd /tmp && curl -s -L https://github.com/teejee2008/groot/releases/latest | egrep -o 'teejee2008/groot/releases/download/.*/groot-v[0-9.]*-i386.run' | wget --base=http://github.com/ -i - -O groot-latest-i386.run && sudo chmod a+x ./groot-latest-i386.run && sudo ./groot-latest-i386.run
66 | ```
67 |
68 | ## Donate
69 |
70 | **PayPal** ~ If you find this application useful and wish to say thanks, you can buy me a coffee by making a one-time donation with Paypal.
71 |
72 | [](https://www.paypal.com/cgi-bin/webscr?business=teejeetech@gmail.com&cmd=_xclick¤cy_code=USD&amount=10&item_name=Groot%20Donation)
73 |
74 | **Patreon** ~ You can also sign up as a sponsor on Patreon.com. As a patron you will get access to beta releases of new applications that I'm working on. You will also get news and updates about new features that are not published elsewhere.
75 |
76 | [](https://www.patreon.com/bePatron?u=3059450)
77 |
78 | **Bitcoin** ~ You can send bitcoins at this address or by scanning the QR code below:
79 |
80 | ```1Js5vfgmwKew4byF9unWacwAjBQVvZ3Fev```
81 |
82 | 
83 |
--------------------------------------------------------------------------------
/build-deb.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | backup=`pwd`
4 | DIR="$( cd "$( dirname "$0" )" && pwd )"
5 | cd $DIR
6 |
7 | . ./BUILD_CONFIG
8 |
9 | sh build-source.sh
10 |
11 | rm -fv release/${pkg_name}-*.deb
12 |
13 | build_deb_for_dist() {
14 |
15 | dist=$1
16 | arch=$2
17 |
18 | echo ""
19 | echo "=========================================================================="
20 | echo " build-deb.sh : $dist-$arch"
21 | echo "=========================================================================="
22 | echo ""
23 |
24 | rm -rfv release/${arch}
25 | mkdir -pv release/${arch}
26 |
27 | echo "-------------------------------------------------------------------------"
28 |
29 | pbuilder-dist $dist $arch build release/source/${pkg_name}*.dsc --buildresult release/$arch
30 |
31 | if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi
32 |
33 | echo "--------------------------------------------------------------------------"
34 |
35 | cp -pv --no-preserve=ownership release/${arch}/${pkg_name}*.deb release/${pkg_name}-v${pkg_version}-${arch}.deb
36 |
37 | if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi
38 |
39 | echo "--------------------------------------------------------------------------"
40 |
41 | }
42 |
43 | build_deb_for_dist xenial i386
44 | build_deb_for_dist xenial amd64
45 | #build_deb_for_dist stretch armel
46 | #build_deb_for_dist stretch armhf
47 |
48 | cd "$backup"
49 |
--------------------------------------------------------------------------------
/build-installers.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | backup=`pwd`
4 | DIR="$( cd "$( dirname "$0" )" && pwd )"
5 | cd $DIR
6 |
7 | . ./BUILD_CONFIG
8 |
9 | rm -vf release/*.run
10 | rm -vf release/*.deb
11 |
12 | # build debs
13 | sh build-deb.sh
14 |
15 |
16 | for arch in i386 amd64
17 | do
18 |
19 | rm -rfv release/${arch}/files
20 | mkdir -pv release/${arch}/files
21 |
22 | echo ""
23 | echo "=========================================================================="
24 | echo " build-installers.sh : $arch"
25 | echo "=========================================================================="
26 | echo ""
27 |
28 | dpkg-deb -x release/${pkg_name}-v${pkg_version}-${arch}.deb release/${arch}/files
29 |
30 | if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1;fi
31 |
32 | echo "--------------------------------------------------------------------------"
33 |
34 | rm -rfv release/${arch}/${pkg_name}*.* # remove source files created by pbuilder
35 | cp -pv --no-preserve=ownership release/sanity.config release/${arch}/sanity.config
36 | sanity --generate --base-path release/${arch} --out-path release --arch ${arch} --xz
37 |
38 | if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi
39 |
40 | mv -v release/*${arch}.run release/${pkg_name}-v${pkg_version}-${arch}.run
41 |
42 | echo "--------------------------------------------------------------------------"
43 |
44 | done
45 |
46 | cp -vf release/*.run ../PACKAGES/
47 | cp -vf release/*.deb ../PACKAGES/
48 |
49 | cd "$backup"
50 |
--------------------------------------------------------------------------------
/build-source.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | backup=`pwd`
4 | DIR="$( cd "$( dirname "$0" )" && pwd )"
5 | cd "$DIR"
6 |
7 | . ./BUILD_CONFIG
8 |
9 | echo ""
10 | echo "=========================================================================="
11 | echo " build-source.sh"
12 | echo "=========================================================================="
13 | echo ""
14 |
15 | echo "app_name: $app_name"
16 | echo "pkg_name: $pkg_name"
17 | echo "--------------------------------------------------------------------------"
18 |
19 | # clean build dir
20 |
21 | rm -rfv /tmp/builds
22 | mkdir -pv /tmp/builds
23 |
24 | make clean
25 |
26 | rm -rfv release/source
27 | mkdir -pv release/source
28 |
29 | echo "--------------------------------------------------------------------------"
30 |
31 | # build source package
32 | dpkg-source --build ./
33 |
34 | mv -vf ../$pkg_name*.dsc release/source/
35 | mv -vf ../$pkg_name*.tar.xz release/source/
36 |
37 | if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi
38 |
39 | echo "--------------------------------------------------------------------------"
40 |
41 | # list files
42 | ls -l release/source
43 |
44 | echo "-------------------------------------------------------------------------"
45 |
46 | cd "$backup"
47 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 |
2 | make 2>&1 | grep -E --color=never 'error:|.vala:.*warning:' | grep -E --color=always "error:|$"
3 |
--------------------------------------------------------------------------------
/debian/changelog:
--------------------------------------------------------------------------------
1 | groot (18.8) xenial; urgency=medium
2 |
3 | * Added command --fixboot for fixing boot issues
4 |
5 | * Added command --update for installing package updates
6 |
7 | * Added command --guestinfo for showing guest system info
8 |
9 | -- Tony George Sun, 26 Aug 2018 10:00:00 +0530
10 |
11 |
12 | groot (18.1) xenial; urgency=medium
13 |
14 | * Added command: --chroot-fstab
15 |
16 | * Added option: --verbose
17 |
18 | * Set environment variables for chroot session from guest system
19 |
20 | * Use XZ compression for installers
21 |
22 | -- Tony George Sat, 20 Jan 2018 10:00:00 +0530
23 |
24 |
25 | groot (17.12) xenial; urgency=medium
26 |
27 | * Initial release
28 |
29 | -- Tony George Fri, 01 Dec 2017 08:00:00 +0530
30 |
--------------------------------------------------------------------------------
/debian/compat:
--------------------------------------------------------------------------------
1 | 9
2 |
--------------------------------------------------------------------------------
/debian/control:
--------------------------------------------------------------------------------
1 | Source: groot
2 | Section: utils
3 | Priority: extra
4 | Maintainer: Tony George
5 | Build-Depends: debhelper (>= 8.0.0), autotools-dev, valac, libgee-0.8-dev, libjson-glib-dev
6 | Standards-Version: 3.9.3
7 | Homepage: http://teejeetech.blogspot.in/
8 | #Vcs-Git:
9 | #Vcs-Browser:
10 |
11 | Package: groot
12 | Architecture: any
13 | Depends: ${shlibs:Depends}, ${misc:Depends}, apt, aptitude, gdebi, apt-transport-https, pv
14 | #Recommends:
15 | #Replaces:
16 | Description: Chroot Utility for all Linux distributions
17 | Chroot Utility for all Linux distributions
18 |
--------------------------------------------------------------------------------
/debian/copyright:
--------------------------------------------------------------------------------
1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2 | Upstream-Name: groot
3 | Source:
4 |
5 | Files: *
6 | Copyright: 2013 Tony George
7 | License: GPL-2+
8 | This package is free software; you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation; either version 2 of the License, or
11 | (at your option) any later version.
12 | .
13 | This package is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 | .
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see
20 | .
21 | On Debian systems, the complete text of the GNU General
22 | Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
23 |
24 |
--------------------------------------------------------------------------------
/debian/docs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teejee2008/groot/ab40dab12b041477ccd53e71c8766e0032d6265b/debian/docs
--------------------------------------------------------------------------------
/debian/rules:
--------------------------------------------------------------------------------
1 | #!/usr/bin/make -f
2 | # -*- makefile -*-
3 | # Sample debian/rules that uses debhelper.
4 | # This file was originally written by Joey Hess and Craig Small.
5 | # As a special exception, when this file is copied by dh-make into a
6 | # dh-make output file, you may use that output file without restriction.
7 | # This special exception was added by Craig Small in version 0.37 of dh-make.
8 |
9 | # Uncomment this to turn on verbose mode.
10 | #export DH_VERBOSE=1
11 |
12 | override_dh_usrlocal:
13 |
14 | %:
15 | dh $@ --with autotools-dev
16 |
--------------------------------------------------------------------------------
/debian/source/format:
--------------------------------------------------------------------------------
1 | 3.0 (native)
2 |
--------------------------------------------------------------------------------
/images/options.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/teejee2008/groot/ab40dab12b041477ccd53e71c8766e0032d6265b/images/options.png
--------------------------------------------------------------------------------
/makefile:
--------------------------------------------------------------------------------
1 | all:
2 | cd src; make all
3 |
4 | clean:
5 | cd src; make clean
6 |
7 | groot-console:
8 | cd src; make groot-console
9 |
10 | install:
11 | cd src; make install
12 |
13 | uninstall:
14 | cd src; make uninstall
15 |
--------------------------------------------------------------------------------
/release/sanity.config:
--------------------------------------------------------------------------------
1 | app_name: groot
2 | depends_debian: libgee-0.8-2
3 | depends_redhat: libgee
4 | depends_arch: libgee
5 | depends_generic: libgee
6 | assume_yes: 0
7 | exec_line: sudo groot --help
8 |
--------------------------------------------------------------------------------
/src/Console/CryptTabEntry.vala:
--------------------------------------------------------------------------------
1 | /*
2 | * CryptTabEntry.vala
3 | *
4 | * Copyright 2017 Tony George
5 | *
6 | * This program is free software; you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation; either version 2 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 | * MA 02110-1301, USA.
20 | *
21 | *
22 | */
23 |
24 | using TeeJee.Logging;
25 | using TeeJee.FileSystem;
26 | using TeeJee.ProcessHelper;
27 |
28 | public class CryptTabEntry : GLib.Object {
29 |
30 | public string name = "";
31 | public string device = "";
32 | public string password = "";
33 | public string options = "";
34 |
35 | public bool is_selected = false;
36 |
37 | public string get_line(){
38 | return "%s\t%s\t%s\t%s".printf(name,device,password,options);
39 | }
40 |
41 | public void print_line(){
42 | log_msg("%-30s %-30s %-30s %-30s".printf(name,device,password,options));
43 | }
44 |
45 | public bool uses_keyfile {
46 | get {
47 | return (password.length > 0) && (password != "none") && !password.has_prefix("/dev/");
48 | }
49 | }
50 | }
51 |
52 |
--------------------------------------------------------------------------------
/src/Console/FsTabEntry.vala:
--------------------------------------------------------------------------------
1 | /*
2 | * FsTabEntry.vala
3 | *
4 | * Copyright 2017 Tony George
5 | *
6 | * This program is free software; you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation; either version 2 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 | * MA 02110-1301, USA.
20 | *
21 | *
22 | */
23 |
24 | using TeeJee.Logging;
25 | using TeeJee.FileSystem;
26 | using TeeJee.ProcessHelper;
27 |
28 | public class FsTabEntry : GLib.Object {
29 |
30 | public string device = "";
31 | public string mount_point = "";
32 | public string fs_type = "";
33 | public string options = "";
34 | public string dump = "";
35 | public string pass = "";
36 |
37 | public bool is_selected = false;
38 |
39 | public string get_line(){
40 | return "%s\t%s\t%s\t%s\t%s\t%s".printf(device,mount_point,fs_type,options,dump,pass);
41 | }
42 |
43 | public void print_line(){
44 | log_msg("%-45s %-40s %-10s %-45s %2s %2s".printf(device,mount_point,fs_type,options,dump,pass));
45 | }
46 |
47 | public Device? get_device(Gee.ArrayList devices){
48 |
49 | return Device.find_device_in_list(devices, device);
50 | }
51 | }
52 |
53 |
--------------------------------------------------------------------------------
/src/Console/GrootConsole.vala:
--------------------------------------------------------------------------------
1 | /*
2 | * GrootConsole.vala
3 | *
4 | * Copyright 2012-2017 Tony George
5 | *
6 | * This program is free software; you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation; either version 2 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 | * MA 02110-1301, USA.
20 | *
21 | *
22 | */
23 |
24 | using GLib;
25 | using Gee;
26 |
27 | using TeeJee.Logging;
28 | using TeeJee.FileSystem;
29 | using TeeJee.ProcessHelper;
30 | using TeeJee.System;
31 | using TeeJee.Misc;
32 |
33 | public const string AppName = "Groot";
34 | public const string AppShortName = "groot";
35 | public const string AppVersion = "18.8";
36 | public const string AppAuthor = "Tony George";
37 | public const string AppAuthorEmail = "teejeetech@gmail.com";
38 |
39 | const string GETTEXT_PACKAGE = "";
40 | const string LOCALE_DIR = "/usr/share/locale";
41 |
42 | extern void exit(int exit_code);
43 |
44 | public class GrootConsole : GLib.Object {
45 |
46 | public string basepath = "";
47 | public string basepath_bkup = "";
48 | public bool verbose = false;
49 | public bool mount_fstab = false;
50 | public bool fix_boot = false;
51 | public bool install_updates = false;
52 |
53 | public bool share_internet = true;
54 | public bool share_display = true;
55 |
56 | public LinuxDistro distro = null;
57 |
58 | private string resolv_conf_bkup = "";
59 |
60 | public static int main (string[] args) {
61 |
62 | set_locale();
63 |
64 | LOG_TIMESTAMP = false;
65 |
66 | //LOG_DEBUG = true;
67 |
68 | init_tmp(AppShortName);
69 |
70 | check_dependencies();
71 |
72 | Device.init();
73 |
74 | //Device.test_all();
75 |
76 | var console = new GrootConsole();
77 | bool is_success = console.parse_arguments(args);
78 | return (is_success) ? 0 : 1;
79 | }
80 |
81 | private static void set_locale() {
82 |
83 | Intl.setlocale(GLib.LocaleCategory.MESSAGES, "groot");
84 | Intl.textdomain(GETTEXT_PACKAGE);
85 | Intl.bind_textdomain_codeset(GETTEXT_PACKAGE, "utf-8");
86 | Intl.bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
87 | }
88 |
89 | public static void check_dependencies(){
90 |
91 | string[] dependencies = {
92 | "mount", "umount", "xhost", "chroot", "unshare"
93 | };
94 |
95 | string missing = "";
96 |
97 | foreach(string cmd in dependencies){
98 |
99 | if (!cmd_exists(cmd)){
100 |
101 | if (missing.length > 0){
102 | missing = ", ";
103 | }
104 | missing += cmd;
105 | }
106 | }
107 |
108 | if (missing.length > 0){
109 | string msg ="%s: %s".printf(Messages.MISSING_COMMAND, missing);
110 | log_error(msg);
111 | log_error(_("Install required packages for missing commands"));
112 | exit(1);
113 | }
114 | }
115 |
116 | public void check_admin_access(){
117 |
118 | if (!user_is_admin()) {
119 | log_msg(_("groot needs admin access to change root"));
120 | log_msg(_("Run groot as admin (using 'sudo' or 'pkexec')"));
121 | exit(0);
122 | }
123 | }
124 |
125 | public GrootConsole(){
126 |
127 | distro = new LinuxDistro();
128 |
129 | basepath = Environment.get_current_dir();
130 | }
131 |
132 | public void print_backup_path(){
133 |
134 | log_msg("Backup path: %s".printf(basepath));
135 | log_msg(string.nfill(70,'-'));
136 | }
137 |
138 | public string help_message() {
139 |
140 | string fmt = " %-20s %s\n";
141 |
142 | //string fmt2 = "--- %s -----------------------------------\n\n"; //▰▰▰ ◈
143 |
144 | string msg = "\n" + AppName + " v" + AppVersion + " by %s (%s)".printf(AppAuthor, AppAuthorEmail) + "\n\n";
145 |
146 | msg += _("Usage") + ": groot [command] [basepath] [options]\n\n";
147 |
148 | msg += "%s:\n".printf(_("Commands"));
149 | msg += fmt.printf(" --chroot", _("Chroot to [basepath] and open shell session (default)"));
150 | msg += fmt.printf("-f, --fixboot", _("Chroot to [basepath] and fix boot issues"));
151 | msg += fmt.printf("", _("(Rebuilds initramfs and updates GRUB menu)"));
152 | msg += fmt.printf("-s, --sysinfo", _("Show host system information"));
153 | msg += fmt.printf("-i, --guestinfo", _("Show guest system information"));
154 | msg += fmt.printf("-d, --list-devices", _("List current devices"));
155 | msg += "\n";
156 |
157 | msg += "%s:\n".printf(_("Options"));
158 | msg += fmt.printf("-m, --fstab", _("Mount devices from fstab and cryptab"));
159 | msg += fmt.printf(" --no-display", _("Do not share display (default: enabled)"));
160 | msg += fmt.printf(" --no-internet", _("Do not share internet connection (default: enabled)"));
161 | msg += fmt.printf("-v, --verbose", _("Show commands and extra messages"));
162 | msg += fmt.printf(" --debug", _("Show debug messages"));
163 | msg += "\n";
164 |
165 | return msg;
166 | }
167 |
168 | public bool parse_arguments(string[] args) {
169 |
170 | string command = "chroot";
171 |
172 | // parse options and commands -------------------------------
173 |
174 | for (int k = 1; k < args.length; k++) {// Oth arg is app path
175 |
176 | switch (args[k].down()) {
177 |
178 | case "--chroot":
179 | command = "chroot";
180 | break;
181 |
182 | case "-m":
183 | case "--fstab":
184 | case "--chroot-fstab": // deprecated alias
185 | command = "chroot";
186 | mount_fstab = true;
187 | break;
188 |
189 | case "-f":
190 | case "--fixboot":
191 | command = "chroot";
192 | mount_fstab = true;
193 | fix_boot = true;
194 | break;
195 |
196 | case "-u":
197 | case "--update":
198 | case "--install-updates":
199 | command = "chroot";
200 | mount_fstab = true;
201 | install_updates = true;
202 | break;
203 |
204 | case "-d":
205 | case "--list-devices":
206 | command = "list-devices";
207 | break;
208 |
209 | case "-s":
210 | case "--sysinfo":
211 | case "--sys-info":
212 | case "--host-info":
213 | command = "sysinfo";
214 | break;
215 |
216 | case "-i":
217 | case "--guestinfo":
218 | case "--guest-info":
219 | command = "sysinfo-guest";
220 | break;
221 |
222 | case "--basepath":
223 | k += 1;
224 | basepath = args[k];
225 | break;
226 |
227 | case "--debug":
228 | LOG_DEBUG = true;
229 | break;
230 |
231 | case "-v":
232 | case "--verbose":
233 | verbose = true;
234 | break;
235 |
236 | case "--no-display":
237 | share_display = false;
238 | break;
239 |
240 | case "--no-internet":
241 | share_internet = false;
242 | break;
243 |
244 | case "-h":
245 | case "--help":
246 | log_msg(help_message());
247 | return true;
248 |
249 | default:
250 | if (args[k].has_prefix("/")){
251 | if (file_exists(args[k])){
252 | basepath = args[k];
253 | }
254 | else {
255 | log_error("%s: %s".printf(_("Path not found"), args[k]));
256 | return false;
257 | }
258 | }
259 | else {
260 | // unknown option. show help and exit
261 | log_error(_("Unknown option") + ": %s".printf(args[k]));
262 | log_error(_("Run 'groot --help' for available commands and options"));
263 | return false;
264 | }
265 | break;
266 | }
267 | }
268 |
269 | if (command.length == 0){
270 | // no command specified
271 | log_error(_("No command specified!"));
272 | log_error(_("Run 'groot --help' for available commands and options"));
273 | return false;
274 | }
275 |
276 | // process command ----------------------------------
277 |
278 | switch (command) {
279 |
280 | case "chroot":
281 | return chroot();
282 |
283 | case "sysinfo":
284 | return sysinfo();
285 |
286 | case "sysinfo-guest":
287 | return sysinfo_guest();
288 |
289 | case "list-devices":
290 | return list_devices();
291 | }
292 |
293 | return true;
294 | }
295 |
296 | // chroot -------------------------------------------------------
297 |
298 | private bool chroot(){
299 |
300 | check_dirs();
301 |
302 | check_admin_access();
303 |
304 | if (verbose || LOG_DEBUG){
305 | log_msg("\n%s=%s".printf(_("basepath"), basepath));
306 | }
307 |
308 | bool status = true, ok;
309 |
310 | if (mount_fstab){
311 | ok = mount_system_devices();
312 | if (!ok){ return false; }
313 | }
314 |
315 | prepare_for_chroot();
316 |
317 | if (fix_boot){
318 | fix_grub();
319 | }
320 | else if (install_updates){
321 | install_package_updates();
322 | }
323 | else {
324 | start_session();
325 | }
326 |
327 | // session has ended --------------------------------------
328 |
329 | cleanup_after_chroot();
330 |
331 | if (mount_fstab){
332 | unmount_system_devices();
333 | }
334 |
335 | return status;
336 | }
337 |
338 | private bool mount_system_devices(){
339 |
340 | string fstab = path_combine(basepath, "/etc/fstab");
341 |
342 | if (!file_exists(fstab)){
343 | log_error("%s: %s".printf(_("File Not Found"), fstab));
344 | log_error("%s".printf(_("Failed to mount system using fstab file")));
345 | log_error("%s".printf(_("Use 'groot --chroot' to change root normally")));
346 | return false;
347 | }
348 |
349 | var mgr = new MountEntryManager(false, basepath);
350 | mgr.read_mount_entries();
351 |
352 | var devices = Device.get_block_devices();
353 |
354 | basepath_bkup = basepath;
355 | basepath = "/tmp/%s".printf(timestamp_for_path());
356 | dir_create(basepath);
357 |
358 | if (verbose || LOG_DEBUG){
359 | log_msg("\n%s=%s".printf(_("basepath"), basepath));
360 | }
361 |
362 | if (verbose || LOG_DEBUG){
363 | log_msg("");
364 | log_msg(string.nfill(70,'-'));
365 | log_msg(_("Mounting devices from fstab and crypttab"));
366 | log_msg(string.nfill(70,'-'));
367 | }
368 |
369 | foreach(var entry in mgr.crypttab){
370 |
371 | var dev = Device.find_device_in_list(devices, entry.device);
372 |
373 | if (dev == null){
374 | if (!entry.options.contains("nofail")){
375 | log_error("%s: %s".printf(_("Could not find device referenced in crypttab file"), entry.device));
376 | return false;
377 | }
378 | else{
379 | continue;
380 | }
381 | }
382 |
383 | if (dev.is_encrypted_partition){
384 |
385 | if (!dev.is_unlocked){
386 |
387 | var cmd = "cryptsetup luksOpen '%s' '%s'".printf(dev.device, entry.name);
388 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd); }
389 | Posix.system(cmd);
390 |
391 | dev.query_changes();
392 | if (!dev.is_unlocked) { return false; }
393 | }
394 | else{
395 |
396 | if (dev.children[0].mapped_name != entry.name){
397 | // create device alias
398 | string cmd = "ln -s '%s' '/dev/mapper/%s'".printf(dev.children[0].device, entry.name);
399 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd); }
400 | Posix.system(cmd);
401 | }
402 | }
403 | }
404 | }
405 |
406 | devices = Device.get_block_devices();
407 |
408 | foreach(var entry in mgr.fstab){
409 |
410 | if (!entry.device.down().has_prefix("/") && !entry.device.down().has_prefix("uuid=")){ continue; }
411 |
412 | if (!entry.mount_point.has_prefix("/")){ continue; }
413 |
414 | var dev = Device.find_device_in_list(devices, entry.device);
415 |
416 | if (dev == null){
417 | if (!entry.options.contains("nofail")){
418 | log_error("%s: %s".printf(_("Could not find device referenced in fstab file"), entry.device));
419 | return false;
420 | }
421 | else{
422 | continue;
423 | }
424 | }
425 |
426 | var mpath = path_combine(basepath, entry.mount_point);
427 |
428 | if (!file_exists(mpath)){
429 | dir_create(mpath);
430 | }
431 |
432 | if (!file_exists(mpath)){
433 | log_error("%s: %s".printf(_("Path not found"), mpath));
434 | return false;
435 | }
436 |
437 | string cmd = "mount";
438 | cmd += " -t %s".printf(entry.fs_type);
439 | cmd += " -o %s".printf(entry.options);
440 | cmd += " %s".printf(dev.device);
441 | cmd += " '%s'".printf(escape_single_quote(mpath));
442 |
443 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
444 |
445 | Posix.system(cmd);
446 | }
447 |
448 | string cmd = "cd '%s'".printf(escape_single_quote(basepath));
449 | log_msg("\n$ " + cmd);
450 | Posix.system(cmd);
451 |
452 | return true;
453 | }
454 |
455 | private bool unmount_system_devices(){
456 |
457 | if (basepath.length == 0){ return false; }
458 |
459 | var mgr = new MountEntryManager(false, basepath);
460 | mgr.read_mount_entries();
461 |
462 | var devices = Device.get_block_devices();
463 |
464 | var list = mgr.fstab;
465 | list.sort((a,b)=>{ return strcmp(a.mount_point,b.mount_point) * -1; });
466 |
467 | if (verbose || LOG_DEBUG){
468 | log_msg("");
469 | log_msg(string.nfill(70,'-'));
470 | log_msg(_("Unmounting devices from fstab and crypttab"));
471 | log_msg(string.nfill(70,'-'));
472 | }
473 |
474 | // unmount in reverse order -----------------
475 |
476 | foreach(var entry in list){
477 |
478 | if (!entry.device.down().has_prefix("/") && !entry.device.down().has_prefix("uuid=")){ continue; }
479 |
480 | if (!entry.mount_point.has_prefix("/")){ continue; }
481 |
482 | var dev = Device.find_device_in_list(devices, entry.device);
483 |
484 | if (dev == null){
485 | if (!entry.options.contains("nofail")){
486 | log_error("%s: %s".printf(_("Could not find device referenced in fstab file"), entry.device));
487 | return false;
488 | }
489 | else{
490 | continue;
491 | }
492 | }
493 |
494 | var mpath = path_combine(basepath, entry.mount_point);
495 |
496 | string cmd = "umount --lazy --force";
497 | cmd += " '%s'".printf(escape_single_quote(mpath));
498 |
499 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
500 |
501 | Posix.system(cmd);
502 | }
503 |
504 | file_delete(basepath); // delete if empty
505 |
506 | basepath = basepath_bkup;
507 |
508 | string cmd = "cd '%s'".printf(escape_single_quote(basepath));
509 |
510 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd); }
511 |
512 | Posix.system(cmd);
513 |
514 | return false;
515 | }
516 |
517 | private bool prepare_for_chroot(){
518 |
519 | check_dirs();
520 |
521 | mount_dirs();
522 |
523 | resolv_conf_bkup = "";
524 | if (share_internet){
525 | resolv_conf_bkup = copy_resolv_conf();
526 | }
527 |
528 | if (share_display){
529 |
530 | if (verbose || LOG_DEBUG){
531 | log_msg("");
532 | log_msg(string.nfill(70,'-'));
533 | log_msg(_("Enable display sharing"));
534 | log_msg(string.nfill(70,'-'));
535 | }
536 |
537 | string cmd = "xhost +local:";
538 |
539 | if (!verbose && !LOG_DEBUG){
540 | cmd += " > /dev/null";
541 | }
542 |
543 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd); }
544 | Posix.system(cmd);
545 | }
546 |
547 | if (share_display){
548 | run_chroot_commands("export DISPLAY=$DISPLAY");
549 | }
550 |
551 | return true;
552 | }
553 |
554 | private bool cleanup_after_chroot(){
555 |
556 | Posix.system("sync");
557 |
558 | if (share_internet){
559 | restore_resolv_conf();
560 | }
561 |
562 | unmount_dirs();
563 |
564 | return true;
565 | }
566 |
567 | private void check_dirs(){
568 |
569 | foreach(string name in new string[]{ "dev", "proc", "run", "sys" }){
570 |
571 | string path = path_combine(basepath, name);
572 |
573 | if (!dir_exists(path)){
574 |
575 | log_error("%s: %s".printf(_("Directory not found"), path));
576 | log_error(_("Path for chroot must have system directories: /dev, /proc, /run, /sys"));
577 | exit(1);
578 | }
579 | }
580 | }
581 |
582 | private void mount_dirs(){
583 |
584 | if (verbose || LOG_DEBUG){
585 | log_msg("");
586 | log_msg(string.nfill(70,'-'));
587 | log_msg(_("Mounting system devices"));
588 | log_msg(string.nfill(70,'-'));
589 | }
590 |
591 | string cmd = "";
592 |
593 | cmd = "mount proc '%s/proc' -t proc -o nosuid,noexec,nodev".printf(escape_single_quote(basepath));
594 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
595 | Posix.system(cmd);
596 |
597 | cmd = "mount sys '%s/sys' -t sysfs -o nosuid,noexec,nodev,ro".printf(escape_single_quote(basepath));
598 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
599 | Posix.system(cmd);
600 |
601 | cmd = "mount udev '%s/dev' -t devtmpfs -o mode=0755,nosuid".printf(escape_single_quote(basepath));
602 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
603 | Posix.system(cmd);
604 |
605 | cmd = "mount devpts '%s/dev/pts' -t devpts -o mode=0620,gid=5,nosuid,noexec".printf(escape_single_quote(basepath));
606 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
607 | Posix.system(cmd);
608 |
609 | cmd = "mount shm '%s/dev/shm' -t tmpfs -o mode=1777,nosuid,nodev".printf(escape_single_quote(basepath));
610 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
611 | Posix.system(cmd);
612 |
613 | cmd = "mount run '%s/run' -t tmpfs -o nosuid,nodev,mode=0755".printf(escape_single_quote(basepath));
614 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
615 | Posix.system(cmd);
616 |
617 | cmd = "mount tmp '%s/tmp' -t tmpfs -o mode=1777,strictatime,nodev,nosuid".printf(escape_single_quote(basepath));
618 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
619 | Posix.system(cmd);
620 | }
621 |
622 | private void unmount_dirs(){
623 |
624 | if (verbose || LOG_DEBUG){
625 | log_msg("");
626 | log_msg(string.nfill(70,'-'));
627 | log_msg(_("Unmounting system devices"));
628 | log_msg(string.nfill(70,'-'));
629 | }
630 |
631 | string cmd = "";
632 |
633 | cmd = "umount --lazy --force --recursive '%s/dev'".printf(escape_single_quote(basepath));
634 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
635 | Posix.system(cmd);
636 |
637 | cmd = "umount --lazy --force --recursive '%s/run'".printf(escape_single_quote(basepath));
638 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
639 | Posix.system(cmd);
640 |
641 | cmd = "umount --lazy --force --recursive '%s/sys'".printf(escape_single_quote(basepath));
642 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
643 | Posix.system(cmd);
644 |
645 | cmd = "umount --lazy --force --recursive '%s/proc'".printf(escape_single_quote(basepath));
646 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
647 | Posix.system(cmd);
648 |
649 | cmd = "umount --lazy --force --recursive '%s/tmp'".printf(escape_single_quote(basepath));
650 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
651 | Posix.system(cmd);
652 | }
653 |
654 | private string copy_resolv_conf(){
655 |
656 | if (!share_internet){ return ""; }
657 |
658 | if (verbose || LOG_DEBUG){
659 | log_msg("");
660 | log_msg(string.nfill(70,'-'));
661 | log_msg(_("Copy resolv.conf"));
662 | log_msg(string.nfill(70,'-'));
663 | }
664 |
665 | string conf = "/etc/resolv.conf";
666 | string conf_chroot = path_combine(basepath, conf);
667 | string conf_chroot_bkup = path_combine(basepath, conf + ".groot-bkup");
668 |
669 | // fix for broken session ---------------------------------------
670 |
671 | if (file_exists(conf_chroot_bkup)){
672 |
673 | // restore the backup -------------------------
674 |
675 | if (file_exists(conf_chroot)){
676 |
677 | file_delete(conf_chroot);
678 |
679 | if (verbose || LOG_DEBUG){
680 |
681 | string msg = "[%s] '%s'".printf(
682 | _("removed"),
683 | escape_single_quote(conf_chroot.replace(basepath, "$basepath")));
684 |
685 | log_msg("\n" + msg);
686 | }
687 | }
688 |
689 | file_move(conf_chroot_bkup, conf_chroot, false);
690 |
691 | if (verbose || LOG_DEBUG){
692 |
693 | string msg = "[%s] '%s' > '%s'".printf(
694 | _("moved"),
695 | escape_single_quote(conf_chroot_bkup.replace(basepath, "$basepath")),
696 | escape_single_quote(conf_chroot.replace(basepath, "$basepath")));
697 |
698 | log_msg("\n" + msg);
699 | }
700 | }
701 |
702 | // copy resolv.conf -----------------------------------------
703 |
704 | if (file_exists(conf)){
705 |
706 | if (file_exists(conf_chroot)){
707 |
708 | file_move(conf_chroot, conf_chroot_bkup, false);
709 |
710 | if (verbose || LOG_DEBUG){
711 |
712 | string msg = "[%s] '%s' > '%s'".printf(
713 | _("moved"),
714 | escape_single_quote(conf_chroot.replace(basepath, "$basepath")),
715 | escape_single_quote(conf_chroot_bkup.replace(basepath, "$basepath")));
716 |
717 | log_msg("\n" + msg);
718 | }
719 | }
720 |
721 | file_copy(conf, conf_chroot, true);
722 |
723 | if (verbose || LOG_DEBUG){
724 |
725 | string msg = "[%s] '%s' > '%s'".printf(
726 | _("copied"),
727 | escape_single_quote(conf.replace(basepath, "$basepath")),
728 | escape_single_quote(conf_chroot.replace(basepath, "$basepath")));
729 |
730 | log_msg("\n" + msg);
731 | }
732 | }
733 |
734 | return conf_chroot_bkup;
735 | }
736 |
737 | private void restore_resolv_conf(){
738 |
739 | if (!share_internet){ return; }
740 |
741 | if (verbose || LOG_DEBUG){
742 | log_msg("");
743 | log_msg(string.nfill(70,'-'));
744 | log_msg(_("Restore resolv.conf"));
745 | log_msg(string.nfill(70,'-'));
746 | }
747 |
748 | string conf = "/etc/resolv.conf";
749 | string conf_chroot = path_combine(basepath, conf);
750 | string conf_chroot_bkup = resolv_conf_bkup;
751 |
752 | // restore resolv.conf ------------------------------------
753 |
754 | if (file_exists(conf_chroot_bkup)){
755 |
756 | if (file_exists(conf_chroot)){
757 |
758 | file_delete(conf_chroot);
759 |
760 | if (verbose || LOG_DEBUG){
761 |
762 | string msg = "[%s] '%s'".printf(
763 | _("removed"),
764 | escape_single_quote(conf_chroot.replace(basepath, "$basepath")));
765 |
766 | log_msg("\n" + msg);
767 | }
768 | }
769 |
770 | file_move(conf_chroot_bkup, conf_chroot, false);
771 |
772 | if (verbose || LOG_DEBUG){
773 |
774 | string msg = "[%s] '%s' > '%s'".printf(
775 | _("moved"),
776 | escape_single_quote(conf_chroot_bkup.replace(basepath, "$basepath")),
777 | escape_single_quote(conf_chroot.replace(basepath, "$basepath")));
778 |
779 | log_msg("\n" + msg);
780 | }
781 | }
782 | }
783 |
784 | private void start_session(){
785 |
786 | show_session_message();
787 |
788 | string cmd = "SHELL=/bin/bash unshare --fork --pid chroot '%s' /usr/bin/env -i HOME=/root USER=root /bin/bash -l".printf(escape_single_quote(basepath));
789 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
790 | Posix.system(cmd); // --pid
791 | }
792 |
793 | private bool fix_grub(){
794 |
795 | bool ok = write_fixboot_script();
796 |
797 | if (!ok){ return false; }
798 |
799 | string cmd = "SHELL=/bin/bash unshare --fork --pid chroot '%s' /usr/bin/env -i HOME=/root USER=root /bin/bash -c '/tmp/fixboot'".printf(escape_single_quote(basepath));
800 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
801 | Posix.system(cmd); // --pid
802 |
803 | return true;
804 | }
805 |
806 | private bool write_fixboot_script(){
807 |
808 | string sh_file = path_combine(basepath, "tmp/fixboot");
809 |
810 | file_delete(sh_file);
811 |
812 | string sh = "#!/bin/bash\n";
813 | string cmd = "";
814 |
815 | var dist = new LinuxDistro.from_path(basepath);
816 |
817 | log_msg(string.nfill(70,'-'));
818 |
819 | dist.print_system_info();
820 |
821 | sh += "echo '%s'\n".printf(string.nfill(70,'-'));
822 |
823 | // update initramfs -----------------------
824 |
825 | cmd = "";
826 |
827 | switch (dist.dist_type){
828 | case "debian":
829 |
830 | cmd = "update-initramfs -u -k all \n";
831 | break;
832 |
833 | case "fedora":
834 |
835 | cmd = "dracut -f -v \n";
836 | break;
837 |
838 | case "arch":
839 |
840 | cmd = "mkinitcpio -p /etc/mkinitcpio.d/*.preset \n";
841 | break;
842 |
843 | default:
844 | break;
845 | }
846 |
847 | sh += "echo '%s'\n".printf(escape_single_quote(cmd));
848 | sh += cmd;
849 | sh += "echo '%s'\n".printf(string.nfill(70,'-'));
850 |
851 | // update grub menu -------------------------------------
852 |
853 | cmd = "";
854 |
855 | switch (dist.dist_type){
856 | case "debian":
857 |
858 | cmd = "update-grub \n";
859 | break;
860 |
861 | case "fedora":
862 | case "arch":
863 |
864 | string cmd_name = "";
865 |
866 | if (cmd_exists_in_path(basepath, "grub-mkconfig")){
867 | cmd_name = "grub-mkconfig";
868 | }
869 | else if (cmd_exists_in_path(basepath, "grub2-mkconfig")){
870 | cmd_name = "grub2-mkconfig";
871 | }
872 |
873 | string grub_conf_name = "/boot/grub/grub.cfg";
874 | string grub_conf_path = path_combine(basepath, grub_conf_name);
875 |
876 | if (!file_exists(grub_conf_path)){
877 | grub_conf_name = "/boot/grub2/grub.cfg";
878 | grub_conf_path = path_combine(basepath, grub_conf_name);
879 | }
880 |
881 | if (!file_exists(grub_conf_path)){
882 | log_error(_("Failed to find GRUB config file. GRUB menu will not be updated."));
883 | }
884 |
885 | if ((cmd_name.length > 0) && file_exists(grub_conf_path)){
886 | cmd = "%s -o %s \n".printf(cmd_name, grub_conf_name);
887 | }
888 |
889 | break;
890 |
891 | default:
892 | break;
893 | }
894 |
895 | sh += "echo '%s'\n".printf(escape_single_quote(cmd));
896 | sh += cmd;
897 | //sh += "echo '%s'\n".printf(string.nfill(70,'-'));
898 |
899 | file_write(sh_file, sh);
900 |
901 | chmod(sh_file, "u+x");
902 |
903 | return file_exists(sh_file);
904 | }
905 |
906 | private bool install_package_updates(){
907 |
908 | bool ok = write_update_script();
909 |
910 | if (!ok){ return false; }
911 |
912 | string cmd = "SHELL=/bin/bash unshare --fork --pid chroot '%s' /usr/bin/env -i HOME=/root USER=root /bin/bash -c '/tmp/install-updates'".printf(escape_single_quote(basepath));
913 | if (verbose || LOG_DEBUG){ log_msg("\n$ " + cmd.replace(basepath, "$basepath")); }
914 | Posix.system(cmd); // --pid
915 |
916 | return true;
917 | }
918 |
919 | private bool write_update_script(){
920 |
921 | string sh_file = path_combine(basepath, "tmp/install-updates");
922 |
923 | file_delete(sh_file);
924 |
925 | string sh = "#!/bin/bash\n";
926 | string cmd = "";
927 |
928 | var dist = new LinuxDistro.from_path(basepath);
929 |
930 | log_msg(string.nfill(70,'-'));
931 |
932 | dist.print_system_info();
933 |
934 | sh += "echo '%s'\n".printf(string.nfill(70,'-'));
935 |
936 | cmd = "";
937 |
938 | switch (dist.dist_type){
939 | case "debian":
940 |
941 | cmd = "%s update \n".printf(dist.package_manager);
942 | cmd += "%s upgrade \n".printf(dist.package_manager);
943 | break;
944 |
945 | case "fedora":
946 |
947 | cmd = "%s check-update \n".printf(dist.package_manager);
948 | cmd += "%s upgrade \n".printf(dist.package_manager);
949 | break;
950 |
951 | case "arch":
952 |
953 | cmd = "%s -Syyu \n".printf(dist.package_manager);
954 | break;
955 |
956 | default:
957 | break;
958 | }
959 |
960 | sh += "echo '%s'\n".printf(escape_single_quote(cmd));
961 | sh += cmd;
962 | //sh += "echo '%s'\n".printf(string.nfill(70,'-'));
963 |
964 | file_write(sh_file, sh);
965 |
966 | chmod(sh_file, "u+x");
967 |
968 | return file_exists(sh_file);
969 | }
970 |
971 | private void show_session_message(){
972 |
973 | log_msg("");
974 | log_msg(string.nfill(70,'='));
975 | log_msg(_("Entering chroot environment..."));
976 | log_msg(string.nfill(70,'='));
977 |
978 | if (share_internet){
979 | log_msg(_("Internet sharing is Enabled (you can connect to internet)"));
980 | }
981 | else{
982 | log_msg(_("Internet sharing is Disabled"));
983 | }
984 |
985 | if (share_display){
986 | log_msg(_("Display sharing is Enabled (you can run GUI apps)"));
987 | }
988 | else{
989 | log_msg(_("Display sharing is Disabled"));
990 | }
991 |
992 | log_msg(string.nfill(70,'-'));
993 | log_msg(_("Type 'exit' to quit the session cleanly"));
994 | log_msg(string.nfill(70,'-'));
995 | //log_msg("");
996 | }
997 |
998 | private void run_chroot_commands(string commands){
999 |
1000 | Posix.system("SHELL=/bin/bash unshare --fork --pid chroot '%s' /bin/bash -c \"%s\"".printf(
1001 | escape_single_quote(basepath), commands));
1002 | }
1003 |
1004 | // list devices ------------------------------
1005 |
1006 | private bool list_devices(){
1007 |
1008 | bool status = true;
1009 |
1010 | //Posix.system("lsblk --fs");
1011 |
1012 | //var devices = Device.get_block_devices();
1013 | Device.print_device_list();
1014 |
1015 | return status;
1016 | }
1017 |
1018 | private bool sysinfo(){
1019 |
1020 | bool status = true;
1021 |
1022 | distro.print_system_info();
1023 |
1024 | return status;
1025 | }
1026 |
1027 | private bool sysinfo_guest(){
1028 |
1029 | bool status = true;
1030 |
1031 | var dist = new LinuxDistro.from_path(basepath);
1032 | dist.print_system_info();
1033 |
1034 | return status;
1035 | }
1036 | }
1037 |
--------------------------------------------------------------------------------
/src/Console/LinuxDistro.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * LinuxDistro.vala
4 | *
5 | * Copyright 2012-17 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | using TeeJee.Logging;
26 | using TeeJee.FileSystem;
27 | using TeeJee.ProcessHelper;
28 |
29 | public class LinuxDistro : GLib.Object{
30 |
31 | /* Class for getting information about Linux distribution */
32 |
33 | public string dist_id = ""; // Ubuntu
34 | public string dist_type = ""; // debian, fedora, arch
35 |
36 | public string description = ""; // Ubuntu 16.04
37 | public string release = ""; // 16.04
38 | public string codename = ""; // xenial
39 | public string dist_full_name = ""; // Ubuntu 16.04 (xenial)
40 |
41 | public string package_manager = ""; // dnf, yum, apt, pacman
42 | public string package_arch = ""; // x86_64, amd64, i386, i686, ...
43 | public string kernel_arch = ""; // x86_64, i386, i686, ...
44 | public int machine_arch = 0; // 32, 64, ...
45 |
46 | public string basepath = ""; // system root or mount path
47 |
48 | // ---------------------------------------
49 |
50 | public LinuxDistro(){
51 |
52 | basepath = "/";
53 |
54 | read_dist_release_file();
55 |
56 | check_dist_type();
57 |
58 | check_package_manager();
59 |
60 | check_package_arch();
61 |
62 | check_system();
63 | }
64 |
65 | public LinuxDistro.from_path(string root_path){
66 |
67 | basepath = root_path;
68 |
69 | read_dist_release_file();
70 |
71 | check_dist_type();
72 |
73 | check_package_manager();
74 |
75 | //check_package_arch(); // NOT_IMPLEMENTED
76 |
77 | //check_system(); // NOT_IMPLEMENTED
78 | }
79 |
80 | private void read_dist_release_file(){
81 |
82 | /* Returns info about Linux distribution installed at root path */
83 |
84 | string dist_file = path_combine(basepath, "/etc/lsb-release");
85 |
86 | var f = File.new_for_path(dist_file);
87 |
88 | if (f.query_exists()){
89 |
90 | /*
91 | DISTRIB_ID=Ubuntu
92 | DISTRIB_RELEASE=13.04
93 | DISTRIB_CODENAME=raring
94 | DISTRIB_DESCRIPTION="Ubuntu 13.04"
95 | */
96 |
97 | foreach(string line in file_read(dist_file).split("\n")){
98 |
99 | if (line.split("=").length != 2){ continue; }
100 |
101 | string key = line.split("=")[0].strip();
102 | string val = line.split("=")[1].strip();
103 |
104 | if (val.has_prefix("\"")){
105 | val = val[1:val.length];
106 | }
107 |
108 | if (val.has_suffix("\"")){
109 | val = val[0:val.length-1];
110 | }
111 |
112 | switch (key){
113 | case "DISTRIB_ID":
114 | dist_id = val;
115 | break;
116 | case "DISTRIB_RELEASE":
117 | release = val;
118 | break;
119 | case "DISTRIB_CODENAME":
120 | codename = val;
121 | break;
122 | case "DISTRIB_DESCRIPTION":
123 | description = val;
124 | break;
125 | }
126 | }
127 | }
128 | else{
129 |
130 | dist_file = path_combine(basepath, "/etc/os-release");
131 |
132 | f = File.new_for_path(dist_file);
133 |
134 | if (f.query_exists()){
135 |
136 | /*
137 | NAME="Ubuntu"
138 | VERSION="13.04, Raring Ringtail"
139 | ID=ubuntu
140 | ID_LIKE=debian
141 | PRETTY_NAME="Ubuntu 13.04"
142 | VERSION_ID="13.04"
143 | HOME_URL="http://www.ubuntu.com/"
144 | SUPPORT_URL="http://help.ubuntu.com/"
145 | BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
146 | */
147 |
148 | foreach(string line in file_read(dist_file).split("\n")){
149 |
150 | if (line.split("=").length != 2){ continue; }
151 |
152 | string key = line.split("=")[0].strip();
153 | string val = line.split("=")[1].strip();
154 |
155 | switch (key){
156 | case "ID":
157 | dist_id = val;
158 | break;
159 | case "VERSION_ID":
160 | release = val;
161 | break;
162 | //case "DISTRIB_CODENAME":
163 | //info.codename = val;
164 | //break;
165 | case "PRETTY_NAME":
166 | description = val;
167 | break;
168 | }
169 | }
170 | }
171 | }
172 |
173 | if (dist_id.length > 0){
174 | string val = "";
175 | val += dist_id;
176 | val += (release.length > 0) ? " " + release : "";
177 | val += (codename.length > 0) ? " (" + codename + ")" : "";
178 | dist_full_name = val;
179 | }
180 | }
181 |
182 | private void check_dist_type(){
183 |
184 | if (dist_id == "manjaro"){
185 | dist_type = "arch";
186 | }
187 | else if ((dist_id == "debian")||(dist_id == "ubuntu")){
188 | dist_type = "debian";
189 | }
190 | else if ((dist_id == "fedora")){
191 | dist_type = "fedora";
192 | }
193 | }
194 |
195 | private void check_package_manager(){
196 |
197 | if (cmd_exists_in_basepath("dpkg")){
198 |
199 | if (dist_type.length == 0){
200 | dist_type = "debian";
201 | }
202 |
203 | if (cmd_exists_in_basepath("aptitude")){
204 | package_manager = "aptitude";
205 | }
206 | else if (cmd_exists_in_basepath("apt")){
207 | package_manager = "apt";
208 | }
209 | else if (cmd_exists_in_basepath("apt-fast")){
210 | package_manager = "apt-fast";
211 | }
212 | else {
213 | package_manager = "apt-get";
214 | }
215 | }
216 | else if (cmd_exists_in_basepath("dnf")){
217 |
218 | if (dist_type.length == 0){
219 | dist_type = "fedora";
220 | }
221 |
222 | package_manager = "dnf";
223 | }
224 | else if (cmd_exists_in_basepath("yum")){
225 |
226 | if (dist_type.length == 0){
227 | dist_type = "fedora";
228 | }
229 |
230 | package_manager = "yum";
231 | }
232 | else if (cmd_exists_in_basepath("pacman")){
233 |
234 | if (dist_type.length == 0){
235 | dist_type = "arch";
236 | }
237 |
238 | package_manager = "pacman";
239 | }
240 | else{
241 | log_error(Messages.UNKNOWN_DISTRO);
242 | dist_type = "";
243 | package_manager = "";
244 | }
245 | }
246 |
247 | private bool cmd_exists_in_basepath(string cmd){
248 |
249 | return cmd_exists_in_path(basepath, cmd);
250 | }
251 |
252 | public string dist_type_name {
253 | owned get {
254 | switch(dist_type){
255 | case "debian":
256 | return "Debian / Ubuntu";
257 | case "fedora":
258 | return "Fedora / RedHat / Cent OS";
259 | case "arch":
260 | return "Arch";
261 | default:
262 | return "";
263 | }
264 | }
265 | }
266 |
267 | private void check_package_arch(){
268 |
269 | string cmd = "";
270 |
271 | switch(dist_type){
272 | case "debian":
273 | cmd = "dpkg --print-architecture"; // i386, amd64, ...
274 | break;
275 |
276 | case "fedora":
277 | cmd = "uname -m";
278 | break;
279 |
280 | case "arch":
281 | cmd = "uname -m"; // x86_64, i386, i686, ...
282 | break;
283 | }
284 |
285 | if (cmd.length == 0){ return; }
286 |
287 | string std_out, std_err;
288 | exec_sync(cmd, out std_out, out std_err);
289 | package_arch = std_out.strip();;
290 | }
291 |
292 | private void check_system(){
293 |
294 | string std_out, std_err;
295 | int status = exec_sync("uname -m", out std_out, out std_err);
296 | kernel_arch = std_out.strip();
297 |
298 | status = exec_sync("getconf LONG_BIT", out std_out, out std_err);
299 | machine_arch = int.parse(std_out);
300 | }
301 |
302 | // public -----------------------------
303 |
304 | public void print_system_info(){
305 |
306 | //log_msg(string.nfill(70,'-'));
307 |
308 | if (dist_full_name.length > 0){
309 | log_msg("Distribution: %s".printf(dist_full_name));
310 | }
311 |
312 | log_msg("Dist Type: %s".printf((dist_type_name.length > 0) ? dist_type_name : "???"));
313 | log_msg("Package Manager: %s".printf((package_manager.length > 0) ? package_manager : "???"));
314 |
315 | if (basepath == "/"){
316 | log_msg("Arch-Pkgs: %s".printf((package_arch.length > 0) ? package_arch : "???"));
317 | log_msg("Arch-Kern: %s".printf((kernel_arch.length > 0) ? kernel_arch : "???"));
318 | log_msg("Arch-Type: %s".printf((machine_arch > 0) ? machine_arch.to_string() + "-bit" : "???"));
319 | }
320 | //log_msg(string.nfill(70,'-'));
321 | }
322 | }
323 |
324 |
325 |
--------------------------------------------------------------------------------
/src/Console/MountEntryManager.vala:
--------------------------------------------------------------------------------
1 | /*
2 | * MountEntryManager.vala
3 | *
4 | * Copyright 2017 Tony George
5 | *
6 | * This program is free software; you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation; either version 2 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program; if not, write to the Free Software
18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 | * MA 02110-1301, USA.
20 | *
21 | *
22 | */
23 |
24 | using TeeJee.Logging;
25 | using TeeJee.FileSystem;
26 | using TeeJee.ProcessHelper;
27 | using TeeJee.Misc;
28 |
29 | public class MountEntryManager : GLib.Object {
30 |
31 | public string basepath = "/";
32 |
33 | public Gee.ArrayList fstab;
34 | public Gee.ArrayList crypttab;
35 |
36 | public bool dry_run = false;
37 |
38 | public MountEntryManager(bool _dry_run = false, string filesystem_root_path = "/"){
39 |
40 | dry_run = _dry_run;
41 |
42 | basepath = filesystem_root_path;
43 |
44 | fstab = new Gee.ArrayList();
45 | crypttab = new Gee.ArrayList();
46 | }
47 |
48 | // read -----------------------------
49 |
50 | public void read_mount_entries(){
51 |
52 | read_fstab_file();
53 |
54 | read_crypttab_file();
55 |
56 | update_device_uuids();
57 | }
58 |
59 | public bool read_fstab_file(){
60 |
61 | string tab_file = "/etc/fstab";
62 |
63 | if (basepath.length > 1){
64 | tab_file = path_combine(basepath, tab_file);
65 | }
66 |
67 | if (!file_exists(tab_file)){
68 | log_error("%s: %s".printf(Messages.FILE_MISSING, tab_file));
69 | return false;
70 | }
71 |
72 | string txt = file_read(tab_file);
73 |
74 | foreach(string line in txt.split("\n")){
75 |
76 | parse_fstab_line(line);
77 | }
78 |
79 | return true;
80 | }
81 |
82 | public bool read_crypttab_file(){
83 |
84 | string tab_file = "/etc/crypttab";
85 |
86 | if (basepath.length > 1){
87 | tab_file = path_combine(basepath, tab_file);
88 | }
89 |
90 | if (!file_exists(tab_file)){
91 | log_error("%s: %s".printf(Messages.FILE_MISSING, tab_file));
92 | return false;
93 | }
94 |
95 | string txt = file_read(tab_file);
96 |
97 | foreach(string line in txt.split("\n")){
98 |
99 | parse_crypttab_line(line);
100 | }
101 |
102 | return true;
103 | }
104 |
105 | private void parse_fstab_line(string line){
106 |
107 | if ((line == null) || (line.length == 0)){ return; }
108 |
109 | if (line.strip().has_prefix("#")){ return; }
110 |
111 | FsTabEntry entry = null;
112 |
113 | //
114 |
115 | var match = regex_match("""([^ \t]*)[ \t]*([^ \t]*)[ \t]*([^ \t]*)[ \t]*([^ \t]*)[ \t]*([^ \t]*)[ \t]*([^ \t]*)""", line);
116 |
117 | if (match != null){
118 |
119 | entry = new FsTabEntry();
120 |
121 | entry.device = match.fetch(1);
122 | entry.mount_point = match.fetch(2);
123 | entry.fs_type = match.fetch(3);
124 | entry.options = match.fetch(4);
125 | entry.dump = match.fetch(5);
126 | entry.pass = match.fetch(6);
127 |
128 | fstab.add(entry);
129 | }
130 | }
131 |
132 | private void parse_crypttab_line(string line){
133 |
134 | if ((line == null) || (line.length == 0)){ return; }
135 |
136 | if (line.strip().has_prefix("#")){ return; }
137 |
138 | CryptTabEntry entry = null;
139 |
140 | //
141 |
142 | var match = regex_match("""([^ \t]*)[ \t]*([^ \t]*)[ \t]*([^ \t]*)[ \t]*([^ \t]*)""", line);
143 |
144 | if (match != null){
145 |
146 | entry = new CryptTabEntry();
147 |
148 | entry.name = match.fetch(1);
149 | entry.device = match.fetch(2);
150 | entry.password = match.fetch(3);
151 | entry.options = match.fetch(4);
152 |
153 | crypttab.add(entry);
154 | }
155 | }
156 |
157 | private void update_device_uuids(){
158 |
159 | var devices = Device.get_block_devices();
160 |
161 | foreach(var entry in fstab){
162 |
163 | if (!entry.device.up().contains("UUID=") && !entry.device.down().has_prefix("/dev/disk/")){
164 |
165 | var dev = Device.find_device_in_list(devices, entry.device);
166 | if ((dev != null) && (dev.uuid.length > 0)){
167 | entry.device = "UUID=%s".printf(dev.uuid);
168 | }
169 | }
170 | }
171 |
172 | foreach(var entry in crypttab){
173 |
174 | if (!entry.device.up().contains("UUID=") && !entry.device.down().has_prefix("/dev/disk/")){
175 |
176 | var dev = Device.find_device_in_list(devices, entry.device);
177 | if ((dev != null) && (dev.uuid.length > 0)){
178 | entry.device = "UUID=%s".printf(dev.uuid);
179 | }
180 | }
181 | }
182 | }
183 |
184 | // write ---------------------------
185 |
186 | public bool save_fstab_file(Gee.ArrayList list){
187 |
188 | string txt = "# \n\n";
189 |
190 | bool found_root = false;
191 |
192 | list.sort((a,b)=>{ return strcmp(a.mount_point, b.mount_point); }); // sorting required
193 |
194 | foreach(var entry in list){
195 |
196 | txt += "%s\n".printf(entry.get_line());
197 |
198 | if (entry.mount_point == "/"){
199 | found_root = true;
200 | }
201 | }
202 |
203 | if (found_root){
204 |
205 | var t = Time.local (time_t ());
206 |
207 | string file_path = "/etc/fstab";
208 |
209 | if (basepath.length > 1){
210 | file_path = path_combine(basepath, file_path);
211 | }
212 |
213 | string cmd = "mv -vf %s %s.bkup.%s".printf(file_path, file_path, t.format("%Y-%d-%m_%H-%M-%S"));
214 | Posix.system(cmd);
215 |
216 | bool ok = file_write(file_path, txt);
217 |
218 | if (ok){ log_msg("%s: %s".printf(_("Saved"), file_path)); }
219 |
220 | return ok;
221 | }
222 | else{
223 | log_error(_("Critical: New fstab does not have entry for root mount point (!). Existing file will not be changed."));
224 | }
225 |
226 | return false;
227 | }
228 |
229 | public bool save_crypttab_file(Gee.ArrayList list){
230 |
231 | string txt = "# \n\n";
232 |
233 | //list.sort((a,b)=>{ return strcmp(a.name, b.name); }); // sorting not required and may cause side-effects
234 |
235 | foreach(var entry in list){
236 |
237 | txt += "%s\n".printf(entry.get_line());
238 | }
239 |
240 | var t = Time.local (time_t ());
241 |
242 | string file_path = "/etc/crypttab";
243 |
244 | if (basepath.length > 1){
245 | file_path = path_combine(basepath, file_path);
246 | }
247 |
248 | string cmd = "mv -vf %s %s.bkup.%s".printf(file_path, file_path, t.format("%Y-%d-%m_%H-%M-%S"));
249 | Posix.system(cmd);
250 |
251 | bool ok = file_write(file_path, txt);
252 |
253 | if (ok){ log_msg("%s: %s".printf(_("Saved"), file_path)); }
254 |
255 | return ok;
256 | }
257 |
258 | // helpers -------------------------
259 |
260 | public bool root_on_btrfs_subvolume(){
261 |
262 | foreach(var entry in fstab){
263 |
264 | if ((entry.mount_point == "/") && (entry.fs_type == "btrfs") && entry.options.contains("subvol=")){
265 |
266 | return true;
267 | }
268 | }
269 |
270 | return false;
271 | }
272 |
273 | public FsTabEntry? get_entry_by_path(string mount_path){
274 |
275 | foreach(var entry in fstab){
276 |
277 | if (entry.mount_point == mount_path){
278 |
279 | return entry;
280 | }
281 | }
282 |
283 | return null;
284 | }
285 |
286 | }
287 |
--------------------------------------------------------------------------------
/src/Messages.vala:
--------------------------------------------------------------------------------
1 |
2 | public class Messages : GLib.Object {
3 | public const string APT_GET_ERROR = _("Package installation has failed or was aborted by user");
4 |
5 | public const string INTERNET_OFFLINE = _("Internet connection is not active. Check the connection and try again.");
6 |
7 | public const string BACKUP_OK = _("Backup completed");
8 | public const string BACKUP_ERROR = _("Backup completed with errors");
9 | public const string BACKUP_SAVED = _("Backup saved");
10 | public const string BACKUP_SAVE_ERROR = _("Failed to save backup");
11 |
12 | public const string UNKNOWN_DISTRO = _("Unknown Linux Distribution & Package Manager");
13 | public const string UNKNOWN_CODENAME = _("CODENAME is unknown for this Linux distribution");
14 |
15 | public const string MISSING_PACKAGE_MANAGER = _("Package Manager Not Found");
16 |
17 | public const string MISSING_COMMAND = _("Missing command");
18 |
19 | public const string CACHE_NOT_SUPPORTED = _("Cache backup & restore not supported for package manager");
20 |
21 | public const string RESTORE_OK = _("Restore completed");
22 | public const string RESTORE_ERROR = _("Restore completed with errors");
23 |
24 | public const string FILE_EXISTS = _("File exists");
25 | public const string FILE_MISSING = _("File not found");
26 |
27 | public const string FILE_SAVE_OK = _("File saved");
28 | public const string FILE_SAVE_ERROR = _("Failed to save file");
29 |
30 | public const string FILE_READ_OK = _("File read");
31 | public const string FILE_READ_ERROR = _("Failed to read file");
32 |
33 | public const string FILE_DECRYPT_OK = _("File decrypted");
34 | public const string FILE_DECRYPT_ERROR = _("Failed to decrypt file");
35 |
36 | public const string FILE_DELETE_OK = _("File deleted");
37 | public const string FILE_DELETE_ERROR = _("Failed to delete file");
38 |
39 | public const string DIR_CREATE_OK = _("Directory created");
40 | public const string DIR_CREATE_ERROR = _("Failed to create directory");
41 |
42 | public const string DIR_EXISTS = _("Directory exists");
43 | public const string DIR_MISSING = _("Directory missing");
44 |
45 | public const string USER_ADD_OK = _("User added");
46 | public const string USER_ADD_ERROR = _("Failed to add user");
47 |
48 | public const string GROUP_ADD_OK = _("Group added");
49 | public const string GROUP_ADD_ERROR = _("Failed to add group");
50 |
51 | public const string GROUP_ADD_USER_OK = _("User added to group");
52 | public const string GROUP_ADD_USER_ERROR = _("Failed to add user to group");
53 |
54 | public const string NO_CHANGES_REQUIRED = _("No changes required");
55 |
56 | public const string PASSWORD_MISSING = _("Password not specified!");
57 | public const string ENTER_PASSWORD_BACKUP = _("Enter password for encrypting backup");
58 | public const string ENTER_PASSWORD_RESTORE = _("Enter password for decrypting backup");
59 | public const string PASSWORD_EMPTY = _("Password cannot be empty!");
60 | public const string PASSWORD_NOT_MATCHING = _("Passwords do not match!");
61 |
62 | public const string TASK_REPOS = _("Software Repositories");
63 | public const string TASK_CACHE = _("Downloaded Packages");
64 | public const string TASK_PACKAGES = _("Installed Software");
65 | public const string TASK_HOME = _("Home Directory Data");
66 | public const string TASK_MOUNTS = _("Mount Entries");
67 | public const string TASK_ICONS = _("Icons");
68 | public const string TASK_THEMES = _("Themes");
69 | public const string TASK_FONTS = _("Fonts");
70 | public const string TASK_USERS = _("User Accounts");
71 | public const string TASK_GROUPS = _("User Groups");
72 | public const string TASK_DCONF = _("Dconf Settings");
73 | public const string TASK_CRON = _("Scheduled Tasks");
74 | }
75 |
76 |
--------------------------------------------------------------------------------
/src/README:
--------------------------------------------------------------------------------
1 |
2 | /Console/ -- Command-line version of this App; Does not contain GUI code (no references to Gtk, Gdk, etc)
3 | /Gtk/ -- Gtk version of this App; Contains GUI code (references to Gtk, Gdk, etc); Calls the commandline version to get work done;
4 |
5 | /Utility/ -- Helper classes
6 | /Utility/Console/ -- Helper classes; Does not contain GUI code (no references to Gtk, Gdk, etc)
7 | /Utility/Gtk/ -- Helper classes; Contains GUI code (references to Gtk, Gdk, etc)
8 |
--------------------------------------------------------------------------------
/src/Utility/Console/Device.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Device.vala
4 | *
5 | * Copyright 2012-18 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | /* Functions and classes for handling disk partitions */
26 |
27 | using TeeJee.Logging;
28 | using TeeJee.FileSystem;
29 | using TeeJee.ProcessHelper;
30 | using TeeJee.Misc;
31 |
32 | public class Device : GLib.Object, Gee.Comparable{
33 |
34 | /* Class for storing disk information */
35 |
36 | public static double KB = 1000;
37 | public static double MB = 1000 * KB;
38 | public static double GB = 1000 * MB;
39 |
40 | public static double KiB = 1024;
41 | public static double MiB = 1024 * KiB;
42 | public static double GiB = 1024 * MiB;
43 |
44 | public string device = "";
45 | public string name = "";
46 | public string kname = "";
47 | public string pkname = "";
48 | public string pkname_toplevel = "";
49 | public string mapped_name = "";
50 | public string uuid = "";
51 | public string label = "";
52 | public string partuuid = "";
53 | public string partlabel = "";
54 |
55 | public int major = -1;
56 | public int minor = -1;
57 |
58 | public string device_mapper = "";
59 | public string device_by_uuid = "";
60 | public string device_by_label = "";
61 | public string device_by_partuuid = ""; // gpt only
62 | public string device_by_partlabel = ""; // gpt only
63 |
64 | public string type = ""; // disk, part, crypt, loop, rom, lvm
65 | public string fstype = ""; // iso9660, ext4, btrfs, ...
66 |
67 | public int order = -1;
68 |
69 | public string vendor = "";
70 | public string model = "";
71 | public string serial = "";
72 | public string revision = "";
73 |
74 | public bool removable = false;
75 | public bool read_only = false;
76 |
77 | public int64 size_bytes = 0;
78 | public int64 used_bytes = 0;
79 | public int64 available_bytes = 0;
80 |
81 | //public string used_percent = "";
82 | public string dist_info = "";
83 | public Gee.ArrayList mount_points = new Gee.ArrayList();
84 | public Gee.ArrayList symlinks = new Gee.ArrayList();
85 |
86 | public Device? parent = null;
87 | public Gee.ArrayList children = new Gee.ArrayList();
88 |
89 | private static string lsblk_version = "";
90 | private static bool lsblk_is_ancient = false;
91 |
92 | private static Gee.ArrayList device_list;
93 |
94 | // static -----------------------------
95 |
96 | public static void init(){
97 |
98 | get_block_devices();
99 | }
100 |
101 | public static void test_lsblk_version(){
102 |
103 | if ((lsblk_version != null) && (lsblk_version.length > 0)){
104 | return;
105 | }
106 |
107 | string std_out, std_err;
108 | int status = exec_sync("lsblk --bytes --pairs --output HOTPLUG,PKNAME,VENDOR,SERIAL,REV", out std_out, out std_err);
109 | if (status == 0){
110 | lsblk_version = std_out;
111 | lsblk_is_ancient = false;
112 | }
113 | else{
114 | lsblk_version = "ancient";
115 | lsblk_is_ancient = true;
116 | }
117 | }
118 |
119 | public static Gee.ArrayList get_devices(){
120 | if (device_list == null){
121 | get_block_devices();
122 | }
123 |
124 | return device_list;
125 | }
126 |
127 | public int compare_to(Device b){
128 |
129 | var a = this;
130 |
131 | // list loop devices after other types ----------------------
132 |
133 | if (a.kname.has_prefix("loop") && !b.kname.has_prefix("loop")){
134 | return 1;
135 | }
136 | else if (!a.kname.has_prefix("loop") && b.kname.has_prefix("loop")){
137 | return -1;
138 | }
139 | else {
140 |
141 | // list internal disks before removable disks ----------
142 |
143 | if (a.removable && !b.removable){
144 | return 1;
145 | }
146 | else if (!a.removable && b.removable){
147 | return -1;
148 | }
149 | else {
150 |
151 | // use numeric sorting for numbered partitions --------------
152 |
153 | var match_a = regex_match("""^(.*)([0-9]+)$""", a.kname);
154 |
155 | var match_b = regex_match("""^(.*)([0-9]+)$""", b.kname);
156 |
157 | if ((match_a != null) && (match_b != null)){
158 |
159 | if (match_a.fetch(1) == match_b.fetch(1)){
160 |
161 | return int.parse(match_a.fetch(2)) - int.parse(match_b.fetch(2));
162 | }
163 | else{
164 | return strcmp(a.kname, b.kname);
165 | }
166 | }
167 | else{
168 | return strcmp(a.kname, b.kname);
169 | }
170 | }
171 | }
172 | }
173 |
174 | // instance ------------------
175 |
176 | public Device(){
177 |
178 | mount_points = new Gee.ArrayList();
179 | symlinks = new Gee.ArrayList();
180 | children = new Gee.ArrayList();
181 |
182 | test_lsblk_version();
183 | }
184 |
185 | public int64 free_bytes{
186 | get{
187 | return (used_bytes == 0) ? 0 : (size_bytes - used_bytes);
188 | }
189 | }
190 |
191 | public string size_formatted{
192 | owned get{
193 | return (size_bytes == 0) ? "" : format_file_size(size_bytes);
194 | }
195 | }
196 |
197 | public string used_formatted{
198 | owned get{
199 | return (used_bytes == 0) ? "" : format_file_size(used_bytes);
200 | }
201 | }
202 |
203 | public string free_formatted{
204 | owned get{
205 | return (free_bytes == 0) ? "" : format_file_size(free_bytes);
206 | }
207 | }
208 |
209 | public string mount_path{
210 | owned get{
211 | string mpath = "";
212 | foreach(var mp in mount_points){
213 | if ((mp.subvolume_name() == "/") || (mp.subvolume_name() == "")){
214 | mpath = mp.mount_point;
215 | break;
216 | }
217 | else{
218 | mpath = mp.mount_point;
219 | }
220 | }
221 | return mpath;
222 | }
223 | }
224 |
225 | public bool is_mounted {
226 | get {
227 | return (mount_points.size > 0);
228 | }
229 | }
230 |
231 | public bool is_mounted_at_path(string subvolname, string mount_path){
232 |
233 | foreach (var mnt in mount_points){
234 | if (mnt.mount_point == mount_path){
235 | if (subvolname.length == 0){
236 | return true;
237 | }
238 | else if (mnt.mount_options.contains("subvol=%s".printf(subvolname))
239 | || mnt.mount_options.contains("subvol=/%s".printf(subvolname))){
240 |
241 | return true;
242 | }
243 | }
244 | }
245 |
246 | return false;
247 | }
248 |
249 | public bool has_linux_filesystem(){
250 | switch (fstype){
251 | case "ext2":
252 | case "ext3":
253 | case "ext4":
254 | case "reiserfs":
255 | case "reiser4":
256 | case "xfs":
257 | case "jfs":
258 | case "btrfs":
259 | case "lvm":
260 | case "lvm2":
261 | case "lvm2_member":
262 | case "luks":
263 | case "crypt":
264 | case "crypto_luks":
265 | return true;
266 | default:
267 | return false;
268 | }
269 | }
270 |
271 | public bool is_encrypted_partition {
272 | get {
273 | return fstype.down().contains("luks");
274 | }
275 | }
276 |
277 | public bool is_unlocked {
278 | get {
279 | return has_children;
280 | }
281 | }
282 |
283 | public bool is_on_encrypted_partition {
284 | get {
285 | return (type == "crypt");
286 | }
287 | }
288 |
289 | public bool is_lvm_partition(){
290 | return (type == "part") && fstype.down().contains("lvm2_member");
291 | }
292 |
293 | public bool is_top_level {
294 | get {
295 | //return ((type == "disk") || (type == "loop")) && (parent == null);
296 | return (pkname.length == 0);
297 | }
298 | }
299 |
300 | public bool has_children {
301 | get{
302 | return (children.size > 0);
303 | }
304 | }
305 |
306 | public Device? first_linux_child(){
307 |
308 | foreach(var child in children){
309 | if (child.has_linux_filesystem()){
310 | return child;
311 | }
312 | }
313 |
314 | return null;
315 | }
316 |
317 | public bool has_mounted_partitions {
318 | get {
319 | if (is_mounted){
320 | return true;
321 | }
322 |
323 | foreach(var child in children){
324 | if (child.has_mounted_partitions){
325 | return true;
326 | }
327 | }
328 |
329 | return false;
330 | }
331 | }
332 |
333 | public bool has_parent(){
334 | return (parent != null);
335 | }
336 |
337 | public bool is_system_device {
338 | get {
339 | foreach (var mnt in mount_points){
340 | switch (mnt.mount_point){
341 | case "/":
342 | case "/boot":
343 | case "/boot/efi":
344 | case "/home":
345 | case "/var":
346 | case "/usr":
347 | return true;
348 | default:
349 | if (fstype == "swap"){
350 | return true;
351 | }
352 | break;
353 | }
354 | }
355 |
356 | foreach(var child in children){
357 | if (child.is_system_device){
358 | return true;
359 | }
360 | }
361 |
362 | return false;
363 | }
364 | }
365 |
366 | public bool is_snap_volume {
367 | get {
368 | return (mount_points.size > 0) && (mount_points[0].mount_point.has_prefix("/snap/"));
369 | }
370 | }
371 |
372 | public bool is_swap_volume {
373 | get {
374 | return (fstype == "swap");
375 | }
376 | }
377 |
378 | // actions ------------------------------
379 |
380 | public bool unmount(){
381 |
382 | var cmd = "udisksctl unmount -b '%s'".printf(device);
383 | log_debug(cmd);
384 | string std_err, std_out;
385 | exec_sync(cmd, out std_out, out std_err);
386 |
387 | if (std_err.length > 0){
388 | log_error(std_err);
389 | }
390 |
391 | query_mount_points();
392 | return is_mounted;
393 | }
394 |
395 | public bool unlock(string _mapped_name, bool show_on_success = false){
396 |
397 | if (is_unlocked){ return true; }
398 |
399 | string std_out, std_err;
400 | int status;
401 | var cmd = "cryptsetup luksOpen '%s' '%s'".printf(device, _mapped_name);
402 | log_debug(cmd);
403 |
404 | status = exec_sync(cmd, out std_out, out std_err);
405 |
406 | query_changes();
407 |
408 | if (is_unlocked){
409 | string message = _("Device unlocked successfully");
410 | string details = "%s: %s, %s: %s".printf(_("Device"), device, _("Path"), mount_points[0].mount_point);
411 | bool is_error = false;
412 | show_message(message, details, is_error, show_on_success);
413 | return is_error;
414 | }
415 | else{
416 | string message = _("Failed to mount device");
417 | string details = "%s: %s\n\n%s".printf(_("Device"), device, std_err);
418 | bool is_error = true;
419 | show_message(message, details, is_error, show_on_success);
420 | return is_error;
421 | }
422 | }
423 |
424 | public void flush_buffers(){
425 | if (!is_mounted) { return; }
426 | if (type != "disk") { return; }
427 | string cmd = "blockdev --flushbufs %s".printf(device);
428 | Posix.system(cmd);
429 | }
430 |
431 | public static void show_message(string message, string details, bool is_error, bool show_on_success){
432 |
433 | if (is_error){
434 | log_error(message);
435 | log_error(details);
436 | }
437 | else if (show_on_success){
438 | log_msg(message);
439 | log_msg(details);
440 | }
441 | else{
442 | log_debug(message);
443 | log_debug(details);
444 | }
445 | }
446 | // static --------------------------------
447 |
448 | public static Gee.ArrayList get_block_devices(){
449 |
450 | /* Returns list of block devices
451 | Populates all fields in Device class */
452 |
453 | log_debug("Device: get_block_devices()");
454 |
455 | var list = get_block_devices_using_lsblk();
456 |
457 | if (device_list == null){
458 | device_list = list; // initialize in advance if null
459 | }
460 |
461 | //update_device_ids(list);
462 |
463 | update_usage(list);
464 |
465 | update_mounts(list);
466 |
467 | device_list = list;
468 |
469 | //print_device_list(list);
470 |
471 | //print_device_mounts(list);
472 |
473 | log_debug("Device: get_block_devices(): %d".printf(device_list.size));
474 |
475 | return device_list;
476 | }
477 |
478 | public static void update_usage(Gee.ArrayList? _list = null){
479 |
480 | //log_debug("Device: update_usage(): %d".printf(device_list.size));
481 |
482 | Gee.ArrayList? list = _list;
483 |
484 | if (list == null){ list = device_list; }
485 |
486 | var list2 = get_disk_space_using_df();
487 |
488 | foreach(var dev2 in list2){
489 |
490 | var dev = find_device_in_list(list, dev2.uuid);
491 |
492 | if (dev != null){
493 | dev.size_bytes = dev2.size_bytes;
494 | dev.used_bytes = dev2.used_bytes;
495 | dev.available_bytes = dev2.available_bytes;
496 | }
497 | }
498 | }
499 |
500 | public static void update_mounts(Gee.ArrayList? _list = null){
501 |
502 | //log_debug("Device: update_usage(): %d".printf(device_list.size));
503 |
504 | Gee.ArrayList? list = _list;
505 |
506 | if (list == null){ list = device_list; }
507 |
508 | var list2 = get_mounted_filesystems_using_mtab();
509 |
510 | foreach(var dev2 in list2){
511 |
512 | var dev = find_device_in_list(list, dev2.uuid);
513 |
514 | if (dev != null){
515 | dev.mount_points = dev2.mount_points;
516 | }
517 | }
518 | }
519 |
520 | private static void find_child_devices(Gee.ArrayList list, Device parent){
521 |
522 | if (lsblk_is_ancient && (parent.type == "disk")){
523 |
524 | foreach (var part in list){
525 |
526 | if ((part.kname != parent.kname) && part.kname.has_prefix(parent.kname)){
527 |
528 | parent.children.add(part);
529 | part.parent = parent;
530 | part.pkname = parent.kname;
531 | log_debug("%s -> %s".printf(parent.kname, part.kname));
532 | }
533 | }
534 | }
535 | else{
536 | foreach (var part in list){
537 | if (part.pkname == parent.kname){
538 | parent.children.add(part);
539 | part.parent = parent;
540 | }
541 | }
542 | }
543 |
544 | if (parent.removable){
545 | foreach(var child in parent.children){
546 | child.removable = true;
547 | }
548 | }
549 |
550 | parent.children.sort();
551 | }
552 |
553 | private static void find_toplevel_parent(Gee.ArrayList list, Device dev){
554 |
555 | if (dev.pkname.length == 0){ return; }
556 |
557 | var top_kname = dev.pkname;
558 |
559 | foreach (var part in list){
560 | if (part.kname == top_kname){
561 | if (part.pkname.length > 0){
562 | top_kname = part.pkname; // get parent's parent if not empty
563 | }
564 | }
565 | }
566 |
567 | dev.pkname_toplevel = top_kname;
568 |
569 | //log_debug("%s -> %s -> %s".printf(dev.pkname_toplevel, dev.pkname, dev.kname));
570 | }
571 |
572 | private static void find_child_devices_using_dmsetup(Gee.ArrayList list){
573 |
574 | string std_out, std_err;
575 | exec_sync("dmsetup deps -o blkdevname", out std_out, out std_err);
576 |
577 | /*
578 | sdb3_crypt: 1 dependencies : (sdb3)
579 | sda5_crypt: 1 dependencies : (sda5)
580 | mmcblk0_crypt: 1 dependencies : (mmcblk0)
581 | */
582 |
583 | Regex rex;
584 | MatchInfo match;
585 |
586 | foreach(string line in std_out.split("\n")){
587 | if (line.strip().length == 0) { continue; }
588 |
589 | try{
590 |
591 | rex = new Regex("""([^:]*)\:.*\((.*)\)""");
592 |
593 | if (rex.match (line, 0, out match)){
594 |
595 | string child_name = match.fetch(1).strip();
596 | string parent_kname = match.fetch(2).strip();
597 |
598 | Device parent = null;
599 | foreach(var dev in list){
600 | if ((dev.kname == parent_kname)){
601 | parent = dev;
602 | break;
603 | }
604 | }
605 |
606 | Device child = null;
607 | foreach(var dev in list){
608 | if ((dev.mapped_name == child_name)){
609 | child = dev;
610 | break;
611 | }
612 | }
613 |
614 | if ((parent != null) && (child != null)){
615 | child.pkname = parent.kname;
616 | //log_debug("%s -> %s".printf(parent.kname, child.kname));
617 | }
618 |
619 | }
620 | else{
621 | log_debug("no-match: %s".printf(line));
622 | }
623 | }
624 | catch(Error e){
625 | log_error (e.message);
626 | }
627 | }
628 | }
629 |
630 | public static void eject_removable_disk(Device dev){
631 |
632 | //http://www.redhatgeek.com/linux/remove-a-disk-from-redhatcentos-linux-without-rebooting-the-system
633 |
634 |
635 | string sh = "";
636 |
637 | string kname = dev.device.replace("/dev/","").strip();
638 |
639 | // mark offline
640 | string sysfile = "/sys/block/%s/device/state".printf(kname);
641 | sh += "echo 'offline' > %s \n".printf(sysfile);
642 |
643 | // delete entries from system
644 | sysfile = "/sys/block/%s/device/delete".printf(kname);
645 | sh += "echo '1' > %s \n".printf(sysfile);
646 |
647 | string std_out, std_err;
648 | exec_script_sync(sh, out std_out, out std_err, false, true);
649 |
650 | log_msg("ejected: %s".printf(dev.device));
651 | }
652 |
653 | public static Gee.ArrayList get_block_devices_using_lsblk(string dev_name = ""){
654 |
655 | //log_debug("Device: get_block_devices_using_lsblk()");
656 |
657 | /* Returns list of mounted partitions using 'lsblk' command
658 | Populates device, type, uuid, label */
659 |
660 | test_lsblk_version();
661 |
662 | var list = new Gee.ArrayList();
663 |
664 | string std_out;
665 | string std_err;
666 | string cmd;
667 | int ret_val;
668 | Regex rex;
669 | MatchInfo match;
670 |
671 | if (lsblk_is_ancient){
672 | cmd = "lsblk --bytes --pairs --output NAME,KNAME,LABEL,UUID,TYPE,FSTYPE,SIZE,MOUNTPOINT,MODEL,RO,RM,MAJ:MIN";
673 | }
674 | else{
675 | cmd = "lsblk --bytes --pairs --output NAME,KNAME,LABEL,UUID,TYPE,FSTYPE,SIZE,MOUNTPOINT,MODEL,RO,HOTPLUG,MAJ:MIN,PARTLABEL,PARTUUID,PKNAME,VENDOR,SERIAL,REV";
676 | }
677 |
678 | if (dev_name.length > 0){
679 | cmd += " %s".printf(dev_name);
680 | }
681 |
682 | ret_val = exec_sync(cmd, out std_out, out std_err);
683 |
684 | /*
685 | sample output
686 | -----------------
687 | NAME="sda" KNAME="sda" PKNAME="" LABEL="" UUID="" FSTYPE="" SIZE="119.2G" MOUNTPOINT="" HOTPLUG="0"
688 | NAME="sda1" KNAME="sda1" PKNAME="sda" LABEL="" UUID="5345-E139" FSTYPE="vfat" SIZE="47.7M" MOUNTPOINT="/boot/efi" HOTPLUG="0"
689 | NAME="mmcblk0p1" KNAME="mmcblk0p1" PKNAME="mmcblk0" LABEL="" UUID="3c0e4bbf" FSTYPE="crypto_LUKS" SIZE="60.4G" MOUNTPOINT="" HOTPLUG="1"
690 | NAME="luks-3c0" KNAME="dm-1" PKNAME="mmcblk0p1" LABEL="" UUID="f0d933c0-" FSTYPE="ext4" SIZE="60.4G" MOUNTPOINT="/mnt/sdcard" HOTPLUG="0"
691 |
692 | Note: Multiple loop devices can have same UUIDs.
693 | Example: Loop devices created by mounting the same ISO multiple times.
694 | */
695 |
696 | // parse output and add to list --------------------------------------------
697 |
698 | int index = -1;
699 |
700 | foreach(string line in std_out.split("\n")){
701 |
702 | if (line.strip().length == 0) { continue; }
703 |
704 | try{
705 | if (lsblk_is_ancient){
706 | rex = new Regex("""NAME="(.*)" KNAME="(.*)" LABEL="(.*)" UUID="(.*)" TYPE="(.*)" FSTYPE="(.*)" SIZE="(.*)" MOUNTPOINT="(.*)" MODEL="(.*)" RO="([0-9]+)" RM="([0-9]+)" MAJ:MIN="([0-9:]+)"""");
707 | }
708 | else{
709 | rex = new Regex("""NAME="(.*)" KNAME="(.*)" LABEL="(.*)" UUID="(.*)" TYPE="(.*)" FSTYPE="(.*)" SIZE="(.*)" MOUNTPOINT="(.*)" MODEL="(.*)" RO="([0-9]+)" HOTPLUG="([0-9]+)" MAJ:MIN="([0-9:]+)" PARTLABEL="(.*)" PARTUUID="(.*)" PKNAME="(.*)" VENDOR="(.*)" SERIAL="(.*)" REV="(.*)"""");
710 | }
711 |
712 | if (rex.match (line, 0, out match)){
713 |
714 | Device pi = new Device();
715 |
716 | int pos = 0;
717 |
718 | pi.name = match.fetch(++pos).strip();
719 | pi.kname = match.fetch(++pos).strip();
720 |
721 | pi.label = match.fetch(++pos); // don't strip; labels can have leading or trailing spaces
722 | pi.uuid = match.fetch(++pos).strip();
723 |
724 | pi.type = match.fetch(++pos).strip().down();
725 |
726 | pi.fstype = match.fetch(++pos).strip().down();
727 | pi.fstype = (pi.fstype == "crypto_luks") ? "luks" : pi.fstype;
728 | pi.fstype = (pi.fstype == "lvm2_member") ? "lvm2" : pi.fstype;
729 |
730 | pi.size_bytes = int64.parse(match.fetch(++pos).strip());
731 |
732 | var mp = match.fetch(++pos).strip();
733 | if (mp.length > 0){
734 | pi.mount_points.add(new MountEntry(pi,mp,""));
735 | }
736 |
737 | pi.model = match.fetch(++pos).strip();
738 |
739 | pi.read_only = (match.fetch(++pos).strip() == "1");
740 |
741 | pi.removable = (match.fetch(++pos).strip() == "1");
742 |
743 | string txt = match.fetch(++pos).strip();
744 | if (txt.contains(":")){
745 | pi.major = int.parse(txt.split(":")[0]);
746 | pi.minor = int.parse(txt.split(":")[1]);
747 | }
748 |
749 | if (!lsblk_is_ancient){
750 |
751 | pi.partlabel = match.fetch(++pos); // don't strip; labels can have leading or trailing spaces
752 | pi.partuuid = match.fetch(++pos).strip();
753 |
754 | pi.pkname = match.fetch(++pos).strip();
755 | pi.vendor = match.fetch(++pos).strip();
756 | pi.serial = match.fetch(++pos).strip();
757 | pi.revision = match.fetch(++pos).strip();
758 | }
759 |
760 | pi.order = ++index;
761 | pi.device = "/dev/%s".printf(pi.kname);
762 |
763 | if (pi.uuid.length > 0){
764 | pi.device_by_uuid = "/dev/disk/by-uuid/%s".printf(pi.uuid);
765 | pi.symlinks.add(pi.device_by_uuid);
766 | }
767 |
768 | if (pi.label.length > 0){
769 | pi.device_by_label = "/dev/disk/by-label/%s".printf(pi.label);
770 | pi.symlinks.add(pi.device_by_label);
771 | }
772 |
773 | if (pi.partuuid.length > 0){
774 | pi.device_by_partuuid = "/dev/disk/by-partuuid/%s".printf(pi.partuuid);
775 | pi.symlinks.add(pi.device_by_partuuid);
776 | }
777 |
778 | if (pi.partlabel.length > 0){
779 | pi.device_by_partlabel = "/dev/disk/by-partlabel/%s".printf(pi.partlabel);
780 | pi.symlinks.add(pi.device_by_partlabel);
781 | }
782 |
783 | list.add(pi);
784 | }
785 | else{
786 | log_error("no-match: %s".printf(line));
787 | }
788 | }
789 | catch(Error e){
790 | log_error (e.message);
791 | }
792 | }
793 |
794 | // add aliases from /dev/mapper/ -------------------------------
795 |
796 | try{
797 | var f_mapper = File.new_for_path ("/dev/mapper");
798 |
799 | var enumerator = f_mapper.enumerate_children (
800 | "%s,%s".printf(FileAttribute.STANDARD_NAME,
801 | FileAttribute.STANDARD_SYMLINK_TARGET),
802 | FileQueryInfoFlags.NOFOLLOW_SYMLINKS);
803 |
804 | FileInfo info;
805 | while ((info = enumerator.next_file ()) != null) {
806 |
807 | if (info.get_name() == "control") { continue; }
808 |
809 | string target = info.get_symlink_target();
810 |
811 | if (target == null){ continue; }
812 |
813 | string target_device = target.replace("..","/dev");
814 |
815 | foreach(var dev in list){
816 | if (dev.device == target_device){
817 | dev.mapped_name = info.get_name();
818 | dev.device_mapper = "/dev/mapper/" + info.get_name();
819 | dev.symlinks.add(dev.device_mapper);
820 | //log_debug("found link: %s -> %s".printf(mapped_file, dev.device));
821 | break;
822 | }
823 | }
824 | }
825 | }
826 | catch (Error e) {
827 | log_error (e.message);
828 | }
829 |
830 | // update relationships ----------------------------------------
831 |
832 | foreach (var part in list){
833 | find_child_devices(list, part);
834 | find_toplevel_parent(list, part);
835 | }
836 |
837 | //find_toplevel_parent();
838 |
839 | if (lsblk_is_ancient){
840 | find_child_devices_using_dmsetup(list);
841 | }
842 |
843 | //print_device_list(list);
844 |
845 | //log_debug("Device: get_block_devices_using_lsblk(): %d".printf(list.size));
846 |
847 | return list;
848 | }
849 |
850 | public static Gee.ArrayList get_disk_space_using_df(string dev_name_or_mount_point = ""){
851 |
852 | /*
853 | Returns list of mounted partitions using 'df' command
854 | Populates device, type, size, used and mount_point_list
855 | */
856 |
857 | //log_debug("Device: get_disk_space_using_df()");
858 |
859 | var list = new Gee.ArrayList();
860 |
861 | string cmd = "df -T -B1";
862 | if (dev_name_or_mount_point.length > 0){
863 | cmd += " '%s'".printf(escape_single_quote(dev_name_or_mount_point));
864 | }
865 | //log_debug(cmd);
866 |
867 | string std_out, std_err;
868 | exec_sync(cmd, out std_out, out std_err);
869 | //ret_val is not reliable, no need to check
870 |
871 | /*
872 | sample output
873 | -----------------
874 | Filesystem Type 1M-blocks Used Available Use% Mounted on
875 | /dev/sda3 ext4 25070M 19508M 4282M 83% /
876 | none tmpfs 1M 0M 1M 0% /sys/fs/cgroup
877 | udev devtmpfs 3903M 1M 3903M 1% /dev
878 | tmpfs tmpfs 789M 1M 788M 1% /run
879 | none tmpfs 5M 0M 5M 0% /run/lock
880 | /dev/sda3 ext4 25070M 19508M 4282M 83% /mnt/timeshift
881 | */
882 |
883 | string[] lines = std_out.split("\n");
884 |
885 | int line_num = 0;
886 | foreach(string line in lines){
887 |
888 | if (++line_num == 1) { continue; }
889 | if (line.strip().length == 0) { continue; }
890 |
891 | var pi = new Device();
892 |
893 | //parse & populate fields ------------------
894 |
895 | int k = 1;
896 | foreach(string val in line.split(" ")){
897 |
898 | if (val.strip().length == 0){ continue; }
899 |
900 | switch(k++){
901 | case 1:
902 | pi.device = val.strip();
903 | break;
904 | case 2:
905 | pi.fstype = val.strip();
906 | break;
907 | case 3:
908 | pi.size_bytes = int64.parse(val.strip());
909 | break;
910 | case 4:
911 | pi.used_bytes = int64.parse(val.strip());
912 | break;
913 | case 5:
914 | pi.available_bytes = int64.parse(val.strip());
915 | break;
916 | case 6:
917 | //pi.used_percent = val.strip();
918 | break;
919 | case 7:
920 | //string mount_point = val.strip();
921 | //if (!pi.mount_point_list.contains(mount_point)){
922 | // pi.mount_point_list.add(mount_point);
923 | //}
924 | break;
925 | }
926 | }
927 |
928 | /* Note:
929 | * The mount points displayed by 'df' are not reliable.
930 | * For example, if same device is mounted at 2 locations, 'df' displays only the first location.
931 | * Hence, we will not populate the 'mount_points' field in Device object
932 | * Use get_mounted_filesystems_using_mtab() if mount info is required
933 | * */
934 |
935 | if (!pi.device.has_prefix("/")){ continue; }
936 |
937 | // resolve device name --------------------
938 |
939 | //log_debug("pi.device=%s".printf(pi.device));
940 |
941 | pi.device = resolve_device_name(pi.device);
942 |
943 | //log_debug("resolved pi.device=%s".printf(pi.device));
944 |
945 | // get uuid ---------------------------
946 |
947 | pi.uuid = get_uuid_by_name(pi.device);
948 |
949 | //log_debug("resolved pi.uuid=%s".printf(pi.uuid));
950 |
951 | // add to map -------------------------
952 |
953 | if (pi.uuid.length > 0){
954 | list.add(pi);
955 | }
956 | }
957 |
958 | //log_debug("Device: get_disk_space_using_df(): %d".printf(list.size));
959 |
960 | return list;
961 | }
962 |
963 | public static Gee.ArrayList get_mounted_filesystems_using_mtab(){
964 |
965 | /* Returns list of mounted partitions by reading /proc/mounts
966 | Populates device, type and mount_point_list */
967 |
968 | var list = new Gee.ArrayList();
969 |
970 | // find mtab file -----------
971 |
972 | string mtab_path = "/proc/mounts";
973 |
974 | File f = File.new_for_path(mtab_path);
975 |
976 | if (!f.query_exists()){
977 |
978 | mtab_path = "/proc/self/mounts";
979 |
980 | f = File.new_for_path(mtab_path);
981 |
982 | if (!f.query_exists()){
983 |
984 | mtab_path = "/etc/mtab";
985 |
986 | f = File.new_for_path(mtab_path);
987 |
988 | if (!f.query_exists()){
989 |
990 | return list;
991 | }
992 | }
993 | }
994 |
995 | /* Note:
996 | * /etc/mtab represents what 'mount' passed to the kernel
997 | * whereas /proc/mounts shows the data as seen inside the kernel
998 | * Hence /proc/mounts is always up-to-date whereas /etc/mtab might not be
999 | * */
1000 |
1001 | //read -----------
1002 |
1003 | var mtab_lines = file_read(mtab_path);
1004 |
1005 | /*
1006 | sample mtab
1007 | -----------------
1008 | /dev/sda3 / ext4 rw,errors=remount-ro 0 0
1009 | proc /proc proc rw,noexec,nosuid,nodev 0 0
1010 | sysfs /sys sysfs rw,noexec,nosuid,nodev 0 0
1011 | none /sys/fs/cgroup tmpfs rw 0 0
1012 | none /sys/fs/fuse/connections fusectl rw 0 0
1013 | none /sys/kernel/debug debugfs rw 0 0
1014 | none /sys/kernel/security securityfs rw 0 0
1015 | udev /dev devtmpfs rw,mode=0755 0 0
1016 |
1017 | device - the device or remote filesystem that is mounted.
1018 | mountpoint - the place in the filesystem the device was mounted.
1019 | filesystemtype - the type of filesystem mounted.
1020 | options - the mount options for the filesystem
1021 | dump - used by dump to decide if the filesystem needs dumping.
1022 | fsckorder - used by fsck to detrmine the fsck pass to use.
1023 | */
1024 |
1025 | //parse ------------
1026 |
1027 | string[] lines = mtab_lines.split("\n");
1028 | var mount_list = new Gee.ArrayList();
1029 |
1030 | foreach (var line in lines){
1031 |
1032 | if (line.strip().length == 0) { continue; }
1033 |
1034 | var pi = new Device();
1035 |
1036 | var mp = new MountEntry(pi,"","");
1037 |
1038 | //parse & populate fields ------------------
1039 |
1040 | int k = 1;
1041 | foreach(string val in line.strip().split(" ")){
1042 |
1043 | if (val.strip().length == 0){ continue; }
1044 |
1045 | switch(k++){
1046 | case 1: //device
1047 | pi.device = val.strip();
1048 | break;
1049 | case 2: //mountpoint
1050 | mp.mount_point = val.strip().replace("""\040"""," ").replace("""\046""","&"); // replace space. TODO: other chars?
1051 | if (!mount_list.contains(mp.mount_point)){
1052 | mount_list.add(mp.mount_point);
1053 | pi.mount_points.add(mp);
1054 | }
1055 | break;
1056 | case 3: //filesystemtype
1057 | pi.fstype = val.strip();
1058 | break;
1059 | case 4: //options
1060 | mp.mount_options = val.strip();
1061 | break;
1062 | default:
1063 | //ignore
1064 | break;
1065 | }
1066 | }
1067 |
1068 | // resolve device names ----------------
1069 |
1070 | pi.device = resolve_device_name(pi.device);
1071 |
1072 | // get uuid ---------------------------
1073 |
1074 | pi.uuid = get_uuid_by_name(pi.device);
1075 |
1076 | // add to map -------------------------
1077 |
1078 | if (pi.uuid.length > 0){
1079 |
1080 | var dev = find_device_in_list(list, pi.uuid);
1081 |
1082 | if (dev == null){
1083 | list.add(pi);
1084 | }
1085 | else{
1086 | // add mount points to existing device
1087 | foreach(var item in pi.mount_points){
1088 | dev.mount_points.add(item);
1089 | }
1090 | }
1091 | }
1092 | }
1093 |
1094 | log_debug("Device: get_mounted_filesystems_using_mtab(): %d".printf(list.size));
1095 |
1096 | return list;
1097 | }
1098 |
1099 | public static Device? get_device_for_path(string path){
1100 |
1101 | Device dev = null;
1102 | string mpath = "";
1103 |
1104 | // find longest matching mount_path and device
1105 | foreach(var d in device_list){
1106 | // loop through all mount_points (not just mount_path)
1107 | foreach(var mp in d.mount_points){
1108 | if (path.has_prefix(mp.mount_point) && (mp.mount_point.length > mpath.length)){
1109 | dev = d;
1110 | mpath = mp.mount_point;
1111 | }
1112 | }
1113 | }
1114 |
1115 | return dev;
1116 | }
1117 |
1118 | // static helpers ----------------------------------
1119 |
1120 | public static void print_device_list_short(Gee.ArrayList list){
1121 |
1122 | string txt = "";
1123 | foreach(var item in list){
1124 | txt += (txt.length == 0) ? "" : " ";
1125 | txt += "%s".printf(file_basename(item.device));
1126 | }
1127 | log_debug("Devices: " + txt);
1128 | }
1129 |
1130 | public static Device? find_device_in_list(Gee.ArrayList list, string _dev_alias){
1131 |
1132 | string dev_alias = _dev_alias;
1133 |
1134 | if (dev_alias.down().has_prefix("uuid=")){
1135 |
1136 | dev_alias = dev_alias.split("=",2)[1].strip().down();
1137 | }
1138 | else if (file_exists(dev_alias) && file_is_symlink(dev_alias)){
1139 |
1140 | var link_path = file_get_symlink_target(dev_alias);
1141 |
1142 | dev_alias = link_path.replace("../../../","/dev/").replace("../../","/dev/").replace("../","/dev/");
1143 | }
1144 |
1145 | foreach(var dev in list){
1146 |
1147 | if (dev.device == dev_alias){
1148 | return dev;
1149 | }
1150 | else if (dev.uuid == dev_alias){
1151 | return dev;
1152 | }
1153 | else if (dev.label == dev_alias){
1154 | return dev;
1155 | }
1156 | else if (dev.partuuid == dev_alias){
1157 | return dev;
1158 | }
1159 | else if (dev.partlabel == dev_alias){
1160 | return dev;
1161 | }
1162 | else if (dev.device_by_uuid == dev_alias){
1163 | return dev;
1164 | }
1165 | else if (dev.device_by_label == dev_alias){
1166 | return dev;
1167 | }
1168 | else if (dev.device_by_partuuid == dev_alias){
1169 | return dev;
1170 | }
1171 | else if (dev.device_by_partlabel == dev_alias){
1172 | return dev;
1173 | }
1174 | else if (dev.device_mapper == dev_alias){
1175 | return dev;
1176 | }
1177 | else if (dev.mapped_name == dev_alias){ // check last
1178 | return dev;
1179 | }
1180 | }
1181 |
1182 | return null;
1183 | }
1184 |
1185 | public static Device? get_device(string dev_alias){
1186 |
1187 | return find_device_in_list(device_list, dev_alias);
1188 | }
1189 |
1190 | public static Device? get_device_by_path(string path_to_check){
1191 |
1192 | var list = Device.get_disk_space_using_df(path_to_check);
1193 |
1194 | //print_device_list_short(list);
1195 |
1196 | if (list.size > 0){
1197 | return list[0];
1198 | }
1199 |
1200 | return null;
1201 | }
1202 |
1203 | public static string get_uuid_by_name(string device){
1204 |
1205 | foreach(var dev in device_list){
1206 | if (dev.device == device){
1207 | return dev.uuid;
1208 | }
1209 | }
1210 |
1211 | return "";
1212 | }
1213 |
1214 | public static Gee.ArrayList get_device_mount_points(string dev_alias){
1215 |
1216 | var list_mtab = get_mounted_filesystems_using_mtab();
1217 |
1218 | var dev = find_device_in_list(list_mtab, dev_alias);
1219 |
1220 | if (dev != null){
1221 | return dev.mount_points;
1222 | }
1223 | else{
1224 | return (new Gee.ArrayList());
1225 | }
1226 | }
1227 |
1228 | public static bool device_is_mounted(string dev_name_or_uuid){
1229 |
1230 | var mps = Device.get_device_mount_points(dev_name_or_uuid);
1231 | if (mps.size > 0){
1232 | return true;
1233 | }
1234 |
1235 | return false;
1236 | }
1237 |
1238 | public static bool mount_point_in_use(string mount_point){
1239 |
1240 | var list = Device.get_mounted_filesystems_using_mtab();
1241 |
1242 | foreach (var dev in list){
1243 |
1244 | foreach(var mp in dev.mount_points){
1245 |
1246 | if (mp.mount_point.has_prefix(mount_point)){
1247 | // check for any mount point at or under the given mount_point
1248 | return true;
1249 | }
1250 | }
1251 | }
1252 | return false;
1253 | }
1254 |
1255 | public static string resolve_device_name(string dev_alias){
1256 |
1257 | var dev = find_device_in_list(device_list, dev_alias);
1258 |
1259 | if (dev != null){
1260 | return dev.device;
1261 | }
1262 | else{
1263 | return dev_alias;
1264 | }
1265 | }
1266 |
1267 | // instance helpers -------------------------------
1268 |
1269 | public void copy_fields_from(Device dev2){
1270 |
1271 | this.device = dev2.device;
1272 | this.name = dev2.name;
1273 | this.kname = dev2.kname;
1274 | this.pkname = dev2.pkname;
1275 | this.pkname_toplevel = dev2.pkname_toplevel;
1276 | this.mapped_name = dev2.mapped_name;
1277 | this.uuid = dev2.uuid;
1278 | this.label = dev2.label;
1279 | this.major = dev2.major;
1280 | this.minor = dev2.minor;
1281 |
1282 | this.type = dev2.type;
1283 | this.fstype = dev2.fstype;
1284 | this.dist_info = dev2.dist_info;
1285 |
1286 | this.vendor = dev2.vendor;
1287 | this.model = dev2.model;
1288 | this.serial = dev2.serial;
1289 | this.revision = dev2.revision;
1290 | this.removable = dev2.removable;
1291 | this.read_only = dev2.read_only;
1292 |
1293 | this.size_bytes = dev2.size_bytes;
1294 | this.used_bytes = dev2.used_bytes;
1295 | this.available_bytes = dev2.available_bytes;
1296 |
1297 | this.mount_points = dev2.mount_points;
1298 | this.symlinks = dev2.symlinks;
1299 | this.parent = dev2.parent;
1300 | this.children = dev2.children;
1301 |
1302 | // aliases
1303 | this.device_mapper = dev2.device_mapper;
1304 | this.device_by_uuid = dev2.device_by_uuid;
1305 | this.device_by_label = dev2.device_by_label;
1306 | this.device_by_partuuid = dev2.device_by_partuuid;
1307 | this.device_by_partlabel = dev2.device_by_partlabel;
1308 |
1309 | this.major = dev2.major;
1310 | this.minor = dev2.minor;
1311 | }
1312 |
1313 | public Device copy(){
1314 | var dev = new Device();
1315 | dev.copy_fields_from(this);
1316 | return dev;
1317 | }
1318 |
1319 | public Device? query_changes(){
1320 |
1321 | foreach (var dev in get_block_devices()){
1322 | if (dev.device == device){
1323 | copy_fields_from(dev);
1324 | break;
1325 | }
1326 | }
1327 |
1328 | return this;
1329 | }
1330 |
1331 | public void query_disk_space(){
1332 |
1333 | var list2 = get_disk_space_using_df(device);
1334 |
1335 | var dev2 = find_device_in_list(list2, uuid);
1336 |
1337 | if (dev2 != null){
1338 | // update size fields
1339 | size_bytes = dev2.size_bytes;
1340 | used_bytes = dev2.used_bytes;
1341 | available_bytes = dev2.available_bytes;
1342 | }
1343 | }
1344 |
1345 | public void query_mount_points(){
1346 |
1347 | var list = get_mounted_filesystems_using_mtab();
1348 |
1349 | var dev = find_device_in_list(list, device);
1350 |
1351 | if (dev != null){
1352 | mount_points = dev.mount_points; // update field
1353 | }
1354 | }
1355 |
1356 | // testing -----------------------------------
1357 |
1358 | public static void test_all(){
1359 |
1360 | get_devices();
1361 |
1362 | print_device_list();
1363 |
1364 | print_device_relationships();
1365 |
1366 | print_device_mounts();
1367 | }
1368 |
1369 | public static void print_device_list(Gee.ArrayList? _list = null){
1370 |
1371 | Gee.ArrayList? list = _list;
1372 | if (list == null){ list = device_list; }
1373 |
1374 | log_msg("");
1375 |
1376 | log_msg("%-15s %-10s %-10s %-10s %-10s %-10s".printf(
1377 | "device",
1378 | "pkname",
1379 | "kname",
1380 | "type",
1381 | "fstype",
1382 | "mapped"
1383 | ));
1384 |
1385 | log_msg(string.nfill(100, '-'));
1386 |
1387 | foreach(var dev in list){
1388 | log_msg("%-15s %-10s %-10s %-10s %-10s %-10s".printf(
1389 | dev.device ,
1390 | dev.pkname,
1391 | dev.kname,
1392 | dev.type,
1393 | dev.fstype,
1394 | dev.mapped_name
1395 | ));
1396 | }
1397 |
1398 | log_msg("");
1399 |
1400 | //print_device_relationships(list);
1401 | }
1402 |
1403 | public static void print_device_relationships(Gee.ArrayList? _list = null){
1404 |
1405 | Gee.ArrayList? list = _list;
1406 | if (list == null){ list = device_list; }
1407 |
1408 | log_msg("");
1409 |
1410 | log_msg(string.nfill(100, '-'));
1411 |
1412 | foreach(var dev in list){
1413 |
1414 | if (dev.pkname.length == 0){
1415 |
1416 | log_msg("%-10s".printf(dev.kname));
1417 |
1418 | foreach(var child1 in dev.children){
1419 | if (!child1.has_children){
1420 | log_msg("%-10s -- %-10s".printf(dev.kname, child1.kname));
1421 | }
1422 | else{
1423 | foreach(var child2 in child1.children){
1424 | log_msg("%-10s -- %-10s -- %-10s".printf(dev.kname, child1.kname, child2.kname));
1425 | }
1426 | }
1427 | }
1428 | }
1429 | }
1430 |
1431 | log_msg("");
1432 | }
1433 |
1434 | public static void print_device_mounts(Gee.ArrayList? _list = null){
1435 |
1436 | Gee.ArrayList? list = _list;
1437 | if (list == null){ list = device_list; }
1438 |
1439 | stdout.printf("\n");
1440 | stdout.printf(string.nfill(100, '-') + "\n");
1441 |
1442 | foreach(var dev in list){
1443 |
1444 | stdout.printf("%-15s: %s\n".printf(dev.device, dev.mount_path));
1445 |
1446 | foreach(var mp in dev.mount_points){
1447 | stdout.printf(" -> %s: %s\n".printf(mp.mount_point, mp.mount_options));
1448 | }
1449 | }
1450 |
1451 | stdout.printf("\n");
1452 | }
1453 | }
1454 |
1455 |
1456 |
1457 |
1458 |
1459 |
--------------------------------------------------------------------------------
/src/Utility/Console/MountEntry.vala:
--------------------------------------------------------------------------------
1 | using TeeJee.Logging;
2 | using TeeJee.FileSystem;
3 | using TeeJee.ProcessHelper;
4 | using TeeJee.System;
5 | using TeeJee.Misc;
6 |
7 | public class MountEntry : GLib.Object{
8 | public Device device = null;
9 | public string mount_point = "";
10 | public string mount_options = "";
11 |
12 | public MountEntry(Device? device, string mount_point, string mount_options){
13 | this.device = device;
14 | this.mount_point = mount_point;
15 | this.mount_options = mount_options;
16 | }
17 |
18 | public string subvolume_name(){
19 | if (mount_options.contains("subvol=")){
20 | return mount_options.split("subvol=")[1].split(",")[0].strip();
21 | }
22 | else{
23 | return "";
24 | }
25 | }
26 |
27 | public string lvm_name(){
28 | if ((device != null) && (device.type == "lvm") && (device.mapped_name.length > 0)){
29 | return device.mapped_name.strip();
30 | }
31 | else{
32 | return "";
33 | }
34 | }
35 |
36 | public static MountEntry? find_entry_by_mount_point(
37 | Gee.ArrayList entries, string mount_path){
38 |
39 | foreach(var entry in entries){
40 | if (entry.mount_point == mount_path){
41 | return entry;
42 | }
43 | }
44 |
45 | return null;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/Utility/Console/TeeJee.FileSystem.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * TeeJee.FileSystem.vala
4 | *
5 | * Copyright 2016 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | namespace TeeJee.FileSystem{
26 |
27 | /* Convenience functions for handling files and directories */
28 |
29 | using TeeJee.Logging;
30 | using TeeJee.ProcessHelper;
31 | using TeeJee.Misc;
32 |
33 | public const int64 KB = 1000;
34 | public const int64 MB = 1000 * KB;
35 | public const int64 GB = 1000 * MB;
36 | public const int64 TB = 1000 * GB;
37 | public const int64 KiB = 1024;
38 | public const int64 MiB = 1024 * KiB;
39 | public const int64 GiB = 1024 * MiB;
40 | public const int64 TiB = 1024 * GiB;
41 |
42 | // path helpers ----------------------------
43 |
44 | public string file_parent(string file_path){
45 | return File.new_for_path(file_path).get_parent().get_path();
46 | }
47 |
48 | public string file_basename(string file_path){
49 | return File.new_for_path(file_path).get_basename();
50 | }
51 |
52 | public string file_get_title(string file_path){
53 |
54 | string file_name = File.new_for_path(file_path).get_basename();
55 |
56 | int end = file_name.length - file_get_extension(file_path).length;
57 | return file_name[0:end];
58 | }
59 |
60 | public string file_get_extension(string file_path){
61 |
62 | string file_name = File.new_for_path(file_path).get_basename();
63 |
64 | string[] parts = file_name.split(".");
65 |
66 | if (parts.length == 1){
67 | // no extension
68 | return "";
69 | }
70 |
71 | if (parts.length > 2){
72 |
73 | string ext1 = parts[parts.length-2];
74 | string ext2 = parts[parts.length-1];
75 |
76 | if ((ext1.length <= 4) && (ext2.length <= 4) && (ext1 == "tar")){
77 | // 2-part extension
78 | return ".%s.%s".printf(parts[parts.length-2], parts[parts.length-1]);
79 | }
80 | }
81 |
82 | if (parts.length > 1){
83 | return ".%s".printf(parts[parts.length - 1]);
84 | }
85 |
86 | return "";
87 | }
88 |
89 | public string file_generate_unique_name(string file_path){
90 |
91 | string title = file_get_title(file_path);
92 | string extension = file_get_extension(file_path);
93 | string location = file_parent(file_path);
94 |
95 | string outpath = file_path;
96 |
97 | int index = 1;
98 | while (file_exists(outpath)){
99 | string new_name = "%s%s%s".printf(title, " (%d)".printf(index++), extension);
100 | outpath = path_combine(location, new_name);
101 | }
102 |
103 | return outpath;
104 | }
105 |
106 | public string path_combine(string path1, string path2){
107 | return GLib.Path.build_path("/", path1, path2);
108 | }
109 |
110 | public string remove_trailing_slash(string path){
111 | if (path.has_suffix("/")){
112 | return path[0:path.length - 1];
113 | }
114 | else{
115 | return path;
116 | }
117 | }
118 |
119 | // file helpers -----------------------------
120 |
121 | public bool file_exists(string item_path){
122 |
123 | /* check if item exists on disk*/
124 |
125 | var item = File.parse_name(item_path);
126 | return item.query_exists();
127 | }
128 |
129 | public bool file_is_dir(string file_path){
130 |
131 | try {
132 | var file = File.new_for_path (file_path);
133 |
134 | if (file.query_exists()) {
135 |
136 | var info = file.query_info("%s".printf(FileAttribute.STANDARD_TYPE),0); // follow symlinks
137 |
138 | var file_type = info.get_file_type();
139 |
140 | return (file_type == FileType.DIRECTORY);
141 | }
142 | }
143 | catch (Error e) {
144 | log_error (e.message);
145 | }
146 |
147 | return false;
148 | }
149 |
150 | public bool file_is_regular(string file_path){
151 |
152 | try {
153 | var file = File.new_for_path (file_path);
154 |
155 | if (file.query_exists()) {
156 |
157 | var info = file.query_info("%s".printf(FileAttribute.STANDARD_TYPE),0); // follow symlinks
158 |
159 | var file_type = info.get_file_type();
160 |
161 | return (file_type == FileType.REGULAR);
162 | }
163 | }
164 | catch (Error e) {
165 | log_error (e.message);
166 | }
167 |
168 | return false;
169 | }
170 |
171 | public bool file_is_special(string file_path){
172 |
173 | try {
174 | var file = File.new_for_path (file_path);
175 |
176 | if (file.query_exists()) {
177 |
178 | var info = file.query_info("%s".printf(FileAttribute.STANDARD_TYPE), 0); // follow symlinks
179 |
180 | var file_type = info.get_file_type();
181 |
182 | return (file_type != FileType.REGULAR) && (file_type != FileType.DIRECTORY);
183 | }
184 | }
185 | catch (Error e) {
186 | log_error (e.message);
187 | }
188 |
189 | return false;
190 | }
191 |
192 | public bool file_is_symlink(string file_path){
193 |
194 | try {
195 | var file = File.new_for_path (file_path);
196 |
197 | if (file.query_exists()) {
198 |
199 | var info = file.query_info("%s".printf(FileAttribute.STANDARD_TYPE), FileQueryInfoFlags.NOFOLLOW_SYMLINKS); // don't follow symlinks
200 |
201 | var file_type = info.get_file_type();
202 |
203 | return (file_type == FileType.SYMBOLIC_LINK);
204 | }
205 | }
206 | catch (Error e) {
207 | log_error (e.message);
208 | }
209 |
210 | return false;
211 | }
212 |
213 | public bool file_delete(string file_path){
214 |
215 | /* Check and delete file */
216 |
217 | try {
218 | var file = File.new_for_path (file_path);
219 | if (file.query_exists ()) {
220 | file.delete ();
221 | }
222 | return true;
223 | } catch (Error e) {
224 | log_error (e.message);
225 | log_error(_("Failed to delete file") + ": %s".printf(file_path));
226 | return false;
227 | }
228 | }
229 |
230 | public int64 file_line_count (string file_path){
231 | /* Count number of lines in text file */
232 | string cmd = "wc -l '%s'".printf(escape_single_quote(file_path));
233 | string std_out, std_err;
234 | exec_sync(cmd, out std_out, out std_err);
235 | return long.parse(std_out.split("\t")[0]);
236 | }
237 |
238 | public string? file_read (string file_path){
239 |
240 | /* Reads text from file */
241 |
242 | string txt;
243 | size_t size;
244 |
245 | try{
246 | GLib.FileUtils.get_contents (file_path, out txt, out size);
247 | return txt;
248 | }
249 | catch (Error e){
250 | log_error (e.message);
251 | log_error(_("Failed to read file") + ": %s".printf(file_path));
252 | }
253 |
254 | return null;
255 | }
256 |
257 | public bool file_write (string file_path, string contents, bool overwrite_in_place = false){
258 |
259 | /* Write text to file */
260 |
261 | try{
262 |
263 | dir_create(file_parent(file_path));
264 |
265 | var file = File.new_for_path (file_path);
266 |
267 | if (file.query_exists() && overwrite_in_place){
268 |
269 | var iostream = file.open_readwrite();
270 | //int64 fsize = iostream.query_info("%s".printf(FileAttribute.STANDARD_SIZE)).get_size();
271 | //iostream.seek (0, GLib.SeekType.END);
272 | iostream.truncate_fn(0);
273 | //iostream.seek (0, GLib.SeekType.SET);
274 | var ostream = iostream.output_stream;
275 | var data_stream = new DataOutputStream(ostream);
276 | data_stream.put_string(contents);
277 | data_stream.close();
278 | }
279 | else{
280 |
281 | if (file.query_exists()) {
282 | file.delete();
283 | }
284 |
285 | var file_stream = file.create (FileCreateFlags.REPLACE_DESTINATION);
286 | var data_stream = new DataOutputStream (file_stream);
287 | data_stream.put_string (contents);
288 | data_stream.close();
289 | }
290 |
291 | return true;
292 | }
293 | catch (Error e) {
294 | log_error(e.message);
295 | return false;
296 | }
297 | }
298 |
299 | public bool file_copy (string src_file, string dest_file, bool follow_symlinks){
300 |
301 | try{
302 | var file_src = File.new_for_path(src_file);
303 |
304 | if (file_src.query_exists()) {
305 |
306 | var file_dest = File.new_for_path (dest_file);
307 |
308 | var flags = FileCopyFlags.OVERWRITE;
309 |
310 | if (!follow_symlinks){
311 | flags = flags | FileCopyFlags.NOFOLLOW_SYMLINKS;
312 | }
313 |
314 | file_src.copy(file_dest, flags, null, null);
315 | return true;
316 | }
317 | }
318 | catch(Error e){
319 | log_error (e.message);
320 | log_error(_("Failed to copy file") + ": '%s', '%s'".printf(src_file, dest_file));
321 | }
322 |
323 | return false;
324 | }
325 |
326 | public bool file_move (string src_file, string dest_file, bool follow_symlinks){
327 | try{
328 | var file_src = File.new_for_path (src_file);
329 |
330 | if (file_src.query_exists()) {
331 |
332 | var file_dest = File.new_for_path (dest_file);
333 |
334 | var flags = FileCopyFlags.OVERWRITE;
335 |
336 | if (!follow_symlinks){
337 | flags = flags | FileCopyFlags.NOFOLLOW_SYMLINKS;
338 | }
339 |
340 | file_src.move(file_dest, flags, null, null);
341 | return true;
342 | }
343 | else{
344 | log_error(_("File not found") + ": '%s'".printf(src_file));
345 | return false;
346 | }
347 | }
348 | catch(Error e){
349 | log_error (e.message);
350 | log_error(_("Failed to move file") + ": '%s', '%s'".printf(src_file, dest_file));
351 | return false;
352 | }
353 | }
354 |
355 | // file info -------------------------------------------
356 |
357 | public int64 file_get_size(string file_path){
358 | try{
359 | File file = File.parse_name (file_path);
360 | if (FileUtils.test(file_path, GLib.FileTest.EXISTS)){
361 | if (FileUtils.test(file_path, GLib.FileTest.IS_REGULAR)
362 | && !FileUtils.test(file_path, GLib.FileTest.IS_SYMLINK)){
363 | return file.query_info("standard::size",0).get_size();
364 | }
365 | }
366 | }
367 | catch(Error e){
368 | log_error (e.message);
369 | }
370 |
371 | return -1;
372 | }
373 |
374 | public DateTime file_get_modified_date(string file_path){
375 | try{
376 | FileInfo info;
377 | File file = File.parse_name (file_path);
378 | if (file.query_exists()) {
379 | info = file.query_info("%s".printf(FileAttribute.TIME_MODIFIED), 0);
380 | return (new DateTime.from_timeval_utc(info.get_modification_time())).to_local();
381 | }
382 | }
383 | catch (Error e) {
384 | log_error (e.message);
385 | }
386 |
387 | return (new DateTime.from_unix_utc(0)); //1970
388 | }
389 |
390 | public string file_get_symlink_target(string file_path){
391 | try{
392 | FileInfo info;
393 | File file = File.parse_name (file_path);
394 | if (file.query_exists()) {
395 | info = file.query_info("%s".printf(FileAttribute.STANDARD_SYMLINK_TARGET), 0);
396 | return info.get_symlink_target();
397 | }
398 | }
399 | catch (Error e) {
400 | log_error (e.message);
401 | }
402 |
403 | return "";
404 | }
405 |
406 | // directory helpers -------------------------------------------
407 |
408 | public bool dir_exists(string dir_path){
409 |
410 | return file_is_dir(dir_path);
411 | }
412 |
413 | public bool dir_create(string dir_path, bool show_message = false){
414 |
415 | /* Creates a directory along with parents */
416 |
417 | try{
418 | var dir = File.parse_name (dir_path);
419 | if (dir.query_exists () == false) {
420 | dir.make_directory_with_parents (null);
421 | if (show_message){
422 | log_msg(_("Created directory") + ": %s".printf(dir_path));
423 | }
424 | }
425 | return true;
426 | }
427 | catch (Error e) {
428 | log_error (e.message);
429 | log_error(_("Failed to create dir") + ": %s".printf(dir_path));
430 | return false;
431 | }
432 | }
433 |
434 | public bool dir_delete(string dir_path, bool show_message = false){
435 |
436 | /* Recursively deletes directory along with contents */
437 |
438 | if (!dir_exists(dir_path)){ return true; }
439 |
440 | string cmd = "rm -rf";
441 |
442 | if (show_message){
443 | cmd += "v";
444 | }
445 |
446 | cmd += " '%s'".printf(escape_single_quote(dir_path));
447 |
448 | int status = Posix.system(cmd);
449 | return (status == 0);
450 | }
451 |
452 | public bool chown(string dir_path, string user_name, string group){
453 | string cmd = "chown %s:%s -R '%s'".printf(user_name, group, escape_single_quote(dir_path));
454 | log_debug("cmd: %s".printf(cmd));
455 | int status = exec_sync(cmd, null, null);
456 | return (status == 0);
457 | }
458 |
459 | // misc --------------------------------------------------
460 |
461 | public string format_file_size (uint64 size, bool binary_units = false, string unit = "", bool show_units = true, int decimals = 1){
462 |
463 | int64 unit_k = binary_units ? 1024 : 1000;
464 | int64 unit_m = binary_units ? 1024 * unit_k : 1000 * unit_k;
465 | int64 unit_g = binary_units ? 1024 * unit_m : 1000 * unit_m;
466 | int64 unit_t = binary_units ? 1024 * unit_g : 1000 * unit_g;
467 |
468 | string txt = "";
469 |
470 | if ((size > unit_t) && ((unit.length == 0) || (unit == "t"))){
471 | txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_t));
472 | if (show_units){
473 | txt += " %sB".printf(binary_units ? "Ti" : "T");
474 | }
475 | }
476 | else if ((size > unit_g) && ((unit.length == 0) || (unit == "g"))){
477 | txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_g));
478 | if (show_units){
479 | txt += " %sB".printf(binary_units ? "Gi" : "G");
480 | }
481 | }
482 | else if ((size > unit_m) && ((unit.length == 0) || (unit == "m"))){
483 | txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_m));
484 | if (show_units){
485 | txt += " %sB".printf(binary_units ? "Mi" : "M");
486 | }
487 | }
488 | else if ((size > unit_k) && ((unit.length == 0) || (unit == "k"))){
489 | txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_k));
490 | if (show_units){
491 | txt += " %sB".printf(binary_units ? "Ki" : "K");
492 | }
493 | }
494 | else{
495 | txt += "%'0lld".printf(size);
496 | if (show_units){
497 | txt += " B";
498 | }
499 | }
500 |
501 | return txt;
502 | }
503 |
504 | public string escape_single_quote(string file_path){
505 | return file_path.replace("'","'\\''");
506 | }
507 |
508 | public int chmod (string file, string permission){
509 |
510 | /* Change file permissions */
511 | string cmd = "chmod %s '%s'".printf(permission, escape_single_quote(file));
512 | return exec_sync (cmd, null, null);
513 | }
514 | }
515 |
--------------------------------------------------------------------------------
/src/Utility/Console/TeeJee.Logging.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * TeeJee.Logging.vala
4 | *
5 | * Copyright 2016 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | namespace TeeJee.Logging{
26 |
27 | /* Functions for logging messages to console and log files */
28 |
29 | using TeeJee.Misc;
30 |
31 | public DataOutputStream dos_log;
32 | public string err_log;
33 | public bool LOG_ENABLE = true;
34 | public bool LOG_TIMESTAMP = false;
35 | public bool LOG_COLORS = true;
36 | public bool LOG_DEBUG = false;
37 | public bool LOG_COMMANDS = false;
38 |
39 | public void log_msg (string message, bool highlight = false){
40 |
41 | if (!LOG_ENABLE) { return; }
42 |
43 | string msg = "";
44 |
45 | if (highlight && LOG_COLORS){
46 | msg += "\033[1;38;5;34m";
47 | }
48 |
49 | if (LOG_TIMESTAMP){
50 | msg += "[" + timestamp(true) + "] ";
51 | }
52 |
53 | msg += message;
54 |
55 | if (highlight && LOG_COLORS){
56 | msg += "\033[0m";
57 | }
58 |
59 | msg += "\n";
60 |
61 | stdout.printf (msg);
62 | stdout.flush();
63 |
64 | try {
65 | if (dos_log != null){
66 | dos_log.put_string ("[%s] %s\n".printf(timestamp(), message));
67 | }
68 | }
69 | catch (Error e) {
70 | stdout.printf (e.message);
71 | }
72 | }
73 |
74 | public void log_error (string message, bool highlight = false,
75 | bool is_warning = false){
76 |
77 | if (!LOG_ENABLE) { return; }
78 |
79 | string msg = "";
80 |
81 | if (highlight && LOG_COLORS){
82 | msg += "\033[1;38;5;160m";
83 | }
84 |
85 | if (LOG_TIMESTAMP){
86 | msg += "[" + timestamp(true) + "] ";
87 | }
88 |
89 | string prefix = (is_warning) ? _("W") : _("E");
90 |
91 | msg += prefix + ": " + message;
92 |
93 | if (highlight && LOG_COLORS){
94 | msg += "\033[0m";
95 | }
96 |
97 | msg += "\n";
98 |
99 | stderr.printf (msg);
100 | stderr.flush();
101 |
102 | try {
103 | string str = "[%s] %s: %s\n".printf(timestamp(), prefix, message);
104 |
105 | if (dos_log != null){
106 | dos_log.put_string (str);
107 | }
108 |
109 | if (err_log != null){
110 | err_log += "%s\n".printf(message);
111 | }
112 | }
113 | catch (Error e) {
114 | stdout.printf (e.message);
115 | }
116 | }
117 |
118 | public void log_debug (string message){
119 | if (!LOG_ENABLE) { return; }
120 |
121 | if (LOG_DEBUG){
122 | log_msg ("D: " + message);
123 | }
124 |
125 | try {
126 | if (dos_log != null){
127 | dos_log.put_string ("[%s] %s\n".printf(timestamp(), message));
128 | }
129 | }
130 | catch (Error e) {
131 | stdout.printf (e.message);
132 | }
133 | }
134 |
135 | public void enable_logging(string log_path){
136 |
137 | var now = new DateTime.now_local();
138 |
139 | string log_file = "%s/%s.log".printf(log_path, now.format("%Y-%m-%d_%H-%M-%S"));
140 |
141 | try{
142 | var file = File.new_for_path (log_path);
143 | if (!file.query_exists ()) {
144 | file.make_directory_with_parents();
145 | }
146 |
147 | file = File.new_for_path (log_file);
148 | if (file.query_exists ()) {
149 | file.delete ();
150 | }
151 |
152 | dos_log = new DataOutputStream (file.create(FileCreateFlags.REPLACE_DESTINATION));
153 | if (LOG_DEBUG){
154 | log_debug(_("Session log file") + ": %s".printf(log_file));
155 | }
156 | }
157 | catch(Error e){
158 | stdout.printf (e.message);
159 | }
160 | }
161 |
162 | public void log_to_file (string message, bool highlight = false){
163 | try {
164 | if (dos_log != null){
165 | dos_log.put_string ("[%s] %s\n".printf(timestamp(), message));
166 | }
167 | }
168 | catch (Error e) {
169 | stdout.printf (e.message);
170 | }
171 | }
172 |
173 | public void log_draw_line(){
174 | log_msg(string.nfill(70,'='));
175 | }
176 |
177 | public void err_log_clear(){
178 | err_log = "";
179 | }
180 |
181 | public void err_log_disable(){
182 | err_log = null;
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/src/Utility/Console/TeeJee.Misc.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * TeeJee.Misc.vala
4 | *
5 | * Copyright 2016 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | namespace TeeJee.Misc {
26 |
27 | /* Various utility functions */
28 |
29 | using TeeJee.Logging;
30 |
31 | // timestamp ----------------
32 |
33 | public string timestamp (bool show_millis = false){
34 |
35 | /* Returns a formatted timestamp string */
36 |
37 | // NOTE: format() does not support milliseconds
38 |
39 | DateTime now = new GLib.DateTime.now_local();
40 |
41 | if (show_millis){
42 | var msec = now.get_microsecond () / 1000;
43 | return "%s.%03d".printf(now.format("%H:%M:%S"), msec);
44 | }
45 | else{
46 | return now.format ("%H:%M:%S");
47 | }
48 | }
49 |
50 | public string timestamp_numeric (){
51 |
52 | /* Returns a numeric timestamp string */
53 |
54 | return "%ld".printf((long) time_t ());
55 | }
56 |
57 | public string timestamp_for_path (){
58 |
59 | /* Returns a formatted timestamp string */
60 |
61 | Time t = Time.local (time_t ());
62 | return t.format ("%Y-%d-%m_%H-%M-%S");
63 | }
64 |
65 | public string random_string(int length = 8, string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"){
66 | string random = "";
67 |
68 | for(int i=0;i
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | namespace TeeJee.ProcessHelper{
26 |
27 | using TeeJee.Logging;
28 | using TeeJee.FileSystem;
29 | using TeeJee.Misc;
30 |
31 | public string TEMP_DIR;
32 |
33 | /* Convenience functions for executing commands and managing processes */
34 |
35 | // execute process ---------------------------------
36 |
37 | public static void init_tmp(string subdir_name){
38 |
39 | TEMP_DIR = Environment.get_tmp_dir() + "/" + subdir_name;
40 | dir_create(TEMP_DIR);
41 | chmod(TEMP_DIR, "a+rwx"); // allow application to create folders when running as nomal user
42 |
43 | //log_msg("chmod: %s: %s".printf(TEMP_DIR, "a+rwx"));
44 |
45 | TEMP_DIR += "/" + random_string();
46 | dir_create(TEMP_DIR);
47 | chmod(TEMP_DIR, "a+rwx");
48 |
49 | //log_msg("chmod: %s: %s".printf(TEMP_DIR, "a+rwx"));
50 |
51 | string std_out, std_err;
52 | exec_script_sync("echo 'ok'",out std_out,out std_err, true);
53 |
54 | if ((std_out == null)||(std_out.strip() != "ok")){
55 |
56 | TEMP_DIR = Environment.get_home_dir() + "/.temp/" + subdir_name + "/" + random_string();
57 | exec_sync("rm -rf '%s'".printf(TEMP_DIR), null, null);
58 | dir_create(TEMP_DIR);
59 | }
60 |
61 | //log_debug("TEMP_DIR=" + TEMP_DIR);
62 | }
63 |
64 | public string create_temp_subdir(){
65 | var temp = "%s/%s".printf(TEMP_DIR, random_string());
66 | dir_create(temp);
67 | return temp;
68 | }
69 |
70 | public int exec_sync (string cmd, out string? std_out, out string? std_err){
71 |
72 | /* Executes single command synchronously.
73 | * Pipes and multiple commands are not supported.
74 | * std_out, std_err can be null. Output will be written to terminal if null. */
75 |
76 | try {
77 | int status;
78 | Process.spawn_command_line_sync(cmd, out std_out, out std_err, out status);
79 | return status;
80 | }
81 | catch (Error e){
82 | log_error (e.message);
83 | return -1;
84 | }
85 | }
86 |
87 | public int exec_script_sync (string script,
88 | out string? std_out = null, out string? std_err = null,
89 | bool supress_errors = false, bool run_as_admin = false,
90 | bool cleanup_tmp = true, bool print_to_terminal = false){
91 |
92 | /* Executes commands synchronously.
93 | * Pipes and multiple commands are fully supported.
94 | * Commands are written to a temporary bash script and executed.
95 | * std_out, std_err can be null. Output will be written to terminal if null.
96 | * */
97 |
98 | string sh_file = save_bash_script_temp(script, null, true, supress_errors, run_as_admin);
99 |
100 | //log_debug("exec_script_sync(): %s".printf(sh_file));
101 |
102 | try {
103 | string[] argv = new string[1];
104 | argv[0] = sh_file;
105 |
106 | string[] env = Environ.get();
107 |
108 | int exit_code;
109 |
110 | if (print_to_terminal){
111 |
112 | Process.spawn_sync (
113 | file_parent(sh_file), //working dir
114 | argv, //argv
115 | env, //environment
116 | SpawnFlags.SEARCH_PATH,
117 | null, // child_setup
118 | null,
119 | null,
120 | out exit_code
121 | );
122 | }
123 | else{
124 |
125 | Process.spawn_sync (
126 | file_parent(sh_file), //working dir
127 | argv, //argv
128 | env, //environment
129 | SpawnFlags.SEARCH_PATH,
130 | null, // child_setup
131 | out std_out,
132 | out std_err,
133 | out exit_code
134 | );
135 | }
136 |
137 | // Process.spawn_sync() exit_code is not reliable when executed as script
138 |
139 | string status_file = path_combine(file_parent(sh_file), "status");
140 | if (file_exists(status_file)){
141 | exit_code = int.parse(file_read(status_file));
142 | }
143 |
144 | //log_debug("exec_script_sync(): exit_code: %d".printf(exit_code));
145 |
146 | if (cleanup_tmp){
147 | file_delete(sh_file);
148 | }
149 |
150 | return exit_code;
151 | }
152 | catch (Error e){
153 | if (!supress_errors){
154 | log_error (e.message);
155 | }
156 | return -1;
157 | }
158 | }
159 |
160 | public int exec_script_async (string script, bool admin_mode = false){
161 |
162 | /* Executes commands synchronously.
163 | * Pipes and multiple commands are fully supported.
164 | * Commands are written to a temporary bash script and executed.
165 | * Return value indicates if script was started successfully.
166 | * */
167 |
168 | try {
169 |
170 | string sh_file = save_bash_script_temp (script, null, false, false, admin_mode);
171 |
172 | string[] argv = new string[1];
173 | argv[0] = sh_file;
174 |
175 | string[] env = Environ.get();
176 |
177 | Pid child_pid;
178 | Process.spawn_async_with_pipes(
179 | file_parent(sh_file), //working dir
180 | argv, //argv
181 | env, //environment
182 | SpawnFlags.SEARCH_PATH,
183 | null,
184 | out child_pid);
185 |
186 | return child_pid;
187 | }
188 | catch (Error e){
189 | log_error (e.message);
190 | return -1;
191 | }
192 | }
193 |
194 | public string? save_bash_script_temp (string commands, string? script_path = null,
195 | bool force_locale = true, bool supress_errors = false, bool admin_mode = false){
196 |
197 | string sh_path = script_path;
198 |
199 | /* Creates a temporary bash script with given commands
200 | * Returns the script file path */
201 |
202 | string sh = "";
203 | sh += "#!/bin/bash\n";
204 | sh += "\n";
205 | if (force_locale){
206 | sh += "LANG=C\n";
207 | }
208 | sh += "\n";
209 | sh += "%s\n".printf(commands);
210 | sh += "\n\nexitCode=$?\n";
211 | sh += "echo ${exitCode} > ${exitCode}\n";
212 | sh += "echo ${exitCode} > status\n";
213 | sh += "exit ${exitCode}\n";
214 |
215 | if ((sh_path == null) || (sh_path.length == 0)){
216 | sh_path = get_temp_file_path() + ".sh";
217 | }
218 |
219 | // write file
220 | file_write(sh_path, sh);
221 |
222 | // set execute permission
223 | chmod (sh_path, "a+x");
224 |
225 | if (admin_mode){
226 |
227 | sh = "";
228 | sh += "#!/bin/bash\n";
229 | sh += "pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY";
230 | sh += " '%s'\n".printf(escape_single_quote(sh_path));
231 | sh += "if [ -f status ]; then exit $(cat status); else exit 0; fi\n";
232 |
233 | string sh_path_admin = GLib.Path.build_filename(file_parent(sh_path),"script-admin.sh");
234 |
235 | // do not use script wrapper, write script file manually
236 | //save_bash_script_temp(script_admin, sh_file_admin, true, supress_errors);
237 |
238 | // write file
239 | file_write(sh_path_admin, sh);
240 |
241 | // set execute permission
242 | chmod(sh_path_admin, "a+x");
243 |
244 | return sh_path_admin;
245 | }
246 | else{
247 | return sh_path;
248 | }
249 | }
250 |
251 | public string get_temp_file_path(bool with_temp_folder = true){
252 |
253 | /* Generates temporary file path */
254 |
255 | string txt = "%s/%s".printf(TEMP_DIR, timestamp_numeric() + (new Rand()).next_int().to_string());
256 |
257 | if (with_temp_folder){
258 | dir_create(txt);
259 | txt += "/%s".printf(timestamp_numeric() + (new Rand()).next_int().to_string());
260 | }
261 |
262 | return txt;
263 | }
264 |
265 | public void exec_process_new_session(string command){
266 | exec_script_async("setsid %s &".printf(command));
267 | }
268 |
269 | // find process -------------------------------
270 |
271 | public string get_cmd_path (string cmd_tool){
272 |
273 | /* Returns the full path to a command */
274 |
275 | try {
276 | int exitCode;
277 | string stdout, stderr;
278 | Process.spawn_command_line_sync("which " + cmd_tool, out stdout, out stderr, out exitCode);
279 | stdout = stdout.strip().replace("\n","");
280 | return stdout;
281 | }
282 | catch (Error e){
283 | log_error (e.message);
284 | return "";
285 | }
286 | }
287 |
288 | public bool cmd_exists(string cmd_tool){
289 | string path = get_cmd_path (cmd_tool);
290 | if ((path == null) || (path.length == 0)){
291 | return false;
292 | }
293 | else{
294 | return true;
295 | }
296 | }
297 |
298 | private bool cmd_exists_in_path(string basepath, string cmd){
299 |
300 | string path = path_combine(basepath, "/bin/%s".printf(cmd));
301 |
302 | if (file_exists(path)){ return true; }
303 |
304 | path = path_combine(basepath, "/usr/bin/%s".printf(cmd));
305 |
306 | if (file_exists(path)){ return true; }
307 |
308 | return false;
309 | }
310 | }
311 |
--------------------------------------------------------------------------------
/src/Utility/Console/TeeJee.System.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * TeeJee.System.vala
4 | *
5 | * Copyright 2017 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | namespace TeeJee.System{
26 |
27 | using TeeJee.ProcessHelper;
28 | using TeeJee.Logging;
29 | using TeeJee.Misc;
30 | using TeeJee.FileSystem;
31 |
32 | // user ---------------------------------------------------
33 |
34 | public bool user_is_admin(){
35 |
36 | return (get_user_id_effective() == 0);
37 | }
38 |
39 | public int get_user_id(){
40 |
41 | // returns actual user id of current user (even for applications executed with sudo and pkexec)
42 |
43 | string pkexec_uid = GLib.Environment.get_variable("PKEXEC_UID");
44 |
45 | if (pkexec_uid != null){
46 | return int.parse(pkexec_uid);
47 | }
48 |
49 | string sudo_user = GLib.Environment.get_variable("SUDO_USER");
50 |
51 | if (sudo_user != null){
52 | return get_user_id_from_username(sudo_user);
53 | }
54 |
55 | return get_user_id_effective(); // normal user
56 | }
57 |
58 | public int get_user_id_effective(){
59 |
60 | // returns effective user id (0 for applications executed with sudo and pkexec)
61 |
62 | int uid = -1;
63 | string cmd = "id -u";
64 | string std_out, std_err;
65 | exec_sync(cmd, out std_out, out std_err);
66 | if ((std_out != null) && (std_out.length > 0)){
67 | uid = int.parse(std_out);
68 | }
69 |
70 | return uid;
71 | }
72 |
73 | public string get_username(){
74 |
75 | // returns actual username of current user (even for applications executed with sudo and pkexec)
76 |
77 | return get_username_from_uid(get_user_id());
78 | }
79 |
80 | public string get_username_effective(){
81 |
82 | // returns effective user id ('root' for applications executed with sudo and pkexec)
83 |
84 | return get_username_from_uid(get_user_id_effective());
85 | }
86 |
87 | public int get_user_id_from_username(string username){
88 |
89 | int user_id = -1;
90 |
91 | foreach(var line in file_read("/etc/passwd").split("\n")){
92 | var arr = line.split(":");
93 | if (arr.length < 3) { continue; }
94 | if (arr[0] == username){
95 | user_id = int.parse(arr[2]);
96 | break;
97 | }
98 | }
99 |
100 | return user_id;
101 | }
102 |
103 | public string get_username_from_uid(int user_id){
104 |
105 | string username = "";
106 |
107 | foreach(var line in file_read("/etc/passwd").split("\n")){
108 | var arr = line.split(":");
109 | if (arr.length < 3) { continue; }
110 | if (int.parse(arr[2]) == user_id){
111 | username = arr[0];
112 | break;
113 | }
114 | }
115 |
116 | return username;
117 | }
118 |
119 | public string get_user_home(string username = get_username()){
120 |
121 | string userhome = "";
122 |
123 | foreach(var line in file_read("/etc/passwd").split("\n")){
124 | var arr = line.split(":");
125 | if (arr.length < 6) { continue; }
126 | if (arr[0] == username){
127 | userhome = arr[5];
128 | break;
129 | }
130 | }
131 |
132 | return userhome;
133 | }
134 |
135 | public string get_user_home_effective(){
136 | return get_user_home(get_username_effective());
137 | }
138 |
139 | // application -----------------------------------------------
140 |
141 | public string get_app_path(){
142 |
143 | /* Get path of current process */
144 |
145 | try{
146 | return GLib.FileUtils.read_link ("/proc/self/exe");
147 | }
148 | catch (Error e){
149 | log_error (e.message);
150 | return "";
151 | }
152 | }
153 |
154 | public string get_app_dir(){
155 |
156 | /* Get parent directory of current process */
157 |
158 | try{
159 | return (File.new_for_path (GLib.FileUtils.read_link ("/proc/self/exe"))).get_parent ().get_path ();
160 | }
161 | catch (Error e){
162 | log_error (e.message);
163 | return "";
164 | }
165 | }
166 |
167 | // system ------------------------------------
168 |
169 | // dep: cat TODO: rewrite
170 | public double get_system_uptime_seconds(){
171 |
172 | /* Returns the system up-time in seconds */
173 |
174 | string cmd = "";
175 | string std_out;
176 | string std_err;
177 | int ret_val;
178 |
179 | try{
180 | cmd = "cat /proc/uptime";
181 | Process.spawn_command_line_sync(cmd, out std_out, out std_err, out ret_val);
182 | string uptime = std_out.split(" ")[0];
183 | double secs = double.parse(uptime);
184 | return secs;
185 | }
186 | catch(Error e){
187 | log_error (e.message);
188 | return 0;
189 | }
190 | }
191 |
192 | public Gee.ArrayList list_dir_names(string path){
193 | var list = new Gee.ArrayList();
194 |
195 | try
196 | {
197 | File f_home = File.new_for_path (path);
198 | FileEnumerator enumerator = f_home.enumerate_children ("%s".printf(FileAttribute.STANDARD_NAME), 0);
199 | FileInfo file;
200 | while ((file = enumerator.next_file ()) != null) {
201 | string name = file.get_name();
202 | //string item = path + "/" + name;
203 | list.add(name);
204 | }
205 | }
206 | catch (Error e) {
207 | log_error (e.message);
208 | }
209 |
210 | //sort the list
211 | CompareDataFunc entry_compare = (a, b) => {
212 | return strcmp(a,b);
213 | };
214 | list.sort((owned) entry_compare);
215 |
216 | return list;
217 | }
218 |
219 | // internet helpers ----------------------
220 |
221 | public bool check_internet_connectivity(){
222 |
223 | bool connected = false;
224 | connected = check_internet_connectivity_test();
225 |
226 | if (connected){
227 | return connected;
228 | }
229 |
230 | if (!connected){
231 | log_error(_("Internet connection is not active"));
232 | }
233 |
234 | return connected;
235 | }
236 |
237 | public bool check_internet_connectivity_test(){
238 |
239 | string std_err, std_out;
240 |
241 | string cmd = "url='http://google.com'\n";
242 |
243 | cmd += "httpCode=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $url)";
244 |
245 | cmd += "test $httpCode -lt 400 && test $httpCode -gt 0\n";
246 |
247 | cmd += "exit $?";
248 |
249 | int status = exec_script_sync(cmd, out std_out, out std_err, false);
250 |
251 | return (status == 0);
252 | }
253 |
254 | public bool check_internet_connectivity_test1(){
255 |
256 | // Deprecated: 'ping' may be disabled on enterprise systems
257 |
258 | string std_err, std_out;
259 |
260 | string cmd = "ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3`\n";
261 |
262 | cmd += "exit $?";
263 |
264 | int status = exec_script_sync(cmd, out std_out, out std_err, false);
265 |
266 | return (status == 0);
267 | }
268 |
269 | public bool check_internet_connectivity_test2(){
270 |
271 | // Deprecated: 'ping' may be disabled on enterprise systems
272 |
273 | string std_err, std_out;
274 |
275 | string cmd = "ping -q -w 1 -c 1 google.com\n";
276 |
277 | cmd += "exit $?";
278 |
279 | int status = exec_script_sync(cmd, out std_out, out std_err, false);
280 |
281 | return (status == 0);
282 | }
283 |
284 | public bool shutdown (){
285 |
286 | /* Shutdown the system immediately */
287 |
288 | try{
289 | string[] argv = { "shutdown", "-h", "now" };
290 | Pid procId;
291 | Process.spawn_async(null, argv, null, SpawnFlags.SEARCH_PATH, null, out procId);
292 | return true;
293 | }
294 | catch (Error e) {
295 | log_error (e.message);
296 | return false;
297 | }
298 | }
299 |
300 | public bool command_exists(string command){
301 | string path = get_cmd_path(command);
302 | return ((path != null) && (path.length > 0));
303 | }
304 |
305 | // open -----------------------------
306 |
307 | public bool xdg_open (string file, string user = ""){
308 |
309 | string path = get_cmd_path ("xdg-open");
310 |
311 | if ((path != null) && (path != "")){
312 |
313 | string cmd = "xdg-open '%s'".printf(escape_single_quote(file));
314 |
315 | if (user.length > 0){
316 | cmd = "pkexec --user %s env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY ".printf(user) + cmd;
317 | }
318 |
319 | log_debug(cmd);
320 |
321 | int status = exec_script_async(cmd);
322 |
323 | return (status == 0);
324 | }
325 |
326 | return false;
327 | }
328 |
329 | public bool using_efi_boot(){
330 |
331 | /* Returns true if the system was booted in EFI mode
332 | * and false for BIOS mode */
333 |
334 | return dir_exists("/sys/firmware/efi");
335 | }
336 |
337 | public void open_terminal_window(
338 | string terminal_emulator,
339 | string working_dir,
340 | string script_file_to_execute,
341 | bool run_as_admin){
342 |
343 | string cmd = "";
344 | if (run_as_admin){
345 | cmd += "pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY ";
346 | }
347 |
348 | string term = terminal_emulator;
349 | if (!command_exists(term)){
350 | term = "gnome-terminal";
351 | if (!command_exists(term)){
352 | term = "xfce4-terminal";
353 | }
354 | }
355 |
356 | cmd += term;
357 |
358 | switch (term){
359 | case "gnome-terminal":
360 | case "xfce4-terminal":
361 | if (working_dir.length > 0){
362 | cmd += " --working-directory='%s'".printf(escape_single_quote(working_dir));
363 | }
364 | if (script_file_to_execute.length > 0){
365 | cmd += " -e '%s\n; echo Press ENTER to exit... ; read dummy;'".printf(escape_single_quote(script_file_to_execute));
366 | }
367 | break;
368 | }
369 |
370 | log_debug(cmd);
371 | exec_script_async(cmd);
372 | }
373 |
374 | // timers --------------------------------------------------
375 |
376 | public GLib.Timer timer_start(){
377 | var timer = new GLib.Timer();
378 | timer.start();
379 | return timer;
380 | }
381 |
382 | public void timer_restart(GLib.Timer timer){
383 | timer.reset();
384 | timer.start();
385 | }
386 |
387 | public ulong timer_elapsed(GLib.Timer timer, bool stop = true){
388 | ulong microseconds;
389 | double seconds;
390 | seconds = timer.elapsed (out microseconds);
391 | if (stop){
392 | timer.stop();
393 | }
394 | return (ulong)((seconds * 1000 ) + (microseconds / 1000));
395 | }
396 |
397 | public void sleep(int milliseconds){
398 | Thread.usleep ((ulong) milliseconds * 1000);
399 | }
400 |
401 | public string timer_elapsed_string(GLib.Timer timer, bool stop = true){
402 | ulong microseconds;
403 | double seconds;
404 | seconds = timer.elapsed (out microseconds);
405 | if (stop){
406 | timer.stop();
407 | }
408 | return "%.0f ms".printf((seconds * 1000 ) + microseconds/1000);
409 | }
410 |
411 | public void timer_elapsed_print(GLib.Timer timer, bool stop = true){
412 | ulong microseconds;
413 | double seconds;
414 | seconds = timer.elapsed (out microseconds);
415 | if (stop){
416 | timer.stop();
417 | }
418 | log_msg("%s %lu\n".printf(seconds.to_string(), microseconds));
419 | }
420 |
421 |
422 | public void set_numeric_locale(string type){
423 | Intl.setlocale(GLib.LocaleCategory.NUMERIC, type);
424 | Intl.setlocale(GLib.LocaleCategory.COLLATE, type);
425 | Intl.setlocale(GLib.LocaleCategory.TIME, type);
426 | }
427 | }
428 |
--------------------------------------------------------------------------------
/src/Utility/TeeJee.JsonHelper.vala:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * TeeJee.JsonHelper.vala
4 | *
5 | * Copyright 2017 Tony George
6 | *
7 | * This program is free software; you can redistribute it and/or modify
8 | * it under the terms of the GNU General Public License as published by
9 | * the Free Software Foundation; either version 2 of the License, or
10 | * (at your option) any later version.
11 | *
12 | * This program is distributed in the hope that it will be useful,
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | * GNU General Public License for more details.
16 | *
17 | * You should have received a copy of the GNU General Public License
18 | * along with this program; if not, write to the Free Software
19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20 | * MA 02110-1301, USA.
21 | *
22 | *
23 | */
24 |
25 | using Json;
26 |
27 | namespace TeeJee.JsonHelper{
28 |
29 | using TeeJee.Logging;
30 |
31 | /* Convenience functions for reading and writing JSON files */
32 |
33 | public string json_get_string(Json.Object jobj, string member, string def_value){
34 | if (jobj.has_member(member)){
35 | return jobj.get_string_member(member);
36 | }
37 | else{
38 | log_debug ("Member not found in JSON object: " + member);
39 | return def_value;
40 | }
41 | }
42 |
43 | public double json_get_double(Json.Object jobj, string member, double def_value){
44 | var text = json_get_string(jobj, member, def_value.to_string());
45 | double double_value;
46 | if (double.try_parse(text, out double_value)){
47 | return double_value;
48 | }
49 | else{
50 | return def_value;
51 | }
52 | }
53 |
54 | public bool json_get_bool(Json.Object jobj, string member, bool def_value){
55 | if (jobj.has_member(member)){
56 | return bool.parse(jobj.get_string_member(member));
57 | }
58 | else{
59 | log_debug ("Member not found in JSON object: " + member);
60 | return def_value;
61 | }
62 | }
63 |
64 | public int json_get_int(Json.Object jobj, string member, int def_value){
65 | if (jobj.has_member(member)){
66 | return int.parse(jobj.get_string_member(member));
67 | }
68 | else{
69 | log_debug ("Member not found in JSON object: " + member);
70 | return def_value;
71 | }
72 | }
73 |
74 | public int64 json_get_int64(Json.Object jobj, string member, int64 def_value){
75 | if (jobj.has_member(member)){
76 | return int64.parse(jobj.get_string_member(member));
77 | }
78 | else{
79 | log_debug ("Member not found in JSON object: " + member);
80 | return def_value;
81 | }
82 | }
83 |
84 | public Gee.ArrayList json_get_array(
85 | Json.Object jobj,
86 | string member,
87 | Gee.ArrayList def_value){
88 |
89 | if (jobj.has_member(member)){
90 | var jarray = jobj.get_array_member(member);
91 | var list = new Gee.ArrayList();
92 | foreach(var node in jarray.get_elements()){
93 | list.add(node.get_string());
94 | }
95 | return list;
96 | }
97 | else{
98 | log_debug ("Member not found in JSON object: " + member);
99 | return def_value;
100 | }
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/makefile:
--------------------------------------------------------------------------------
1 | SHELL=/bin/bash
2 | CFLAGS=--std=c99
3 |
4 | prefix=/usr
5 | bindir=$(prefix)/bin
6 | sharedir=$(prefix)/share
7 | localedir=$(sharedir)/locale
8 | launcherdir=$(sharedir)/applications
9 | polkitdir=$(sharedir)/polkit-1/actions
10 | mandir=$(sharedir)/man
11 | man1dir=$(mandir)/man1
12 |
13 | app_name=groot
14 | app_fullname=Groot
15 |
16 | all: groot-console
17 |
18 | groot-console:
19 |
20 | valac -X -D'GETTEXT_PACKAGE="${app_name}"' --Xcc="-lm" --thread \
21 | *.vala Console/*.vala Utility/Console/*.vala \
22 | -o ${app_name} \
23 | --pkg glib-2.0 \
24 | --pkg gio-unix-2.0 \
25 | --pkg posix \
26 | --pkg gee-0.8
27 |
28 | clean:
29 | rm -rfv ../release/{source,i386,amd64,armel,armhf}
30 | rm -rfv ../release/*.{run,deb}
31 | rm -rfv *.c *.o *.mo
32 | rm -fv ${app_name}
33 |
34 | install:
35 |
36 | #dirs
37 | mkdir -p "$(DESTDIR)$(bindir)"
38 | mkdir -p "$(DESTDIR)$(sharedir)"
39 | mkdir -p "$(DESTDIR)$(mandir)"
40 | mkdir -p "$(DESTDIR)$(man1dir)"
41 | mkdir -p "$(DESTDIR)$(launcherdir)"
42 | mkdir -p "$(DESTDIR)$(polkitdir)"
43 |
44 | #binary
45 | install -m 0755 ${app_name} "$(DESTDIR)$(bindir)"
46 |
47 | #polkit policy file
48 | install -m 0644 ./share/polkit-1/actions/in.teejeetech.pkexec.groot.policy "$(DESTDIR)$(polkitdir)"
49 |
50 | uninstall:
51 |
52 | #binary
53 | rm -f "$(DESTDIR)$(bindir)/${app_name}"
54 |
55 | #polkit policy file
56 | rm -f ./share/polkit-1/actions/in.teejeetech.pkexec.groot.policy "$(DESTDIR)$(polkitdir)"
57 |
58 |
59 |
--------------------------------------------------------------------------------
/src/share/polkit-1/actions/in.teejeetech.pkexec.groot.policy:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | Tony George
7 | https://github.com/teejee2008
8 |
9 | Authentication is required to run Groot as Administrator
10 | Run Groot as Administrator
11 | groot
12 |
13 | auth_admin_keep
14 | auth_admin_keep
15 | auth_admin_keep
16 |
17 | /usr/bin/groot
18 | false
19 |
20 |
21 |
--------------------------------------------------------------------------------