├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .travis.yaml ├── CONTRIBUTING ├── Cargo.toml ├── LICENSE.LGPL2.1 ├── README.md ├── build.rs ├── lxc-sys ├── Cargo.toml ├── build.rs ├── src │ └── lib.rs └── wrapper.h ├── rust-toolchain ├── rustfmt.toml └── src ├── bin └── rlxc.rs ├── cli ├── mod.rs └── rlxc.rs ├── lib.rs ├── lxc ├── attach_options.rs ├── log_options.rs └── mod.rs ├── macros.rs └── util ├── ffi.rs └── mod.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Install 20 | run: sudo add-apt-repository ppa:ubuntu-lxc/daily -y && sudo apt-get update -qq && sudo apt-get install -qq liblxc1 liblxc-dev 21 | - name: Build 22 | run: cargo build --verbose 23 | - name: Clippy 24 | run: cargo clippy 25 | - name: Run tests 26 | run: cargo test --verbose 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | /target 3 | **/*.rs.bk 4 | -------------------------------------------------------------------------------- /.travis.yaml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | before_script: 6 | - rustup component add clippy 7 | script: 8 | - cargo clippy 9 | - cargo test 10 | # etc. 11 | -------------------------------------------------------------------------------- /CONTRIBUTING: -------------------------------------------------------------------------------- 1 | Contributing to this project 2 | ---------------------------- 3 | 4 | This project accepts contributions. In order to contribute, you should 5 | pay attention to a few things: 6 | 7 | 1 - your code must follow the coding style rules 8 | 2 - the format of the submission must be GitHub pull requests 9 | 3 - your work must be signed 10 | 11 | 12 | Submitting Modifications: 13 | ------------------------- 14 | 15 | The contributions must be GitHub pull requests. 16 | 17 | Licensing for new files: 18 | ------------------------ 19 | 20 | Anything that ends up being part of the rlxc binary needs to be released 21 | under LGPLv2.1+ or a license compatible with it (though the latter will 22 | only be accepted for cases where the code originated elsewhere and was 23 | imported into rlxc). 24 | 25 | Language bindings for the libraries need to be released under LGPLv2.1+. 26 | 27 | When introducing a new file into the project, please make sure it has a 28 | SPDX header line making clear under which license it's being released under 29 | and if it doesn't match the criteria described above, please explain 30 | your decision. 31 | 32 | Developer Certificate of Origin: 33 | -------------------------------- 34 | 35 | To improve tracking of contributions to this project we will use a 36 | process modeled on the modified DCO 1.1 and use a "sign-off" procedure. 37 | 38 | The sign-off is a simple line at the end of the explanation for the 39 | patch, which certifies that you wrote it or otherwise have the right 40 | to pass it on as an open-source patch. The rules are pretty simple: 41 | if you can certify the below: 42 | 43 | By making a contribution to this project, I certify that: 44 | 45 | (a) The contribution was created in whole or in part by me and I have 46 | the right to submit it under the open source license indicated in 47 | the file; or 48 | 49 | (b) The contribution is based upon previous work that, to the best of 50 | my knowledge, is covered under an appropriate open source License 51 | and I have the right under that license to submit that work with 52 | modifications, whether created in whole or in part by me, under 53 | the same open source license (unless I am permitted to submit 54 | under a different license), as indicated in the file; or 55 | 56 | (c) The contribution was provided directly to me by some other person 57 | who certified (a), (b) or (c) and I have not modified it. 58 | 59 | (d) The contribution is made free of any other party's intellectual 60 | property claims or rights. 61 | 62 | (e) I understand and agree that this project and the contribution are 63 | public and that a record of the contribution (including all 64 | personal information I submit with it, including my sign-off) is 65 | maintained indefinitely and may be redistributed consistent with 66 | this project or the open source license(s) involved. 67 | 68 | 69 | then you just add a line saying 70 | 71 | Signed-off-by: Random J Developer 72 | 73 | You can do it by using option -s or --signoff when you commit 74 | 75 | git commit --signoff ... 76 | 77 | using your real name (sorry, no pseudonyms or anonymous contributions.) 78 | 79 | In addition we support the following DCOs which maintainers can use to indicate 80 | that a patch is acceptable: 81 | 82 | Acked-by: Random J Developer 83 | Reviewed-by: Random J Developer 84 | 85 | If you are contributing as a group who is implementing a feature together such 86 | that it cannot be reasonably attributed to a single developer please use: 87 | 88 | Co-developed-by: Random J Developer 1 89 | Co-developed-by: Random J Developer 2 90 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "rlxc" 4 | version = "0.1.0" 5 | authors = [ 6 | "Christian Brauner ", 7 | "Wolfgang Bumiller ", 8 | ] 9 | description = "A simple tool to interact with LXC containers" 10 | build = "build.rs" 11 | license-file = "LICENSE.LGPL2.1" 12 | repository = "https://github.com/brauner/rlxc" 13 | keywords = ["containers", "lxc", "linux"] 14 | 15 | [dependencies] 16 | anyhow = "1.0" 17 | lxc-sys = { path = "lxc-sys", version = ">=0.1.0" } 18 | libc = "0.2" 19 | clap = "2.33.3" 20 | xdg = "^2.1" 21 | prettytable-rs = "0.8.0" 22 | rayon = "1.1" 23 | 24 | [build-dependencies] 25 | clap = "2.32" 26 | 27 | [profile.dev] 28 | opt-level = 0 29 | debug = true 30 | -------------------------------------------------------------------------------- /LICENSE.LGPL2.1: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![LXD](https://linuxcontainers.org/static/img/containers.png)](https://linuxcontainers.org/lxd) 2 | # rlxc 3 | Simple side-project to implement a Rust binary using 4 | [LXC](https://github.com/lxc/lxc) to run containers. 5 | Currently covers: 6 | 7 | - `lxc-attach` -> `rlxc exec ...` 8 | * `lxc-start` -> `rlxc start ` 9 | - `lxc-execute -> rlxc start [command]` 10 | - `lxc-stop` -> `rlxc stop` 11 | - `lxc-ls` -> `rlxc list` 12 | - `lxc-console` -> `rlxc login ` 13 | 14 | as well as: 15 | 16 | - `rlxc help` 17 | - `rlxc version` 18 | 19 | # LXC 20 | For information about LXC see [here](https://github.com/lxc/lxc). 21 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | 3 | use clap::Shell; 4 | 5 | include!("src/cli/rlxc.rs"); 6 | 7 | fn main() { 8 | let outdir = match env::var_os("OUT_DIR") { 9 | None => return, 10 | Some(outdir) => outdir, 11 | }; 12 | 13 | let mut app = build_cli(); 14 | app.gen_completions("rlxc", Shell::Bash, outdir); 15 | //app.gen_completions("rlxc", Shell::Zsh, outdir); 16 | } 17 | -------------------------------------------------------------------------------- /lxc-sys/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "lxc-sys" 4 | version = "0.1.0" 5 | authors = [ 6 | "Christian Brauner ", 7 | "Wolfgang Bumiller ", 8 | ] 9 | license-file = "LICENSE.LGPL2.1" 10 | repository = "https://github.com/brauner/rlxc" 11 | keywords = ["containers", "lxc", "linux"] 12 | 13 | [build-dependencies] 14 | bindgen = ">0.42.2" 15 | -------------------------------------------------------------------------------- /lxc-sys/build.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | extern crate bindgen; 4 | 5 | use std::env; 6 | use std::path::PathBuf; 7 | 8 | fn main() { 9 | // Tell cargo to tell rustc to link the system liblxc 10 | // shared library. 11 | println!("cargo:rustc-link-lib=lxc"); 12 | 13 | // The bindgen::Builder is the main entry point 14 | // to bindgen, and lets you build up options for 15 | // the resulting bindings. 16 | let bindings = bindgen::Builder::default() 17 | .allowlist_function("list_all_containers") 18 | .allowlist_function("lxc_container_new") 19 | .allowlist_function("lxc_container_put") 20 | .allowlist_function("lxc_get_version") 21 | .allowlist_function("lxc_get_global_config_item") 22 | .allowlist_function("lxc_log_init") 23 | .allowlist_type("lxc_container") 24 | .allowlist_type("lxc_log") 25 | .allowlist_var("LXC_ATTACH_TERMINAL") 26 | .allowlist_var("LXC_ATTACH_DEFAULT") 27 | // The input header we would like to generate 28 | // bindings for. 29 | .header("wrapper.h") 30 | // Finish the builder and generate the bindings. 31 | .generate() 32 | // Unwrap the Result and panic on failure. 33 | .expect("Unable to generate bindings"); 34 | 35 | // Write the bindings to the $OUT_DIR/bindings.rs file. 36 | let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); 37 | bindings 38 | .write_to_file(out_path.join("bindings.rs")) 39 | .expect("Couldn't write bindings!"); 40 | } 41 | -------------------------------------------------------------------------------- /lxc-sys/src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | #![allow(non_upper_case_globals)] 4 | #![allow(non_camel_case_types)] 5 | #![allow(non_snake_case)] 6 | 7 | include!(concat!(env!("OUT_DIR"), "/bindings.rs")); 8 | -------------------------------------------------------------------------------- /lxc-sys/wrapper.h: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | #include 4 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | stable 2 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2018" 2 | max_width = 80 3 | newline_style = "Unix" 4 | format_strings = true 5 | condense_wildcard_suffixes = true 6 | #struct_field_align_threshold = 32 7 | #enum_discrim_align_threshold = 32 8 | wrap_comments = true 9 | #report_todo = "Always" 10 | #report_fixme = "Always" 11 | #license_template_path 12 | -------------------------------------------------------------------------------- /src/bin/rlxc.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | use std::os::unix::process::ExitStatusExt; 4 | use std::process::{exit, ExitStatus}; 5 | 6 | use anyhow::{bail, Error}; 7 | 8 | use rlxc::cli::rlxc as cli; 9 | use rlxc::lxc::{self, Lxc}; 10 | #[macro_use] 11 | extern crate prettytable; 12 | use prettytable::Table; 13 | use rayon::prelude::*; 14 | 15 | fn may_control_container(c: &Lxc) -> Result<(), Error> { 16 | if let Err(err) = c.may_control() { 17 | eprintln!("{}", err); 18 | } 19 | Ok(()) 20 | } 21 | 22 | fn initialize_log( 23 | subcommand: &'static str, 24 | args: &clap::ArgMatches, 25 | ) -> Result<(), Error> { 26 | let logfile = args 27 | .value_of_os("logfile") 28 | .unwrap_or_else(|| "none".as_ref()); 29 | if !logfile.is_empty() { 30 | let mut options = lxc::LogOptions::new(); 31 | options = options.set_log_prefix(&format!( 32 | "{} {}", 33 | clap::crate_name!(), 34 | subcommand 35 | ))?; 36 | options = options.set_log_file(logfile)?; 37 | options = options.set_log_level( 38 | args.value_of_os("loglevel") 39 | .unwrap_or_else(|| "ERROR".as_ref()), 40 | )?; 41 | lxc::set_log(&mut options)?; 42 | } 43 | Ok(()) 44 | } 45 | 46 | fn cmd_start(args: &clap::ArgMatches) -> Result<(), Error> { 47 | let sname = args.value_of_os("name").unwrap(); 48 | let spath = args 49 | .value_of_os("path") 50 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 51 | if spath.is_empty() { 52 | bail!("Missing required argument: 'path' and no default path set"); 53 | } 54 | 55 | let vals: Vec<_> = match args.values_of_os("command") { 56 | None => Vec::new(), 57 | Some(v) => v.collect(), 58 | }; 59 | 60 | let container = Lxc::new(sname, spath)?; 61 | 62 | may_control_container(&container)?; 63 | 64 | if container.is_running() { 65 | bail!("Container already running"); 66 | } 67 | 68 | if args.is_present("terminal") { 69 | container.daemonize(false); 70 | } 71 | 72 | if !vals.is_empty() { 73 | return container.start(true, vals); 74 | } 75 | 76 | container.start(false, vals) 77 | } 78 | 79 | fn cmd_stop(args: &clap::ArgMatches) -> Result<(), Error> { 80 | let sname = args.value_of_os("name").unwrap_or_else(|| "".as_ref()); 81 | 82 | let spath = args 83 | .value_of_os("path") 84 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 85 | if spath.is_empty() { 86 | bail!("Missing required argument: 'path' and no default path set"); 87 | } 88 | 89 | let all = args.is_present("all"); 90 | 91 | if !all && sname.is_empty() { 92 | bail!("Either a single container or all containers must be stopped"); 93 | } 94 | 95 | let force = args.is_present("force"); 96 | let timeout = match args.value_of("timeout") { 97 | None => None, 98 | Some(value) => match value.parse::() { 99 | Ok(-1) => None, 100 | Ok(n) => { 101 | if n < 0 { 102 | bail!("Invalid timeout (must be -1, 0 or positive)"); 103 | } 104 | Some(std::time::Duration::from_secs(n as u64)) 105 | } 106 | Err(e) => bail!("Invalid timeout: {:?}", e), 107 | }, 108 | }; 109 | 110 | let stop_function = |name| { 111 | let container = Lxc::new(name, spath)?; 112 | 113 | may_control_container(&container)?; 114 | 115 | if !container.is_running() { 116 | println!("Container {:?} not running", name); 117 | return Ok(()); 118 | } 119 | 120 | if force { 121 | return container.stop(); 122 | } 123 | 124 | container.shutdown(timeout) 125 | }; 126 | 127 | if !all { 128 | return stop_function(sname); 129 | } 130 | 131 | let bulk: Vec = lxc::list_all_containers(spath)?.collect(); 132 | let errors: Vec<_> = bulk 133 | .par_iter() 134 | .map(|name| stop_function(name.as_ref())) 135 | .filter_map(Result::err) 136 | .collect(); 137 | 138 | if !errors.is_empty() { 139 | bail!("Failed to stop some containers"); 140 | } 141 | Ok(()) 142 | } 143 | 144 | fn cmd_exec(args: &clap::ArgMatches) -> i32 { 145 | let sname = args.value_of_os("name").unwrap(); 146 | let spath = args 147 | .value_of_os("path") 148 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 149 | if spath.is_empty() { 150 | eprintln!("Missing required argument: 'path' and no default path set"); 151 | return 1; 152 | } 153 | 154 | let vals: Vec<_> = args.values_of_os("command").unwrap().collect(); 155 | 156 | let env: Vec<_> = args 157 | .values_of_os("env") 158 | .map_or_else(Vec::new, |matches| matches.collect()); 159 | 160 | if let Err(err) = initialize_log("exec", args) { 161 | eprintln!("error: {}", err); 162 | return 1; 163 | }; 164 | 165 | let container = match Lxc::new(sname, spath) { 166 | Ok(c) => c, 167 | Err(_) => return 1, 168 | }; 169 | 170 | if may_control_container(&container).is_err() { 171 | return 1; 172 | } 173 | 174 | if !container.is_running() { 175 | eprintln!("Container not running"); 176 | return 1; 177 | } 178 | 179 | let mut options = lxc::AttachOptions::new(); 180 | for e in env { 181 | let s = match e.to_str() { 182 | Some(v) => v, 183 | None => { 184 | eprintln!("Failed to convert to UTF-8 string"); 185 | return 1; 186 | } 187 | }; 188 | 189 | let res: Vec<_> = s.splitn(2, '=').collect(); 190 | if res.len() != 2 { 191 | eprintln!("Invalid environment variable"); 192 | return 1; 193 | } 194 | options = match options.set_env_var(res[0], res[1]) { 195 | Ok(opt) => opt, 196 | Err(_) => { 197 | eprintln!("Failed to set environment variable"); 198 | return 1; 199 | } 200 | } 201 | } 202 | 203 | let uid = match args.value_of("user") { 204 | None => None, 205 | Some(value) => match value.parse::() { 206 | Ok(v) => Some(v), 207 | Err(err) => { 208 | eprintln!("{} - invalid user id specified", err); 209 | return 1; 210 | } 211 | }, 212 | }; 213 | options = options.uid(uid); 214 | 215 | let gid = match args.value_of("group") { 216 | None => None, 217 | Some(value) => match value.parse::() { 218 | Ok(v) => Some(v), 219 | Err(err) => { 220 | eprintln!("{} - invalid group id specified", err); 221 | return 1; 222 | } 223 | }, 224 | }; 225 | options = options.gid(gid); 226 | 227 | let ret = container.attach_run_wait(&mut options, vals[0], vals); 228 | let status = ExitStatus::from_raw(ret); 229 | if status.success() { 230 | return 0; 231 | } 232 | 233 | match status.code() { 234 | Some(code) => code, 235 | None => match status.signal() { 236 | Some(signal) => 128 + signal, 237 | None => -1, 238 | }, 239 | } 240 | } 241 | 242 | fn cmd_freeze(args: &clap::ArgMatches) -> Result<(), Error> { 243 | let sname = args.value_of_os("name").unwrap_or_else(|| "".as_ref()); 244 | 245 | let spath = args 246 | .value_of_os("path") 247 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 248 | if spath.is_empty() { 249 | bail!("Missing required argument: 'path' and no default path set"); 250 | } 251 | 252 | let all = args.is_present("all"); 253 | 254 | if !all && sname.is_empty() { 255 | bail!("Either a single container or all containers must be stopped"); 256 | } 257 | 258 | let freeze_function = |name| { 259 | let container = Lxc::new(name, spath)?; 260 | 261 | may_control_container(&container)?; 262 | 263 | if !container.is_running() { 264 | println!("Container {:?} not running", name); 265 | return Ok(()); 266 | } 267 | 268 | container.freeze() 269 | }; 270 | 271 | if !all { 272 | return freeze_function(sname); 273 | } 274 | 275 | let bulk: Vec = lxc::list_all_containers(spath)?.collect(); 276 | let errors: Vec<_> = bulk 277 | .par_iter() 278 | .map(|name| freeze_function(name.as_ref())) 279 | .filter_map(Result::err) 280 | .collect(); 281 | 282 | if !errors.is_empty() { 283 | bail!("Failed to freeze some containers"); 284 | } 285 | Ok(()) 286 | } 287 | 288 | fn cmd_unfreeze(args: &clap::ArgMatches) -> Result<(), Error> { 289 | let sname = args.value_of_os("name").unwrap_or_else(|| "".as_ref()); 290 | 291 | let spath = args 292 | .value_of_os("path") 293 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 294 | if spath.is_empty() { 295 | bail!("Missing required argument: 'path' and no default path set"); 296 | } 297 | 298 | let all = args.is_present("all"); 299 | 300 | if !all && sname.is_empty() { 301 | bail!("Either a single container or all containers must be stopped"); 302 | } 303 | 304 | let unfreeze_function = |name| { 305 | let container = Lxc::new(name, spath)?; 306 | 307 | may_control_container(&container)?; 308 | 309 | if !container.is_running() { 310 | println!("Container {:?} not running", name); 311 | return Ok(()); 312 | } 313 | 314 | container.unfreeze() 315 | }; 316 | 317 | if !all { 318 | return unfreeze_function(sname); 319 | } 320 | 321 | let bulk: Vec = lxc::list_all_containers(spath)?.collect(); 322 | let errors: Vec<_> = bulk 323 | .par_iter() 324 | .map(|name| unfreeze_function(name.as_ref())) 325 | .filter_map(Result::err) 326 | .collect(); 327 | 328 | if !errors.is_empty() { 329 | bail!("Failed to unfreeze some containers"); 330 | } 331 | Ok(()) 332 | } 333 | 334 | fn cmd_list(args: &clap::ArgMatches) -> Result<(), Error> { 335 | let spath = args 336 | .value_of_os("path") 337 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 338 | if spath.is_empty() { 339 | bail!("Missing required argument: 'path' and no default path set"); 340 | } 341 | 342 | let mut table = Table::new(); 343 | table.add_row(row!["NAME", "STATE", "IPV4", "IPV6"]); 344 | for name in lxc::list_all_containers(spath)? { 345 | let container = Lxc::new(&name, spath)?; 346 | 347 | if may_control_container(&container).is_err() { 348 | continue; 349 | } 350 | 351 | let mut ipv4 = String::new(); 352 | let mut ipv6 = String::new(); 353 | if container.is_running() { 354 | let interfaces = container.get_interfaces(); 355 | for iface in interfaces { 356 | // skip the loopback device 357 | if iface == "lo" { 358 | continue; 359 | } 360 | 361 | for ipv4_addr in container.get_ipv4(&iface) { 362 | ipv4.push_str(&format!("{} ({})\n", ipv4_addr, iface)); 363 | } 364 | for ipv6_addr in container.get_ipv6(&iface) { 365 | ipv6.push_str(&format!("{} ({})\n", ipv6_addr, iface)); 366 | } 367 | } 368 | } 369 | 370 | table.add_row(row![&name, container.state(), ipv4, ipv6]); 371 | } 372 | table.printstd(); 373 | Ok(()) 374 | } 375 | 376 | fn cmd_login(args: &clap::ArgMatches) -> Result<(), Error> { 377 | let sname = args.value_of_os("name").unwrap(); 378 | let spath = args 379 | .value_of_os("path") 380 | .unwrap_or_else(|| lxc::get_default_path().as_ref()); 381 | if spath.is_empty() { 382 | bail!("Missing required argument: 'path' and no default path set"); 383 | } 384 | 385 | let container = Lxc::new(sname, spath)?; 386 | 387 | may_control_container(&container)?; 388 | 389 | if !container.is_running() { 390 | bail!("Container not running"); 391 | } 392 | 393 | container.terminal() 394 | } 395 | 396 | fn do_cmd( 397 | subcommand: &'static str, 398 | args: &clap::ArgMatches, 399 | func: fn(args: &clap::ArgMatches) -> Result<(), Error>, 400 | ) { 401 | if let Err(err) = initialize_log(subcommand, args) { 402 | eprintln!("error: {}", err); 403 | exit(1); 404 | }; 405 | 406 | if let Err(err) = func(args) { 407 | eprintln!("error: {}", err); 408 | exit(1); 409 | } 410 | } 411 | 412 | fn main() { 413 | let matches = cli::build_cli().get_matches(); 414 | 415 | if matches.subcommand_matches("version").is_some() { 416 | let version = lxc::get_version(); 417 | println!("driver_version: {}", version); 418 | return; 419 | } 420 | 421 | match matches.subcommand() { 422 | ("start", Some(args)) => do_cmd("start", args, cmd_start), 423 | ("stop", Some(args)) => do_cmd("stop", args, cmd_stop), 424 | ("list", Some(args)) => do_cmd("list", args, cmd_list), 425 | ("login", Some(args)) => do_cmd("login", args, cmd_login), 426 | ("freeze", Some(args)) => do_cmd("freeze", args, cmd_freeze), 427 | ("unfreeze", Some(args)) => do_cmd("unfreeze", args, cmd_unfreeze), 428 | ("exec", Some(args)) => exit(cmd_exec(args)), 429 | _ => { 430 | println!("{}", matches.usage()); 431 | exit(1); 432 | } 433 | } 434 | } 435 | -------------------------------------------------------------------------------- /src/cli/mod.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | pub mod rlxc; 4 | -------------------------------------------------------------------------------- /src/cli/rlxc.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | use clap::{App, Arg, SubCommand}; 4 | 5 | pub fn build_cli() -> App<'static, 'static> { 6 | App::new("rlxc") 7 | .version("0.1") 8 | .author(clap::crate_authors!("\n")) 9 | .about("Run LXC containers") 10 | .arg( 11 | Arg::with_name("path") 12 | .short("p") 13 | .long("path") 14 | .help("Base path for containers") 15 | .global(true) 16 | .takes_value(true) 17 | .required(false) 18 | ) 19 | .arg( 20 | Arg::with_name("logfile") 21 | .short("o") 22 | .long("output") 23 | .help("Logfile for the container") 24 | .global(true) 25 | .takes_value(true) 26 | .required(false) 27 | ) 28 | .arg( 29 | Arg::with_name("loglevel") 30 | .short("l") 31 | .long("level") 32 | .help("Loglevel for the container") 33 | .global(true) 34 | .takes_value(true) 35 | .required(false) 36 | ) 37 | .subcommand( 38 | SubCommand::with_name("login") 39 | .about("Attach to terminal of container") 40 | .arg( 41 | Arg::with_name("name") 42 | .index(1) 43 | .help("Name of the container") 44 | .required(true), 45 | ), 46 | ) 47 | .subcommand( 48 | SubCommand::with_name("exec") 49 | .about("Execute commands in a container") 50 | .arg( 51 | Arg::with_name("name") 52 | .index(1) 53 | .help("Name of the container") 54 | .required(true), 55 | ) 56 | .arg( 57 | Arg::with_name("env") 58 | .long("env") 59 | .help("Environment variable to set") 60 | .takes_value(true) 61 | .required(false) 62 | .multiple(true) 63 | .number_of_values(1), 64 | ) 65 | .arg( 66 | Arg::with_name("user") 67 | .short("u") 68 | .long("user") 69 | .help("User ID to run the command as (default 0)") 70 | .takes_value(true) 71 | .required(false) 72 | ) 73 | .arg( 74 | Arg::with_name("group") 75 | .short("g") 76 | .long("group") 77 | .help("Group ID to run the command as (default 0)") 78 | .takes_value(true) 79 | .required(false) 80 | ) 81 | .arg( 82 | Arg::with_name("command") 83 | .index(2) 84 | .help("Command to execute") 85 | .takes_value(true) 86 | .required(true) 87 | .multiple(true), 88 | ), 89 | ) 90 | .subcommand( 91 | SubCommand::with_name("start") 92 | .about("Run LXC containers") 93 | .arg( 94 | Arg::with_name("name") 95 | .index(1) 96 | .help("Name of the container") 97 | .required(true), 98 | ) 99 | .arg( 100 | Arg::with_name("terminal") 101 | .short("t") 102 | .long("terminal") 103 | .help("Immediately attach to the terminal for the container") 104 | .takes_value(false) 105 | .required(false), 106 | ) 107 | .arg( 108 | Arg::with_name("command") 109 | .index(2) 110 | .help("Command to execute") 111 | .takes_value(true) 112 | .required(false) 113 | .multiple(true), 114 | ), 115 | ) 116 | .subcommand( 117 | SubCommand::with_name("stop") 118 | .about("Stop LXC containers") 119 | .arg( 120 | Arg::with_name("name") 121 | .index(1) 122 | .help("Name of the container") 123 | .required(false), 124 | ) 125 | .arg( 126 | Arg::with_name("force") 127 | .short("f") 128 | .long("force") 129 | .help("SIGKILL the container") 130 | .takes_value(false) 131 | .required(false) 132 | .conflicts_with("timeout"), 133 | ) 134 | .arg( 135 | Arg::with_name("timeout") 136 | .short("t") 137 | .long("timeout") 138 | .help("timeout to wait for the container to stop") 139 | .takes_value(true) 140 | .required(false) 141 | .conflicts_with("force"), 142 | ) 143 | .arg( 144 | Arg::with_name("all") 145 | .long("all") 146 | .help("stop all containers") 147 | .takes_value(false) 148 | .required(false) 149 | .conflicts_with("name"), 150 | ), 151 | ) 152 | .subcommand(SubCommand::with_name("list").about("List LXC containers")) 153 | .subcommand( 154 | SubCommand::with_name("version") 155 | .about("Show runtime and client version") 156 | .arg( 157 | Arg::with_name("version") 158 | .index(1) 159 | .help("Show runtime and client version") 160 | .takes_value(false) 161 | .required(false), 162 | ), 163 | ) 164 | .subcommand( 165 | SubCommand::with_name("freeze") 166 | .about("Freeze LXC containers") 167 | .arg( 168 | Arg::with_name("name") 169 | .index(1) 170 | .help("Name of the container") 171 | .required(false), 172 | ) 173 | .arg( 174 | Arg::with_name("all") 175 | .long("all") 176 | .help("stop all containers") 177 | .takes_value(false) 178 | .required(false) 179 | .conflicts_with("name"), 180 | ), 181 | ) 182 | .subcommand( 183 | SubCommand::with_name("unfreeze") 184 | .about("Unfreeze LXC containers") 185 | .arg( 186 | Arg::with_name("name") 187 | .index(1) 188 | .help("Name of the container") 189 | .required(false), 190 | ) 191 | .arg( 192 | Arg::with_name("all") 193 | .long("all") 194 | .help("stop all containers") 195 | .takes_value(false) 196 | .required(false) 197 | .conflicts_with("name"), 198 | ), 199 | ) 200 | } 201 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | #[macro_use] 4 | mod macros; 5 | 6 | #[doc(hidden)] 7 | pub mod cli; 8 | 9 | pub mod lxc; 10 | pub mod util; 11 | -------------------------------------------------------------------------------- /src/lxc/attach_options.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | use std::ffi::{CString, NulError, OsStr}; 4 | use std::os::raw::{c_char, c_int, c_long}; 5 | use std::os::unix::io::AsRawFd; 6 | use std::ptr; 7 | 8 | use crate::util::ffi::CStringVec; 9 | 10 | /// Type representing options for how to attach to a container. 11 | pub struct AttachOptions<'t, 'u, 'v, 'w> { 12 | raw: lxc_sys::lxc_attach_options_t, 13 | extra_env_vars: CStringVec, 14 | extra_keep_env: CStringVec, 15 | initial_cwd: Option, 16 | stdin: Option<&'t dyn AsRawFd>, 17 | stdout: Option<&'u dyn AsRawFd>, 18 | stderr: Option<&'v dyn AsRawFd>, 19 | log_file: Option<&'w dyn AsRawFd>, 20 | } 21 | 22 | impl AttachOptions<'static, 'static, 'static, 'static> { 23 | pub fn default() -> Self { 24 | Self::new() 25 | } 26 | pub fn new() -> Self { 27 | Self { 28 | raw: unsafe { std::mem::zeroed() }, 29 | extra_env_vars: CStringVec::new(), 30 | extra_keep_env: CStringVec::new(), 31 | initial_cwd: None, 32 | stdin: None, 33 | stdout: None, 34 | stderr: None, 35 | log_file: None, 36 | } 37 | .set_default() 38 | } 39 | } 40 | 41 | impl Default for AttachOptions<'static, 'static, 'static, 'static> { 42 | fn default() -> Self { 43 | Self::new() 44 | } 45 | } 46 | 47 | impl<'t, 'u, 'v, 'w> AttachOptions<'t, 'u, 'v, 'w> { 48 | #[inline(always)] 49 | fn set_default(mut self) -> Self { 50 | self.raw.attach_flags = lxc_sys::LXC_ATTACH_DEFAULT as c_int 51 | | lxc_sys::LXC_ATTACH_TERMINAL as c_int; 52 | self.raw.namespaces = -1; 53 | self.raw.personality = -1; 54 | self.raw.uid = !0; 55 | self.raw.gid = !0; 56 | self.raw.env_policy = 57 | lxc_sys::lxc_attach_env_policy_t_LXC_ATTACH_CLEAR_ENV; 58 | self 59 | } 60 | 61 | pub fn attach_flag(mut self, flag: c_int, on: bool) -> Self { 62 | if on { 63 | self.raw.attach_flags |= flag; 64 | } else { 65 | self.raw.attach_flags &= !flag; 66 | } 67 | self 68 | } 69 | 70 | pub fn move_to_cgroup(self, on: bool) -> Self { 71 | self.attach_flag(lxc_sys::LXC_ATTACH_MOVE_TO_CGROUP as _, on) 72 | } 73 | 74 | pub fn drop_capabilities(self, on: bool) -> Self { 75 | self.attach_flag(lxc_sys::LXC_ATTACH_DROP_CAPABILITIES as _, on) 76 | } 77 | 78 | pub fn set_personality(self, on: bool) -> Self { 79 | self.attach_flag(lxc_sys::LXC_ATTACH_SET_PERSONALITY as _, on) 80 | } 81 | 82 | pub fn lsm_exec(self, on: bool) -> Self { 83 | self.attach_flag(lxc_sys::LXC_ATTACH_LSM_EXEC as _, on) 84 | } 85 | 86 | pub fn remount_proc_sys(self, on: bool) -> Self { 87 | self.attach_flag(lxc_sys::LXC_ATTACH_REMOUNT_PROC_SYS as _, on) 88 | } 89 | 90 | pub fn lsm_now(self, on: bool) -> Self { 91 | self.attach_flag(lxc_sys::LXC_ATTACH_LSM_NOW as _, on) 92 | } 93 | 94 | pub fn no_new_privs(self, on: bool) -> Self { 95 | self.attach_flag(lxc_sys::LXC_ATTACH_NO_NEW_PRIVS as _, on) 96 | } 97 | 98 | pub fn terminal(self, on: bool) -> Self { 99 | self.attach_flag(lxc_sys::LXC_ATTACH_TERMINAL as _, on) 100 | } 101 | 102 | pub fn namespaces(mut self, v: c_int) -> Self { 103 | self.raw.namespaces = v; 104 | self 105 | } 106 | 107 | /// Pass `None` to autodetect (which is the default). 108 | pub fn personality(mut self, v: Option) -> Self { 109 | self.raw.personality = v.unwrap_or(!0); 110 | self 111 | } 112 | 113 | pub fn set_initial_cwd(mut self, v: T) -> Result 114 | where 115 | T: Into>, 116 | { 117 | self.initial_cwd = Some(CString::new(v)?); 118 | Ok(self) 119 | } 120 | 121 | pub fn unset_initial_cwd(mut self) -> Self { 122 | self.initial_cwd = None; 123 | self 124 | } 125 | 126 | /// Pass `None` for the default behavior which is using the init-uid for 127 | /// userns containers, or 0 if auto detection fails. 128 | pub fn uid(mut self, v: Option) -> Self { 129 | self.raw.uid = v.unwrap_or(!0); 130 | self 131 | } 132 | 133 | /// Pass `None` for the default behavior which is using the init-gid for 134 | /// userns containers, or 0 if auto detection fails. 135 | pub fn gid(mut self, v: Option) -> Self { 136 | self.raw.gid = v.unwrap_or(!0); 137 | self 138 | } 139 | 140 | pub fn keep_env(mut self) -> Self { 141 | self.raw.env_policy = 142 | lxc_sys::lxc_attach_env_policy_t_LXC_ATTACH_KEEP_ENV; 143 | self 144 | } 145 | 146 | pub fn clear_env(mut self) -> Self { 147 | self.raw.env_policy = 148 | lxc_sys::lxc_attach_env_policy_t_LXC_ATTACH_CLEAR_ENV; 149 | self 150 | } 151 | 152 | pub fn set_keep_env(self, on: bool) -> Self { 153 | if on { 154 | self.keep_env() 155 | } else { 156 | self.clear_env() 157 | } 158 | } 159 | 160 | pub fn stdin<'a, T: AsRawFd>( 161 | self, 162 | file: &'a T, 163 | ) -> AttachOptions<'a, 'u, 'v, 'w> { 164 | AttachOptions { 165 | stdin: Some(file), 166 | ..unsafe { std::mem::transmute(self) } 167 | } 168 | } 169 | 170 | pub fn stdout<'a, T: AsRawFd>( 171 | self, 172 | file: &'a T, 173 | ) -> AttachOptions<'t, 'a, 'v, 'w> { 174 | AttachOptions { 175 | stdout: Some(file), 176 | ..unsafe { std::mem::transmute(self) } 177 | } 178 | } 179 | 180 | pub fn stderr<'a, T: AsRawFd>( 181 | self, 182 | file: &'a T, 183 | ) -> AttachOptions<'t, 'u, 'a, 'w> { 184 | AttachOptions { 185 | stderr: Some(file), 186 | ..unsafe { std::mem::transmute(self) } 187 | } 188 | } 189 | 190 | pub fn log_file<'a, T: AsRawFd>( 191 | self, 192 | file: &'a T, 193 | ) -> AttachOptions<'t, 'u, 'v, 'a> { 194 | AttachOptions { 195 | log_file: Some(file), 196 | ..unsafe { std::mem::transmute(self) } 197 | } 198 | } 199 | 200 | pub fn set_env_var< 201 | S: std::fmt::Display + AsRef, 202 | T: std::fmt::Display + AsRef, 203 | >( 204 | mut self, 205 | name: S, 206 | value: T, 207 | ) -> Result { 208 | self.extra_env_vars 209 | .push(CString::new(format!("{}={}", name, value))?); 210 | Ok(self) 211 | } 212 | 213 | pub fn keep_env_var(mut self, name: &str) -> Result { 214 | self.extra_keep_env.push(CString::new(name)?); 215 | Ok(self) 216 | } 217 | 218 | fn finish(&mut self) { 219 | self.raw.extra_env_vars = 220 | self.extra_env_vars.get_raw().as_ptr() as *mut *mut c_char; 221 | self.raw.extra_keep_env = 222 | self.extra_keep_env.get_raw().as_ptr() as *mut *mut c_char; 223 | self.raw.stdin_fd = self.stdin.map(|f| f.as_raw_fd()).unwrap_or(0); 224 | self.raw.stdout_fd = self.stdout.map(|f| f.as_raw_fd()).unwrap_or(1); 225 | self.raw.stderr_fd = self.stderr.map(|f| f.as_raw_fd()).unwrap_or(2); 226 | self.raw.log_fd = 227 | self.log_file.map(|f| f.as_raw_fd()).unwrap_or(-libc::EBADF); 228 | self.raw.initial_cwd = self 229 | .initial_cwd 230 | .as_ref() 231 | .map(|s| s.as_ptr() as *mut _) 232 | .unwrap_or(ptr::null_mut()); 233 | } 234 | 235 | pub fn raw(&mut self) -> &mut lxc_sys::lxc_attach_options_t { 236 | self.finish(); 237 | &mut self.raw 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /src/lxc/log_options.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | use crate::util::ffi::ToCString; 4 | use std::ffi::{CString, NulError, OsStr}; 5 | use std::ptr; 6 | 7 | /// Type representing options to initialize a log for the container. 8 | pub struct LogOptions { 9 | raw: lxc_sys::lxc_log, 10 | name: Option, 11 | path: Option, 12 | file: Option, 13 | level: Option, 14 | prefix: Option, 15 | quiet: bool, 16 | } 17 | 18 | impl LogOptions { 19 | pub fn new() -> Self { 20 | Self { 21 | raw: unsafe { std::mem::zeroed() }, 22 | name: None, 23 | path: None, 24 | file: None, 25 | level: None, 26 | prefix: None, 27 | quiet: true, 28 | } 29 | } 30 | } 31 | 32 | impl Default for LogOptions { 33 | fn default() -> Self { 34 | Self::new() 35 | } 36 | } 37 | 38 | impl LogOptions { 39 | pub fn set_log_name>( 40 | mut self, 41 | v: T, 42 | ) -> Result { 43 | let cv = v.as_ref().to_c_string()?; 44 | 45 | self.name = Some(cv.into_owned()); 46 | Ok(self) 47 | } 48 | 49 | pub fn set_log_path>( 50 | mut self, 51 | v: T, 52 | ) -> Result { 53 | let cv = v.as_ref().to_c_string()?; 54 | 55 | self.path = Some(cv.into_owned()); 56 | Ok(self) 57 | } 58 | 59 | pub fn set_log_file>( 60 | mut self, 61 | v: T, 62 | ) -> Result { 63 | let cv = v.as_ref().to_c_string()?; 64 | 65 | self.file = Some(cv.into_owned()); 66 | Ok(self) 67 | } 68 | 69 | pub fn set_log_level>( 70 | mut self, 71 | v: T, 72 | ) -> Result { 73 | let cv = v.as_ref().to_c_string()?; 74 | 75 | self.level = Some(cv.into_owned()); 76 | Ok(self) 77 | } 78 | 79 | pub fn set_log_prefix>( 80 | mut self, 81 | v: T, 82 | ) -> Result { 83 | let cv = v.as_ref().to_c_string()?; 84 | 85 | self.prefix = Some(cv.into_owned()); 86 | Ok(self) 87 | } 88 | 89 | pub fn set_quiet(mut self, quiet: bool) -> Self { 90 | self.quiet = quiet; 91 | self 92 | } 93 | 94 | fn finish(&mut self) { 95 | self.raw.name = self 96 | .name 97 | .as_ref() 98 | .map(|s| s.as_ptr() as *mut _) 99 | .unwrap_or(ptr::null_mut()); 100 | self.raw.lxcpath = self 101 | .path 102 | .as_ref() 103 | .map(|s| s.as_ptr() as *mut _) 104 | .unwrap_or(ptr::null_mut()); 105 | self.raw.file = self 106 | .file 107 | .as_ref() 108 | .map(|s| s.as_ptr() as *mut _) 109 | .unwrap_or(ptr::null_mut()); 110 | self.raw.level = self 111 | .level 112 | .as_ref() 113 | .map(|s| s.as_ptr() as *mut _) 114 | .unwrap_or(ptr::null_mut()); 115 | self.raw.prefix = self 116 | .prefix 117 | .as_ref() 118 | .map(|s| s.as_ptr() as *mut _) 119 | .unwrap_or(ptr::null_mut()); 120 | self.raw.quiet = self.quiet; 121 | } 122 | 123 | pub fn raw(&mut self) -> &mut lxc_sys::lxc_log { 124 | self.finish(); 125 | &mut self.raw 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/lxc/mod.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | //! Rust wrapper for `struct lxc_container`. Implements methods to control 4 | //! containers. 5 | 6 | use anyhow::{bail, Error}; 7 | use std::ffi::{CStr, CString, OsStr}; 8 | use std::os::raw::{c_char, c_int}; 9 | use std::path::Path; 10 | use std::ptr; 11 | use std::time::Duration; 12 | 13 | use crate::util::ffi::{StringArrayIter, ToCString}; 14 | 15 | mod attach_options; 16 | mod log_options; 17 | pub use attach_options::AttachOptions; 18 | pub use log_options::LogOptions; 19 | 20 | /// The main container handle. This implements the methods for `struct 21 | /// lxc_container`. 22 | pub struct Lxc { 23 | handle: *mut lxc_sys::lxc_container, 24 | } 25 | 26 | impl Drop for Lxc { 27 | fn drop(&mut self) { 28 | unsafe { 29 | lxc_sys::lxc_container_put(self.handle); 30 | } 31 | } 32 | } 33 | 34 | /// Get an iterator over all containers defined in the given `path`. This is a 35 | /// wrapper for liblxc's `list_all_containers` function. 36 | pub fn list_all_containers>( 37 | path: T, 38 | ) -> Result { 39 | let cpath = path.as_ref().to_c_string()?; 40 | let mut names: *mut *mut c_char = ptr::null_mut(); 41 | 42 | let nr = unsafe { 43 | lxc_sys::list_all_containers( 44 | cpath.as_ptr(), 45 | &mut names, 46 | ptr::null_mut(), 47 | ) 48 | }; 49 | 50 | if nr < 0 { 51 | bail!("failed to list containers"); 52 | } 53 | Ok(unsafe { StringArrayIter::new(names, nr as usize) }) 54 | } 55 | 56 | /// Returns the currently used liblxc's version string. 57 | pub fn get_version() -> &'static str { 58 | let cstr: &CStr = unsafe { CStr::from_ptr(lxc_sys::lxc_get_version()) }; 59 | cstr.to_str().unwrap_or("unknown") 60 | } 61 | 62 | pub fn get_global_config_item(key: &str) -> Result<&'static str, Error> { 63 | let ckey = CString::new(key).unwrap(); 64 | let cstr: &CStr = unsafe { 65 | CStr::from_ptr(lxc_sys::lxc_get_global_config_item(ckey.as_ptr())) 66 | }; 67 | if cstr.as_ptr().is_null() { 68 | bail!("failed to find value of {}", key); 69 | } 70 | Ok(cstr.to_str().unwrap()) 71 | } 72 | 73 | pub fn get_default_path() -> &'static str { 74 | match get_global_config_item("lxc.lxcpath") { 75 | Ok(s) => s, 76 | Err(_) => "", 77 | } 78 | } 79 | 80 | pub fn set_log(options: &mut LogOptions) -> Result<(), Error> { 81 | let ret = unsafe { lxc_sys::lxc_log_init(options.raw()) }; 82 | 83 | if ret < 0 { 84 | bail!("failed to initialize log"); 85 | } 86 | 87 | Ok(()) 88 | } 89 | 90 | impl Lxc { 91 | /// Create a new container handler for the container of the given `name` 92 | /// residing under the provided `path`. 93 | pub fn new, T: AsRef>( 94 | name: S, 95 | path: T, 96 | ) -> Result { 97 | let cname = name.as_ref().to_c_string()?; 98 | let cpath = path.as_ref().to_c_string()?; 99 | let handle = unsafe { 100 | lxc_sys::lxc_container_new(cname.as_ptr(), cpath.as_ptr()) 101 | }; 102 | 103 | if handle.is_null() { 104 | bail!("failed to allocate new container"); 105 | } 106 | 107 | Ok(Lxc { handle }) 108 | } 109 | 110 | pub fn name(&self) -> Option<&str> { 111 | let n = unsafe { CStr::from_ptr((*self.handle).name) }; 112 | match n.to_str() { 113 | Ok(s) => Some(s), 114 | Err(_) => None, 115 | } 116 | } 117 | 118 | pub fn path(&self) -> Option<&str> { 119 | let n = unsafe { CStr::from_ptr((*self.handle).config_path) }; 120 | match n.to_str() { 121 | Ok(s) => Some(s), 122 | Err(_) => None, 123 | } 124 | } 125 | 126 | /// Attempt to start the container. If `stub` is true, the container's 127 | /// `lxc.execute.cmd` is executed instead of `lxc.init.cmd`. 128 | pub fn start(&self, stub: bool, argv: Vec<&OsStr>) -> Result<(), Error> { 129 | let useinit = if stub { 1 } else { 0 }; 130 | 131 | let cargv: Vec<_> = 132 | argv.iter().map(|arg| arg.to_c_string().unwrap()).collect(); 133 | let mut args: Vec<_> = cargv.iter().map(|arg| arg.as_ptr()).collect(); 134 | if !args.is_empty() { 135 | args.push(std::ptr::null()); 136 | } 137 | 138 | let started = unsafe { 139 | if !args.is_empty() { 140 | // LXC doesn't alter char *const argv[] so the cast is safe. 141 | (*self.handle).start.unwrap()( 142 | self.handle, 143 | useinit, 144 | args.as_ptr() as *const *mut i8, 145 | ) 146 | } else { 147 | (*self.handle).start.unwrap()(self.handle, useinit, ptr::null()) 148 | } 149 | }; 150 | if !started { 151 | bail!("failed to start container"); 152 | } 153 | Ok(()) 154 | } 155 | 156 | /// Atetmpt to shutdown a container with a timeout. 157 | pub fn shutdown(&self, timeout: Option) -> Result<(), Error> { 158 | let timeout: c_int = match timeout { 159 | Some(to) => { 160 | let secs = to.as_secs(); 161 | // seconds can be large... 162 | if secs > (!(0 as c_int)) as u64 { 163 | bail!("timeout too large"); 164 | } 165 | secs as _ 166 | } 167 | None => -1, 168 | }; 169 | let down = 170 | unsafe { (*self.handle).shutdown.unwrap()(self.handle, timeout) }; 171 | if !down { 172 | bail!("failed to shutdown container"); 173 | } 174 | Ok(()) 175 | } 176 | 177 | /// Attempt to stop a running container. 178 | pub fn stop(&self) -> Result<(), Error> { 179 | let stopped = unsafe { (*self.handle).stop.unwrap()(self.handle) }; 180 | if !stopped { 181 | bail!("failed to start container"); 182 | } 183 | Ok(()) 184 | } 185 | 186 | /// Determine if the caller may control the container. 187 | pub fn may_control(&self) -> Result<(), Error> { 188 | if !unsafe { (*self.handle).may_control.unwrap()(self.handle) } { 189 | match self.name() { 190 | Some(n) => bail!("Insufficient permissions to control {}", n), 191 | None => bail!("Insufficient permissions to control container"), 192 | } 193 | }; 194 | Ok(()) 195 | } 196 | 197 | /// Determine if the container is running. 198 | pub fn is_running(&self) -> bool { 199 | unsafe { (*self.handle).is_running.unwrap()(self.handle) } 200 | } 201 | 202 | /// Try to run a program inside the container. 203 | pub fn attach_run_wait>( 204 | &self, 205 | options: &mut AttachOptions, 206 | program: T, 207 | argv: Vec<&OsStr>, 208 | ) -> i32 { 209 | let cprogram = match program.as_ref().to_c_string() { 210 | Ok(p) => p, 211 | Err(_) => return -1, 212 | }; 213 | let cargv: Vec<_> = 214 | argv.iter().map(|arg| arg.to_c_string().unwrap()).collect(); 215 | let mut args: Vec<_> = cargv.iter().map(|arg| arg.as_ptr()).collect(); 216 | args.push(std::ptr::null()); 217 | 218 | unsafe { 219 | (*self.handle).attach_run_wait.unwrap()( 220 | self.handle, 221 | options.raw(), 222 | cprogram.as_ptr(), 223 | args.as_ptr(), 224 | ) 225 | } 226 | } 227 | 228 | /// Determine state of container. 229 | pub fn state(&self) -> &'static str { 230 | let cstr: &CStr = unsafe { 231 | CStr::from_ptr((*self.handle).state.unwrap()(self.handle)) 232 | }; 233 | cstr.to_str().unwrap_or("UNKNOWN") 234 | } 235 | 236 | /// Get network interfaces of container. 237 | pub fn get_interfaces(&self) -> StringArrayIter { 238 | let mut len = 0; 239 | let names: *mut *mut c_char = 240 | unsafe { (*self.handle).get_interfaces.unwrap()(self.handle) }; 241 | 242 | if !names.is_null() { 243 | unsafe { 244 | for i in 0.. { 245 | if (*names.add(i)).is_null() { 246 | break; 247 | } 248 | len += 1; 249 | } 250 | }; 251 | } 252 | unsafe { StringArrayIter::new(names, len) } 253 | } 254 | 255 | /// Get ip addresses of an interface. 256 | pub fn get_ipv4(&self, interface: &str) -> StringArrayIter { 257 | let iface = CString::new(interface).unwrap(); 258 | 259 | let mut len = 0; 260 | let addresses: *mut *mut c_char = unsafe { 261 | (*self.handle).get_ips.unwrap()( 262 | self.handle, 263 | iface.as_ptr(), 264 | c_str!("inet").as_ptr(), 265 | 0, 266 | ) 267 | }; 268 | 269 | if !addresses.is_null() { 270 | unsafe { 271 | for i in 0.. { 272 | if (*addresses.add(i)).is_null() { 273 | // Since the string array is NULL-terminated so free the last element here. 274 | libc::free(*addresses.add(i) as *mut _); 275 | break; 276 | } 277 | len += 1; 278 | } 279 | }; 280 | } 281 | unsafe { StringArrayIter::new(addresses, len) } 282 | } 283 | 284 | /// Get ip addresses of an interface. 285 | pub fn get_ipv6(&self, interface: &str) -> StringArrayIter { 286 | let iface = CString::new(interface).unwrap(); 287 | 288 | let mut len = 0; 289 | let addresses: *mut *mut c_char = unsafe { 290 | (*self.handle).get_ips.unwrap()( 291 | self.handle, 292 | iface.as_ptr(), 293 | c_str!("inet6").as_ptr(), 294 | 0, 295 | ) 296 | }; 297 | 298 | if !addresses.is_null() { 299 | unsafe { 300 | for i in 0.. { 301 | if (*addresses.add(i)).is_null() { 302 | // Since the string array is NULL-terminated so free the last element here. 303 | libc::free(*addresses.add(i) as *mut _); 304 | break; 305 | } 306 | len += 1; 307 | } 308 | }; 309 | } 310 | unsafe { StringArrayIter::new(addresses, len) } 311 | } 312 | 313 | pub fn daemonize(&self, daemonize: bool) { 314 | unsafe { 315 | (*self.handle).want_daemonize.unwrap()(self.handle, daemonize) 316 | }; 317 | } 318 | 319 | pub fn terminal(&self) -> Result<(), Error> { 320 | let ret = unsafe { 321 | (*self.handle).console.unwrap()(self.handle, 0, 0, 1, 2, 1) 322 | }; 323 | 324 | if ret < 0 { 325 | bail!("failed to attach to terminal"); 326 | } 327 | Ok(()) 328 | } 329 | 330 | /// Freeze a running container. 331 | pub fn freeze(&self) -> Result<(), Error> { 332 | let frozen = unsafe { (*self.handle).freeze.unwrap()(self.handle) }; 333 | if !frozen { 334 | bail!("failed to freeze container"); 335 | } 336 | Ok(()) 337 | } 338 | 339 | /// Unfreeze a running container. 340 | pub fn unfreeze(&self) -> Result<(), Error> { 341 | let thawed = unsafe { (*self.handle).unfreeze.unwrap()(self.handle) }; 342 | if !thawed { 343 | bail!("failed to unfreeze container"); 344 | } 345 | Ok(()) 346 | } 347 | } 348 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! c_str { 2 | ($data:expr) => {{ 3 | #![allow(unused_unsafe)] 4 | let bytes = concat!($data, "\0"); 5 | unsafe { 6 | std::ffi::CStr::from_bytes_with_nul_unchecked(bytes.as_bytes()) 7 | } 8 | }}; 9 | } 10 | -------------------------------------------------------------------------------- /src/util/ffi.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | //! FFI utilities to help communicating with the C library. 4 | 5 | use std::borrow::Cow; 6 | use std::ffi::{CStr, CString, NulError}; 7 | use std::os::raw::c_char; 8 | use std::os::unix::ffi::OsStrExt; 9 | 10 | /// Helper to create a C string array (`char**`) variable with the ownership 11 | /// still in rust code. The raw version of this will contain a trailing `NULL` 12 | /// pointer. 13 | #[derive(Debug, Default)] 14 | pub struct CStringVec { 15 | owned: Vec, 16 | ffi: Vec<*const c_char>, 17 | } 18 | 19 | impl CStringVec { 20 | /// Create a new empty vector. 21 | pub fn new() -> Self { 22 | Self { 23 | owned: Vec::new(), 24 | ffi: Vec::new(), 25 | } 26 | } 27 | 28 | /// Update the inner `ffi` vector. 29 | fn update(&mut self) { 30 | self.ffi.truncate(0); 31 | self.ffi.reserve(self.owned.len() + 1); 32 | for cstr in self.owned.iter() { 33 | self.ffi.push(cstr.as_ptr()); 34 | } 35 | self.ffi.push(std::ptr::null()); 36 | } 37 | 38 | /// Get a reference to the ffi vector. We return a reference to the `Vec` 39 | /// type instead of returning a `*const *const c_char` to explicitly show 40 | /// that this borrows `self`! 41 | pub fn get_raw<'a>(&'a mut self) -> &'a Vec<*const c_char> { 42 | self.update(); 43 | &self.ffi 44 | } 45 | 46 | //pub fn into_inner(self) -> Vec { 47 | // self.owned 48 | //} 49 | } 50 | 51 | // Implement `Deref>` so we can use this type exactly as if 52 | // it actually were just the inner `Vec`. 53 | impl std::ops::Deref for CStringVec { 54 | type Target = Vec; 55 | 56 | fn deref(&self) -> &Self::Target { 57 | &self.owned 58 | } 59 | } 60 | 61 | impl std::ops::DerefMut for CStringVec { 62 | fn deref_mut(&mut self) -> &mut Self::Target { 63 | &mut self.owned 64 | } 65 | } 66 | 67 | /// This iterates over a `char**`, consuming each contained string by returning 68 | /// it as an owning CString. The pointer holding the list will also be freed in 69 | /// `drop`. 70 | #[derive(Debug)] 71 | pub struct StringArrayIter { 72 | ptr: *mut *mut c_char, 73 | len: usize, 74 | at: usize, 75 | } 76 | 77 | impl StringArrayIter { 78 | /// Get the contents as a slice to work with more easily. 79 | fn as_slice(&self) -> &[*mut c_char] { 80 | unsafe { 81 | std::slice::from_raw_parts(self.ptr as *const *mut c_char, self.len) 82 | } 83 | } 84 | 85 | /// Create a new string array iterator. 86 | /// 87 | /// # Safety 88 | /// 89 | /// `ptr` must point to an allocated array of valid pointers to C strings. 90 | pub unsafe fn new(ptr: *mut *mut c_char, len: usize) -> Self { 91 | let mut this = Self { ptr, len, at: 0 }; 92 | // Try to find any early NULLs. 93 | this.len = this 94 | .as_slice() 95 | .iter() 96 | .position(|p| p.is_null()) 97 | .unwrap_or(this.len); 98 | this 99 | } 100 | } 101 | 102 | impl Iterator for StringArrayIter { 103 | type Item = String; 104 | 105 | fn next(&mut self) -> Option { 106 | let ptr = *self.as_slice().get(self.at)?; 107 | self.at += 1; 108 | let cstr = unsafe { CStr::from_ptr(ptr) }; 109 | Some( 110 | cstr.to_str() 111 | .expect("liblxc returned non-utf8 string") 112 | .to_string(), 113 | ) 114 | } 115 | } 116 | 117 | impl Drop for StringArrayIter { 118 | fn drop(&mut self) { 119 | unsafe { 120 | for ptr in self.as_slice() { 121 | libc::free(*ptr as *mut libc::c_void); 122 | } 123 | libc::free(self.ptr as *mut _); 124 | } 125 | } 126 | } 127 | 128 | /// Helper trait allowing faster conversion from various string types to 129 | /// `CStrings`. 130 | /// 131 | /// Some types in rust don't have convenient conversion paths towards to 132 | /// `CString` (due to rust methods having to be safe for multiple platforms). 133 | /// `CString::new` takes a value which is `Into>`. When you have a 134 | /// `Path` you can take it `AsRef` which can provide an `as_bytes()` 135 | /// method, but only if the `std::os::unix::ffi::OsStrExt` trait is visible. 136 | /// 137 | /// This trait connects all those missing paths for the most common types. Use 138 | /// it as: 139 | /// 140 | /// use rlxc::util::ffi::ToCString; 141 | /// 142 | /// fn foo(path: &T) -> Result<()> { 143 | /// let cpath = path.to_c_string()?; 144 | /// unsafe { c_function(cpath.as_ptr()) }; 145 | /// Ok(()) 146 | /// } 147 | pub trait ToCString { 148 | fn to_c_string(&self) -> Result, NulError>; 149 | } 150 | 151 | impl ToCString for CStr { 152 | fn to_c_string(&self) -> Result, NulError> { 153 | Ok(Cow::Borrowed(self)) 154 | } 155 | } 156 | 157 | impl ToCString for CString { 158 | fn to_c_string(&self) -> Result, NulError> { 159 | Ok(Cow::Borrowed(&self)) 160 | } 161 | } 162 | 163 | impl ToCString for str { 164 | fn to_c_string(&self) -> Result, NulError> { 165 | Ok(Cow::Owned(CString::new(self)?)) 166 | } 167 | } 168 | 169 | impl ToCString for [u8] { 170 | fn to_c_string(&self) -> Result, NulError> { 171 | Ok(Cow::Owned(CString::new(self)?)) 172 | } 173 | } 174 | 175 | impl ToCString for String { 176 | fn to_c_string(&self) -> Result, NulError> { 177 | Ok(Cow::Owned(CString::new(self.as_bytes())?)) 178 | } 179 | } 180 | 181 | impl ToCString for std::ffi::OsStr { 182 | fn to_c_string(&self) -> Result, NulError> { 183 | Ok(Cow::Owned(CString::new(self.as_bytes())?)) 184 | } 185 | } 186 | 187 | impl ToCString for std::ffi::OsString { 188 | fn to_c_string(&self) -> Result, NulError> { 189 | Ok(Cow::Owned(CString::new(self.as_bytes())?)) 190 | } 191 | } 192 | 193 | impl ToCString for std::path::Path { 194 | fn to_c_string(&self) -> Result, NulError> { 195 | AsRef::::as_ref(self).to_c_string() 196 | } 197 | } 198 | 199 | impl ToCString for std::path::PathBuf { 200 | fn to_c_string(&self) -> Result, NulError> { 201 | AsRef::::as_ref(self).to_c_string() 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/util/mod.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: LGPL-2.1+ 2 | 3 | //! Collection of various utilties. 4 | 5 | pub mod ffi; 6 | --------------------------------------------------------------------------------