├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .gitmodules ├── BUILD.md ├── LICENSE ├── README.md ├── assets └── post.png ├── build.zig ├── build.zig.zon ├── crun_include └── git-version.h ├── libfuse_include ├── fuse_config.h └── libfuse_config.h └── src ├── common.zig ├── dockerc.zig ├── extract_squashfs.zig ├── main.zig ├── replace.zig ├── runtimes.zig └── tools └── policy.json /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push] 2 | jobs: 3 | lint: 4 | runs-on: ubuntu-latest 5 | steps: 6 | - uses: actions/checkout@v4 7 | - uses: goto-bus-stop/setup-zig@v2 8 | with: 9 | version: 0.13.0 10 | - run: zig fmt --check . 11 | test: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | with: 16 | submodules: 'recursive' 17 | - uses: actions/setup-go@v5 18 | with: 19 | go-version: '1.22.6' 20 | - uses: goto-bus-stop/setup-zig@v2 21 | with: 22 | version: 0.13.0 23 | - run: sudo apt install autoconf libtool pkg-config make libzstd-dev libfuse3-dev 24 | - run: zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-linux-musl 25 | - run: zig-out/bin/dockerc --image docker://hello-world --output enlo 26 | - run: ./enlo -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .zig-cache/ 2 | zig-out/ 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "umoci"] 2 | path = umoci 3 | url = https://github.com/opencontainers/umoci.git 4 | [submodule "skopeo"] 5 | path = skopeo 6 | url = https://github.com/containers/skopeo.git 7 | [submodule "crun"] 8 | path = crun 9 | url = https://github.com/NilsIrl/crun.git 10 | branch = dockerc 11 | [submodule "squashfs-tools"] 12 | path = squashfs-tools 13 | url = https://github.com/plougher/squashfs-tools.git 14 | [submodule "zstd"] 15 | path = zstd 16 | url = https://github.com/facebook/zstd.git 17 | [submodule "squashfuse"] 18 | path = squashfuse 19 | url = https://github.com/vasi/squashfuse.git 20 | [submodule "fuse-overlayfs"] 21 | path = fuse-overlayfs 22 | url = https://github.com/containers/fuse-overlayfs.git 23 | [submodule "libfuse"] 24 | path = libfuse 25 | url = https://github.com/libfuse/libfuse.git 26 | [submodule "argp-standalone"] 27 | path = argp-standalone 28 | url = https://github.com/argp-standalone/argp-standalone.git 29 | -------------------------------------------------------------------------------- /BUILD.md: -------------------------------------------------------------------------------- 1 | ``` 2 | sudo apt install libzstd-dev 3 | ./configure --without-xz --without-zlib LDFLAGS="-static" 4 | make LDFLAGS="-all-static" -j 5 | ``` 6 | 7 | ``` 8 | zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-linux-musl 9 | ``` 10 | 11 | Examples images to try on: 12 | 13 | * https://github.com/oven-sh/bun?tab=readme-ov-file#install 14 | * https://github.com/containers/skopeo/blob/main/install.md#container-images 15 | * https://github.com/shepherdjerred/macos-cross-compiler 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dockerc - compile docker images to standalone portable binaries 2 | 3 | No more [![Tweet](./assets/post.png)][4] 4 | 5 | No more `docker run`, no more `pip install`, no more `npm i`, just give your users executables they can run! 6 | 7 | 8 | ## Usage 9 | 10 | Install dockerc from the [latest release](https://github.com/NilsIrl/dockerc/releases). 11 | 12 | 13 | ``` 14 | # Image from docker hub 15 | $ dockerc --image docker://oven/bun --output bun 16 | # Image in local docker daemon storage 17 | $ dockerc --image docker-daemon:mysherlock-image:latest --output sherlock_bin 18 | # Specify target instruction set architecture 19 | $ dockerc --image docker://hello-world --arch arm64 --output hello 20 | ``` 21 | 22 | The output binary can then be called as you would with usual binaries. You can 23 | also specify `-e`, and `-v` in the same way you would when using `docker run`. 24 | Networked services running inside the container can be accessed directly without 25 | having to specify `-p`. 26 | 27 | Skopeo is used for loading images, for other locations refer to [its documentation][1]. 28 | 29 | ## Build from source 30 | 31 | Please note that this project uses Git submodules. If you clone this repository, you may need to run the following commands to initialize and update the submodules: 32 | 33 | ``` 34 | $ git submodule init 35 | $ git submodule update 36 | ``` 37 | 38 | This will ensure that you download and update all relevant submodule contents. 39 | 40 | dockerc uses a patched version of the zig compiler than can be found on the 41 | [nils-dockerc-version branch][5] of the NilsIrl/zig repository. There is an 42 | [open PR][6] for the patch to be included in upstream zig. 43 | 44 | To compile dockerc use the following commands: 45 | 46 | ``` 47 | $ zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-linux-musl 48 | $ zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-linux-musl 49 | ``` 50 | 51 | ## Features 52 | 53 | - [X] Compile docker images into portable binaries 54 | - [X] Rootless containers 55 | - [ ] MacOS and Windows support (using QEMU) 56 | - [X] x86_64 support 57 | - [X] arm64 support 58 | - [X] Supports arguments 59 | - [X] [Supports specifying environment variables using `-e`][2] 60 | - [X] [Supports specifying volumes using `-v`][3] 61 | - [ ] Support other [arguments][0]... 62 | 63 | [0]: https://docs.docker.com/engine/reference/commandline/container_run/ 64 | [1]: https://github.com/containers/skopeo/blob/main/docs/skopeo.1.md#image-names 65 | [2]: https://docs.docker.com/reference/cli/docker/container/run/#env 66 | [3]: https://docs.docker.com/reference/cli/docker/container/run/#volume 67 | [4]: https://www.reddit.com/r/github/comments/1at9br4/i_am_new_to_github_and_i_have_lots_to_say/ 68 | [5]: https://github.com/NilsIrl/zig/tree/nils-dockerc-version 69 | [6]: https://github.com/ziglang/zig/pull/21092 70 | -------------------------------------------------------------------------------- /assets/post.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsIrl/dockerc/18e03306a162654b40677b3a0e40dc60c61fb328/assets/post.png -------------------------------------------------------------------------------- /build.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | 3 | // Although this function looks imperative, note that its job is to 4 | // declaratively construct a build graph that will be executed by an external 5 | // runner. 6 | pub fn build(b: *std.Build) void { 7 | b.reference_trace = 64; 8 | 9 | // Standard target options allows the person running `zig build` to choose 10 | // what target to build for. Here we do not override the defaults, which 11 | // means any target is allowed, and the default is native. Other options 12 | // for restricting supported target set are available. 13 | const target = b.standardTargetOptions(.{}); 14 | 15 | // Standard optimization options allow the person running `zig build` to select 16 | // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not 17 | // set a preferred release mode, allowing the user to decide how to optimize. 18 | const optimize = b.standardOptimizeOption(.{}); 19 | 20 | const skip_crun_build = b.option(bool, "skip_crun_build", "Skip crun build") orelse false; 21 | const dockerc_version = b.option([]const u8, "dockerc_version", "Set dockerc version") orelse "HEAD"; 22 | 23 | const build_info = b.addOptions(); 24 | build_info.addOption([]const u8, "dockerc_version", dockerc_version); 25 | 26 | const zstd = b.createModule(.{}); 27 | zstd.addAssemblyFile(b.path("zstd/lib/decompress/huf_decompress_amd64.S")); 28 | zstd.addCSourceFiles(.{ 29 | .files = &[_][]const u8{ 30 | "zstd/lib/common/debug.c", 31 | "zstd/lib/common/entropy_common.c", 32 | "zstd/lib/common/error_private.c", 33 | "zstd/lib/common/fse_decompress.c", 34 | "zstd/lib/common/pool.c", 35 | "zstd/lib/common/threading.c", 36 | "zstd/lib/common/xxhash.c", 37 | "zstd/lib/common/zstd_common.c", 38 | 39 | "zstd/lib/compress/fse_compress.c", 40 | "zstd/lib/compress/hist.c", 41 | "zstd/lib/compress/huf_compress.c", 42 | "zstd/lib/compress/zstd_compress.c", 43 | "zstd/lib/compress/zstd_compress_literals.c", 44 | "zstd/lib/compress/zstd_compress_sequences.c", 45 | "zstd/lib/compress/zstd_compress_superblock.c", 46 | "zstd/lib/compress/zstd_double_fast.c", 47 | "zstd/lib/compress/zstd_fast.c", 48 | "zstd/lib/compress/zstd_lazy.c", 49 | "zstd/lib/compress/zstd_ldm.c", 50 | "zstd/lib/compress/zstdmt_compress.c", 51 | "zstd/lib/compress/zstd_opt.c", 52 | 53 | "zstd/lib/decompress/huf_decompress.c", 54 | "zstd/lib/decompress/zstd_ddict.c", 55 | "zstd/lib/decompress/zstd_decompress_block.c", 56 | "zstd/lib/decompress/zstd_decompress.c", 57 | }, 58 | }); 59 | 60 | const fuse_fss = b.createModule(.{}); 61 | fuse_fss.addIncludePath(b.path("zstd/lib")); 62 | 63 | fuse_fss.addIncludePath(b.path("libfuse/include")); 64 | fuse_fss.addIncludePath(b.path("libfuse_include")); 65 | 66 | fuse_fss.addCSourceFiles(.{ 67 | .files = &[_][]const u8{ 68 | "libfuse/lib/fuse_opt.c", 69 | "libfuse/lib/helper.c", 70 | "libfuse/lib/fuse_log.c", 71 | "libfuse/lib/fuse_lowlevel.c", 72 | "libfuse/lib/mount_util.c", 73 | "libfuse/lib/fuse.c", 74 | "libfuse/lib/fuse_signals.c", 75 | "libfuse/lib/fuse_loop_mt.c", 76 | "libfuse/lib/buffer.c", 77 | "libfuse/lib/mount.c", 78 | "libfuse/lib/fuse_loop.c", 79 | "libfuse/lib/modules/subdir.c", 80 | "libfuse/lib/modules/iconv.c", 81 | "libfuse/lib/cuse_lowlevel.c", 82 | }, 83 | .flags = &[_][]const u8{ 84 | // TODO: figure out where to get this value from 85 | "-DFUSE_USE_VERSION=317", 86 | // TODO: make sure this is correct value as well, or maybe we're supposed to dynamically link 87 | "-DFUSERMOUNT_DIR=\"/usr/local/bin\"", 88 | }, 89 | }); 90 | 91 | fuse_fss.addIncludePath(b.path("fuse-overlayfs")); 92 | fuse_fss.addIncludePath(b.path("fuse-overlayfs/lib")); 93 | fuse_fss.addCSourceFiles(.{ 94 | .files = &[_][]const u8{ 95 | "fuse-overlayfs/main.c", 96 | "fuse-overlayfs/lib/hash.c", 97 | "fuse-overlayfs/lib/bitrotate.c", 98 | "fuse-overlayfs/utils.c", 99 | "fuse-overlayfs/plugin-manager.c", 100 | "fuse-overlayfs/direct.c", 101 | }, 102 | .flags = &[_][]const u8{ 103 | "-Dmain=overlayfs_main", 104 | // collision with libcrun 105 | "-Dsafe_openat=overlayfs_safe_openat", 106 | "-DPKGLIBEXECDIR=\"\"", 107 | "-Wno-format", 108 | "-Wno-switch", 109 | }, 110 | }); 111 | fuse_fss.addCSourceFiles(.{ 112 | .files = &[_][]const u8{ 113 | "squashfuse/ll_main.c", 114 | "squashfuse/ll.c", 115 | "squashfuse/ll_inode.c", 116 | "squashfuse/fs.c", 117 | "squashfuse/fuseprivate.c", 118 | "squashfuse/stat.c", 119 | "squashfuse/dir.c", 120 | "squashfuse/file.c", 121 | "squashfuse/xattr.c", 122 | "squashfuse/nonstd-enoattr.c", 123 | "squashfuse/nonstd-makedev.c", 124 | "squashfuse/util.c", 125 | "squashfuse/nonstd-daemon.c", 126 | "squashfuse/nonstd-pread.c", 127 | "squashfuse/swap.c", 128 | "squashfuse/table.c", 129 | "squashfuse/cache_mt.c", 130 | "squashfuse/decompress.c", 131 | "squashfuse/nonstd-stat.c", 132 | }, 133 | .flags = &[_][]const u8{ 134 | "-Dmain=squashfuse_main", 135 | "-D_FILE_OFFSET_BITS=64", 136 | }, 137 | }); 138 | 139 | const clap = b.dependency("clap", .{ 140 | .optimize = optimize, 141 | .target = target, 142 | }); 143 | 144 | const cc = std.fmt.allocPrint( 145 | b.allocator, 146 | "{s} cc --target={s}", 147 | .{ 148 | b.graph.zig_exe, 149 | target.result.zigTriple(b.allocator) catch @panic("OOM"), 150 | }, 151 | ) catch @panic("OOM"); 152 | 153 | const squashfuse_autogen = b.addSystemCommand(&[_][]const u8{ 154 | "./autogen.sh", 155 | }); 156 | squashfuse_autogen.setCwd(b.path("squashfuse")); 157 | 158 | const squashfuse_configure = b.addSystemCommand(&[_][]const u8{ 159 | "./configure", 160 | "--without-zlib", 161 | "--without-xz", 162 | "--without-lzo", 163 | "--without-lz4", 164 | "--with-zstd", 165 | }); 166 | squashfuse_configure.setCwd(b.path("squashfuse")); 167 | squashfuse_configure.step.dependOn(&squashfuse_autogen.step); 168 | 169 | const squashfuse_make_generate_swap = b.addSystemCommand(&[_][]const u8{ 170 | "make", 171 | "swap.h.inc", 172 | "swap.c.inc", 173 | }); 174 | squashfuse_make_generate_swap.setCwd(b.path("squashfuse")); 175 | squashfuse_make_generate_swap.step.dependOn(&squashfuse_configure.step); 176 | 177 | const overlayfs_autogen = b.addSystemCommand(&[_][]const u8{ 178 | "./autogen.sh", 179 | }); 180 | overlayfs_autogen.setCwd(b.path("fuse-overlayfs")); 181 | 182 | const overlayfs_configure = b.addSystemCommand(&[_][]const u8{ 183 | "./configure", 184 | }); 185 | overlayfs_configure.setCwd(b.path("fuse-overlayfs")); 186 | overlayfs_configure.step.dependOn(&overlayfs_autogen.step); 187 | 188 | const runtime = b.createModule(.{ 189 | .root_source_file = b.path("src/main.zig"), 190 | .link_libc = true, 191 | }); 192 | 193 | runtime.addOptions("build_info", build_info); 194 | 195 | runtime.addImport("zstd", zstd); 196 | runtime.addImport("fuse-overlayfs", fuse_fss); 197 | 198 | runtime.addIncludePath(b.path("crun_include")); 199 | runtime.addIncludePath(b.path("crun")); 200 | runtime.addIncludePath(b.path("crun/src")); 201 | runtime.addIncludePath(b.path("crun/libocispec/src")); 202 | 203 | runtime.addIncludePath(b.path("argp-standalone")); 204 | 205 | runtime.addCSourceFiles(.{ 206 | .files = &[_][]const u8{ 207 | "crun/src/libcrun/container.c", 208 | "crun/src/libcrun/status.c", 209 | "crun/src/libcrun/linux.c", 210 | "crun/src/libcrun/utils.c", 211 | "crun/src/libcrun/cgroup-utils.c", 212 | "crun/src/libcrun/cgroup.c", 213 | "crun/src/libcrun/intelrdt.c", 214 | "crun/src/libcrun/cgroup-resources.c", 215 | "crun/src/libcrun/ebpf.c", 216 | "crun/src/libcrun/cgroup-cgroupfs.c", 217 | "crun/src/libcrun/chroot_realpath.c", 218 | "crun/src/libcrun/cloned_binary.c", 219 | "crun/src/libcrun/custom-handler.c", 220 | "crun/src/libcrun/terminal.c", 221 | "crun/src/libcrun/cgroup-systemd.c", 222 | "crun/src/libcrun/error.c", 223 | "crun/src/libcrun/mount_flags.c", 224 | "crun/src/libcrun/seccomp.c", 225 | "crun/src/libcrun/seccomp_notify.c", 226 | "crun/src/libcrun/scheduler.c", 227 | "crun/src/libcrun/io_priority.c", 228 | "crun/src/libcrun/cgroup-setup.c", 229 | "crun/src/libcrun/signals.c", 230 | 231 | "crun/src/libcrun/blake3/blake3.c", 232 | "crun/src/libcrun/blake3/blake3_portable.c", 233 | 234 | "crun/libocispec/src/ocispec/read-file.c", 235 | "crun/libocispec/src/ocispec/json_common.c", 236 | "crun/libocispec/src/ocispec/runtime_spec_schema_config_schema.c", 237 | "crun/libocispec/src/ocispec/runtime_spec_schema_config_zos.c", 238 | "crun/libocispec/src/ocispec/runtime_spec_schema_config_vm.c", 239 | "crun/libocispec/src/ocispec/runtime_spec_schema_config_windows.c", 240 | "crun/libocispec/src/ocispec/runtime_spec_schema_config_solaris.c", 241 | "crun/libocispec/src/ocispec/runtime_spec_schema_config_linux.c", 242 | "crun/libocispec/src/ocispec/runtime_spec_schema_defs.c", 243 | "crun/libocispec/src/ocispec/runtime_spec_schema_defs_linux.c", 244 | "crun/libocispec/src/ocispec/runtime_spec_schema_defs_windows.c", 245 | "crun/libocispec/src/ocispec/runtime_spec_schema_defs_zos.c", 246 | 247 | "crun/libocispec/yajl/src/yajl.c", 248 | "crun/libocispec/yajl/src/yajl_gen.c", 249 | "crun/libocispec/yajl/src/yajl_buf.c", 250 | "crun/libocispec/yajl/src/yajl_alloc.c", 251 | "crun/libocispec/yajl/src/yajl_encode.c", 252 | "crun/libocispec/yajl/src/yajl_tree.c", 253 | "crun/libocispec/yajl/src/yajl_parser.c", 254 | "crun/libocispec/yajl/src/yajl_lex.c", 255 | }, 256 | }); 257 | 258 | runtime.addIncludePath(b.dependency("shadow", .{}).path("libsubid")); 259 | runtime.addIncludePath(b.dependency("shadow", .{}).path("lib")); 260 | runtime.addIncludePath(b.dependency("shadow", .{}).path("")); 261 | 262 | runtime.addCSourceFiles(.{ 263 | .root = b.dependency("shadow", .{}).path(""), 264 | .files = &[_][]const u8{ 265 | "libsubid/api.c", 266 | "lib/shadowlog.c", 267 | "lib/subordinateio.c", 268 | "lib/commonio.c", 269 | "lib/write_full.c", 270 | "lib/nss.c", 271 | "lib/get_pid.c", 272 | "lib/memzero.c", 273 | "lib/alloc.c", 274 | "lib/atoi/str2i.c", 275 | "lib/atoi/a2i.c", 276 | "lib/atoi/strtou_noneg.c", 277 | "lib/atoi/strtoi.c", 278 | "lib/string/sprintf.c", 279 | }, 280 | .flags = &[_][]const u8{ 281 | "-DENABLE_SUBIDS", 282 | // duplicate symbol with crun 283 | "-Dxasprintf=shadow_xasprintf", 284 | }, 285 | }); 286 | 287 | const aarch64_target = b.resolveTargetQuery(.{ 288 | .cpu_arch = .aarch64, 289 | .abi = target.result.abi, 290 | .os_tag = .linux, 291 | }); 292 | 293 | const x86_64_target = b.resolveTargetQuery(.{ 294 | .cpu_arch = .x86_64, 295 | .abi = target.result.abi, 296 | .os_tag = .linux, 297 | }); 298 | 299 | const runtime_x86_64 = b.addExecutable(.{ 300 | .name = "runtime_x86-64", 301 | .target = x86_64_target, 302 | .optimize = optimize, 303 | }); 304 | 305 | const runtime_aarch64 = b.addExecutable(.{ 306 | .name = "runtime_aarch64", 307 | .target = aarch64_target, 308 | // FIXME: When compiled with ReleaseSafe reading files in the overlayfs 309 | // will give EINVAL (Invalid Argument) 310 | .optimize = .Debug, 311 | }); 312 | 313 | runtime_x86_64.root_module.addImport("runtime", runtime); 314 | runtime_aarch64.root_module.addImport("runtime", runtime); 315 | 316 | const crun_autogen = b.addSystemCommand(&[_][]const u8{ 317 | "./autogen.sh", 318 | }); 319 | crun_autogen.setCwd(b.path("crun")); 320 | 321 | const crun_configure = b.addSystemCommand(&[_][]const u8{ 322 | "./configure", 323 | "--enable-embedded-yajl", 324 | "--disable-systemd", 325 | "--disable-caps", 326 | "--disable-seccomp", 327 | }); 328 | crun_configure.setEnvironmentVariable( 329 | "CC", 330 | cc, 331 | ); 332 | crun_configure.setCwd(b.path("crun")); 333 | crun_configure.step.dependOn(&crun_autogen.step); 334 | 335 | const libocspec_generate_files = b.addSystemCommand(&[_][]const u8{ 336 | "make", 337 | "src/ocispec/runtime_spec_schema_config_schema.c", 338 | "src/ocispec/runtime_spec_schema_config_zos.c", 339 | "src/ocispec/runtime_spec_schema_config_vm.c", 340 | "src/ocispec/runtime_spec_schema_config_windows.c", 341 | "src/ocispec/runtime_spec_schema_config_solaris.c", 342 | "src/ocispec/runtime_spec_schema_config_linux.c", 343 | "src/ocispec/runtime_spec_schema_defs.c", 344 | "src/ocispec/runtime_spec_schema_defs_linux.c", 345 | "src/ocispec/runtime_spec_schema_defs_windows.c", 346 | "src/ocispec/runtime_spec_schema_defs_zos.c", 347 | }); 348 | libocspec_generate_files.setCwd(b.path("crun/libocispec")); 349 | libocspec_generate_files.step.dependOn(&crun_configure.step); 350 | 351 | if (!skip_crun_build) { 352 | runtime_x86_64.step.dependOn(&squashfuse_make_generate_swap.step); 353 | runtime_x86_64.step.dependOn(&overlayfs_configure.step); 354 | runtime_x86_64.step.dependOn(&libocspec_generate_files.step); 355 | 356 | runtime_aarch64.step.dependOn(&squashfuse_make_generate_swap.step); 357 | runtime_aarch64.step.dependOn(&overlayfs_configure.step); 358 | runtime_aarch64.step.dependOn(&libocspec_generate_files.step); 359 | } 360 | 361 | const go_cpu_arch = switch (target.query.cpu_arch orelse target.result.cpu.arch) { 362 | .x86_64 => "amd64", 363 | .aarch64 => "arm64", 364 | else => @panic("unimplemented"), 365 | }; 366 | const umoci = b.addSystemCommand(&[_][]const u8{ 367 | "go", 368 | "build", 369 | "-tags", 370 | "", 371 | "-ldflags", 372 | "-s -extldflags '-static'", 373 | "-o", 374 | }); 375 | umoci.setCwd(b.path("umoci")); 376 | const umoci_output = umoci.addOutputFileArg( 377 | std.fmt.allocPrint( 378 | b.allocator, 379 | "umoci_{s}", 380 | .{go_cpu_arch}, 381 | ) catch @panic("OOM"), 382 | ); 383 | umoci.addArg("github.com/opencontainers/umoci/cmd/umoci"); 384 | umoci.setEnvironmentVariable( 385 | "CGO_ENABLED", 386 | "0", 387 | ); 388 | 389 | umoci.setEnvironmentVariable("GOARCH", go_cpu_arch); 390 | 391 | const skopeo = b.addSystemCommand(&[_][]const u8{ 392 | "go", 393 | "build", 394 | "-gcflags", 395 | "", 396 | "-tags", 397 | "containers_image_openpgp", 398 | "-o", 399 | }); 400 | skopeo.setCwd(b.path("skopeo")); 401 | const skopeo_output = skopeo.addOutputFileArg( 402 | std.fmt.allocPrint( 403 | b.allocator, 404 | "skopeo_{s}", 405 | .{go_cpu_arch}, 406 | ) catch @panic("OOM"), 407 | ); 408 | skopeo.addArg("./cmd/skopeo"); 409 | 410 | skopeo.setEnvironmentVariable( 411 | "CGO_ENABLED", 412 | "0", 413 | ); 414 | skopeo.setEnvironmentVariable("GOARCH", go_cpu_arch); 415 | skopeo.setEnvironmentVariable("DISABLE_DOCS", "1"); 416 | 417 | const dockerc = b.addExecutable(.{ 418 | .name = "dockerc", 419 | .root_source_file = b.path("src/dockerc.zig"), 420 | .target = target, 421 | .optimize = optimize, 422 | .link_libc = true, 423 | }); 424 | 425 | dockerc.root_module.addOptions("build_info", build_info); 426 | 427 | dockerc.addIncludePath(b.path("zstd/lib")); 428 | dockerc.root_module.addImport("zstd", zstd); 429 | dockerc.addCSourceFiles(.{ 430 | .files = &[_][]const u8{ 431 | "squashfs-tools/squashfs-tools/mksquashfs.c", 432 | "squashfs-tools/squashfs-tools/progressbar.c", 433 | "squashfs-tools/squashfs-tools/caches-queues-lists.c", 434 | "squashfs-tools/squashfs-tools/date.c", 435 | "squashfs-tools/squashfs-tools/pseudo.c", 436 | "squashfs-tools/squashfs-tools/action.c", 437 | "squashfs-tools/squashfs-tools/sort.c", 438 | "squashfs-tools/squashfs-tools/restore.c", 439 | "squashfs-tools/squashfs-tools/info.c", 440 | "squashfs-tools/squashfs-tools/mksquashfs_help.c", 441 | "squashfs-tools/squashfs-tools/print_pager.c", 442 | "squashfs-tools/squashfs-tools/compressor.c", 443 | "squashfs-tools/squashfs-tools/tar.c", 444 | "squashfs-tools/squashfs-tools/reader.c", 445 | "squashfs-tools/squashfs-tools/read_fs.c", 446 | "squashfs-tools/squashfs-tools/memory.c", 447 | "squashfs-tools/squashfs-tools/process_fragments.c", 448 | "squashfs-tools/squashfs-tools/zstd_wrapper.c", 449 | }, 450 | .flags = &[_][]const u8{ 451 | // avoid collision of main function 452 | "-Dmain=mksquashfs_main", 453 | "-DZSTD_SUPPORT", 454 | "-D_GNU_SOURCE", 455 | "-DVERSION=\"dockerc\"", 456 | "-DDATE=\"2024/07/21\"", 457 | "-DYEAR=\"2024\"", 458 | "-DCOMP_DEFAULT=\"zstd\"", 459 | "-DCOMPRESSORS=\"zstd\"", 460 | // There's UB in squashfs. This deals with it. 461 | "-fno-sanitize=undefined", 462 | }, 463 | }); 464 | 465 | dockerc.root_module.addAnonymousImport( 466 | "runtime_x86_64", 467 | .{ .root_source_file = runtime_x86_64.getEmittedBin() }, 468 | ); 469 | 470 | dockerc.root_module.addAnonymousImport( 471 | "runtime_aarch64", 472 | .{ .root_source_file = runtime_aarch64.getEmittedBin() }, 473 | ); 474 | 475 | dockerc.root_module.addAnonymousImport( 476 | "umoci", 477 | .{ .root_source_file = umoci_output }, 478 | ); 479 | dockerc.root_module.addAnonymousImport( 480 | "skopeo", 481 | .{ .root_source_file = skopeo_output }, 482 | ); 483 | 484 | dockerc.root_module.addImport("clap", clap.module("clap")); 485 | 486 | b.installArtifact(dockerc); 487 | 488 | const replace_bin = b.addExecutable(.{ 489 | .name = "replace", 490 | .root_source_file = b.path("src/replace.zig"), 491 | .target = target, 492 | .optimize = optimize, 493 | .link_libc = true, 494 | }); 495 | 496 | replace_bin.root_module.addAnonymousImport( 497 | "runtime_x86_64", 498 | .{ .root_source_file = runtime_x86_64.getEmittedBin() }, 499 | ); 500 | 501 | replace_bin.root_module.addAnonymousImport( 502 | "runtime_aarch64", 503 | .{ .root_source_file = runtime_aarch64.getEmittedBin() }, 504 | ); 505 | 506 | b.installArtifact(replace_bin); 507 | 508 | const extract_bin = b.addExecutable(.{ 509 | .name = "extract", 510 | .root_source_file = b.path("src/extract_squashfs.zig"), 511 | .target = target, 512 | .optimize = optimize, 513 | .link_libc = true, 514 | }); 515 | 516 | b.installArtifact(extract_bin); 517 | 518 | // This declares intent for the executable to be installed into the 519 | // standard location when the user invokes the "install" step (the default 520 | // step when running `zig build`). 521 | // b.installArtifact(exe); 522 | 523 | // This *creates* a Run step in the build graph, to be executed when another 524 | // step is evaluated that depends on it. The next line below will establish 525 | // such a dependency. 526 | // const run_cmd = b.addRunArtifact(exe); 527 | 528 | // By making the run step depend on the install step, it will be run from the 529 | // installation directory rather than directly from within the cache directory. 530 | // This is not necessary, however, if the application depends on other installed 531 | // files, this ensures they will be present and in the expected location. 532 | // run_cmd.step.dependOn(b.getInstallStep()); 533 | 534 | // This allows the user to pass arguments to the application in the build 535 | // command itself, like this: `zig build run -- arg1 arg2 etc` 536 | // if (b.args) |args| { 537 | // run_cmd.addArgs(args); 538 | // } 539 | 540 | // This creates a build step. It will be visible in the `zig build --help` menu, 541 | // and can be selected like this: `zig build run` 542 | // This will evaluate the `run` step rather than the default, which is "install". 543 | // const run_step = b.step("run", "Run the app"); 544 | // run_step.dependOn(&run_cmd.step); 545 | } 546 | -------------------------------------------------------------------------------- /build.zig.zon: -------------------------------------------------------------------------------- 1 | .{ 2 | .name = "dockerc", 3 | // This is a [Semantic Version](https://semver.org/). 4 | // In a future version of Zig it will be used for package deduplication. 5 | .version = "0.3.2", 6 | 7 | // This field is optional. 8 | // This is currently advisory only; Zig does not yet do anything 9 | // with this value. 10 | //.minimum_zig_version = "0.11.0", 11 | 12 | // This field is optional. 13 | // Each dependency must either provide a `url` and `hash`, or a `path`. 14 | // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. 15 | // Once all dependencies are fetched, `zig build` no longer requires 16 | // internet connectivity. 17 | .dependencies = .{ 18 | .clap = .{ 19 | .url = "https://github.com/Hejsil/zig-clap/archive/60cd46aacff4960104703da9ba683077b1e3c76c.tar.gz", 20 | .hash = "12205eb22c644df2469045083efe9c92189d56494ebe8901b36ef1218c3717e6eb78", 21 | }, 22 | .shadow = .{ 23 | .url = "https://github.com/shadow-maint/shadow/releases/download/4.15.3/shadow-4.15.3.tar.gz", 24 | .hash = "12202972bc830245199eb4c5b10f853f1be094eb8c86d431299a69b1c01fa5781a7e", 25 | }, 26 | }, 27 | .paths = .{ 28 | // This makes *all* files, recursively, included in this package. It is generally 29 | // better to explicitly list the files and directories instead, to insure that 30 | // fetching from tarballs, file system paths, and version control all result 31 | // in the same contents hash. 32 | "", 33 | // For example... 34 | //"build.zig", 35 | //"build.zig.zon", 36 | //"src", 37 | //"LICENSE", 38 | //"README.md", 39 | }, 40 | } 41 | -------------------------------------------------------------------------------- /crun_include/git-version.h: -------------------------------------------------------------------------------- 1 | #ifndef GIT_VERSION 2 | # define GIT_VERSION "dockerc-hash" 3 | #endif 4 | -------------------------------------------------------------------------------- /libfuse_include/fuse_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Autogenerated by the Meson build system. 3 | * Do not edit, your changes will be lost. 4 | */ 5 | 6 | #pragma once 7 | 8 | // not available in musl 9 | // #define HAVE_BACKTRACE 10 | 11 | #define HAVE_COPY_FILE_RANGE 12 | 13 | #define HAVE_FALLOCATE 14 | 15 | #define HAVE_FDATASYNC 16 | 17 | #define HAVE_FORK 18 | 19 | #define HAVE_FSTATAT 20 | 21 | #define HAVE_ICONV 22 | 23 | #define HAVE_OPENAT 24 | 25 | #define HAVE_PIPE2 26 | 27 | #define HAVE_POSIX_FALLOCATE 28 | 29 | #define HAVE_READLINKAT 30 | 31 | #define HAVE_SETXATTR 32 | 33 | #define HAVE_SPLICE 34 | 35 | #define HAVE_STRUCT_STAT_ST_ATIM 36 | 37 | #undef HAVE_STRUCT_STAT_ST_ATIMESPEC 38 | 39 | #define HAVE_UTIMENSAT 40 | 41 | #define HAVE_VMSPLICE 42 | 43 | #define PACKAGE_VERSION "3.17.0" 44 | 45 | -------------------------------------------------------------------------------- /libfuse_include/libfuse_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Autogenerated by the Meson build system. 3 | * Do not edit, your changes will be lost. 4 | */ 5 | 6 | #pragma once 7 | 8 | #define FUSE_HOTFIX_VERSION 0 9 | 10 | #define FUSE_MAJOR_VERSION 3 11 | 12 | #define FUSE_MINOR_VERSION 17 13 | 14 | #define LIBFUSE_BUILT_WITH_VERSIONED_SYMBOLS 1 15 | 16 | -------------------------------------------------------------------------------- /src/common.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const builtin = @import("builtin"); 3 | 4 | const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 5 | const native_endian = builtin.target.cpu.arch.endian(); 6 | 7 | pub const Footer = extern struct { 8 | offset: u64, 9 | // TODO: make use of this field, currently ignored 10 | require_mapped_uids: bool = false, 11 | }; 12 | 13 | pub fn mkdtemp(in: []u8) !void { 14 | try std.posix.getrandom(in[in.len - 6 ..]); 15 | for (in[in.len - 6 ..]) |*v| { 16 | v.* = letters[v.* % letters.len]; 17 | } 18 | 19 | try std.posix.mkdir(in, 0o700); 20 | } 21 | 22 | // TODO: ideally we can use memfd_create 23 | // The problem is that zig doesn't have fexecve support by default so it would 24 | // be a pain to find the location of the file. 25 | pub fn extract_file(tmpDir: []const u8, name: []const u8, data: []const u8, allocator: std.mem.Allocator) ![]const u8 { 26 | const path = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ tmpDir, name }); 27 | 28 | const file = try std.fs.createFileAbsolute(path, .{ .mode = 0o700 }); 29 | defer file.close(); 30 | try file.writeAll(data); 31 | 32 | return path; 33 | } 34 | 35 | pub fn getFooter(path: []const u8) !Footer { 36 | var file = try std.fs.cwd().openFile(path, .{}); 37 | try file.seekFromEnd(-@sizeOf(Footer)); 38 | 39 | var footer: Footer = undefined; 40 | std.debug.assert(try file.readAll(std.mem.asBytes(&footer)) == @sizeOf(Footer)); 41 | 42 | if (native_endian != std.builtin.Endian.little) { 43 | std.mem.byteSwapAllFields(Footer, footer[0]); 44 | } 45 | 46 | return footer; 47 | } 48 | 49 | pub fn writeFooter(file: std.fs.File, footer: Footer) !void { 50 | comptime std.debug.assert(@typeInfo(Footer).Struct.layout != .auto); 51 | 52 | if (native_endian != std.builtin.Endian.little) { 53 | std.mem.byteSwapAllFields(Footer, &footer); 54 | } 55 | 56 | try file.writeAll(std.mem.asBytes(&footer)); 57 | } 58 | -------------------------------------------------------------------------------- /src/dockerc.zig: -------------------------------------------------------------------------------- 1 | const builtin = @import("builtin"); 2 | const std = @import("std"); 3 | const clap = @import("clap"); 4 | const common = @import("common.zig"); 5 | const build_info = @import("build_info"); 6 | 7 | const mkdtemp = common.mkdtemp; 8 | const extract_file = common.extract_file; 9 | 10 | const debug = std.debug; 11 | 12 | const io = std.io; 13 | 14 | const skopeo_content = @embedFile("skopeo"); 15 | const umoci_content = @embedFile("umoci"); 16 | 17 | const policy_content = @embedFile("tools/policy.json"); 18 | 19 | fn get_runtime_content_len_u64(runtime_content: []const u8) [8]u8 { 20 | var buf: [8]u8 = undefined; 21 | std.mem.writeInt(u64, &buf, runtime_content.len, .big); 22 | return buf; 23 | } 24 | 25 | const runtime_content_x86_64 = @embedFile("runtime_x86_64"); 26 | const runtime_content_aarch64 = @embedFile("runtime_aarch64"); 27 | 28 | const runtime_content_len_u64_x86_64 = get_runtime_content_len_u64(runtime_content_x86_64); 29 | const runtime_content_len_u64_aarch64 = get_runtime_content_len_u64(runtime_content_aarch64); 30 | 31 | extern fn mksquashfs_main(argc: c_int, argv: [*:null]const ?[*:0]const u8) void; 32 | 33 | pub fn main() !void { 34 | var gpa = std.heap.GeneralPurposeAllocator(.{}){}; 35 | defer _ = gpa.deinit(); 36 | 37 | var temp_dir_path = "/tmp/dockerc-XXXXXX".*; 38 | try mkdtemp(&temp_dir_path); 39 | 40 | const allocator = gpa.allocator(); 41 | const skopeo_path = try extract_file(&temp_dir_path, "skopeo", skopeo_content, allocator); 42 | defer allocator.free(skopeo_path); 43 | 44 | const umoci_path = try extract_file(&temp_dir_path, "umoci", umoci_content, allocator); 45 | defer allocator.free(umoci_path); 46 | 47 | const policy_path = try extract_file(&temp_dir_path, "policy.json", policy_content, allocator); 48 | defer allocator.free(policy_path); 49 | 50 | const params = comptime clap.parseParamsComptime( 51 | \\-h, --help Display this help and exit. 52 | \\--version Display dockerc version. 53 | \\-i, --image Image to pull. 54 | \\-o, --output Output file. 55 | \\--arch Architecture (amd64, arm64). 56 | \\--rootfull Do not use rootless container. 57 | \\ 58 | ); 59 | 60 | var diag = clap.Diagnostic{}; 61 | var res = clap.parse(clap.Help, ¶ms, clap.parsers.default, .{ 62 | .diagnostic = &diag, 63 | .allocator = allocator, 64 | }) catch |err| { 65 | // Report useful error and exit 66 | diag.report(io.getStdErr().writer(), err) catch {}; 67 | return err; 68 | }; 69 | defer res.deinit(); 70 | 71 | if (res.args.version != 0) { 72 | std.debug.print("dockerc version: {s}\n", .{build_info.dockerc_version}); 73 | return; 74 | } 75 | 76 | if (res.args.help != 0) { 77 | try clap.help(io.getStdErr().writer(), clap.Help, ¶ms, .{}); 78 | return; 79 | } 80 | 81 | var missing_args = false; 82 | if (res.args.image == null) { 83 | debug.print("no --image specified\n", .{}); 84 | missing_args = true; 85 | } 86 | 87 | if (res.args.output == null) { 88 | debug.print("no --output specified\n", .{}); 89 | missing_args = true; 90 | } 91 | 92 | if (missing_args) { 93 | debug.print("--help for usage\n", .{}); 94 | return; 95 | } 96 | 97 | // safe to assert because checked above 98 | const image = res.args.image.?; 99 | const output_path = try allocator.dupeZ(u8, res.args.output.?); 100 | defer allocator.free(output_path); 101 | 102 | const destination_arg = try std.fmt.allocPrint(allocator, "oci:{s}/image:latest", .{temp_dir_path}); 103 | defer allocator.free(destination_arg); 104 | 105 | var skopeo_args = std.ArrayList([]const u8).init(allocator); 106 | defer skopeo_args.deinit(); 107 | 108 | try skopeo_args.appendSlice(&[_][]const u8{ 109 | skopeo_path, 110 | "copy", 111 | "--policy", 112 | policy_path, 113 | }); 114 | 115 | var runtime_content: []const u8 = undefined; 116 | 117 | if (res.args.arch) |arch| { 118 | try skopeo_args.append("--override-arch"); 119 | try skopeo_args.append(arch); 120 | 121 | if (std.mem.eql(u8, arch, "amd64")) { 122 | runtime_content = runtime_content_x86_64; 123 | } else if (std.mem.eql(u8, arch, "arm64")) { 124 | runtime_content = runtime_content_aarch64; 125 | } else { 126 | std.debug.panic("unsupported arch: {s}\n", .{arch}); 127 | } 128 | } else { 129 | switch (builtin.target.cpu.arch) { 130 | .x86_64 => { 131 | runtime_content = runtime_content_x86_64; 132 | }, 133 | .aarch64 => { 134 | runtime_content = runtime_content_aarch64; 135 | }, 136 | else => { 137 | std.debug.panic("unsupported arch: {}", .{builtin.target.cpu.arch}); 138 | }, 139 | } 140 | } 141 | 142 | try skopeo_args.append(image); 143 | try skopeo_args.append(destination_arg); 144 | 145 | var skopeoProcess = std.process.Child.init(skopeo_args.items, gpa.allocator()); 146 | _ = try skopeoProcess.spawnAndWait(); 147 | 148 | const umoci_image_layout_path = try std.fmt.allocPrint(allocator, "{s}/image:latest", .{temp_dir_path}); 149 | defer allocator.free(umoci_image_layout_path); 150 | 151 | const bundle_destination = try std.fmt.allocPrintZ(allocator, "{s}/bundle", .{temp_dir_path}); 152 | defer allocator.free(bundle_destination); 153 | 154 | const umoci_args = [_][]const u8{ 155 | umoci_path, 156 | "unpack", 157 | "--image", 158 | umoci_image_layout_path, 159 | bundle_destination, 160 | "--rootless", 161 | }; 162 | var umociProcess = std.process.Child.init(if (res.args.rootfull == 0) &umoci_args else umoci_args[0 .. umoci_args.len - 1], gpa.allocator()); 163 | _ = try umociProcess.spawnAndWait(); 164 | 165 | const offset_arg = try std.fmt.allocPrintZ(allocator, "{}", .{runtime_content.len}); 166 | defer allocator.free(offset_arg); 167 | 168 | var mksquashfs_args = [_:null]?[*:0]const u8{ 169 | "mksquashfs", 170 | bundle_destination, 171 | output_path, 172 | "-comp", 173 | "zstd", 174 | "-offset", 175 | offset_arg, 176 | "-noappend", 177 | "-force-uid", 178 | "0", 179 | "-force-gid", 180 | "0", 181 | }; 182 | 183 | mksquashfs_main( 184 | // in rootfull, do not force uid/gid to 0,0 185 | if (res.args.rootfull != 0) 186 | mksquashfs_args.len - 4 187 | else 188 | mksquashfs_args.len, 189 | &mksquashfs_args, 190 | ); 191 | 192 | const file = try std.fs.cwd().openFile(output_path, .{ 193 | .mode = .write_only, 194 | }); 195 | defer file.close(); 196 | 197 | try file.writeAll(runtime_content); 198 | try file.seekFromEnd(0); 199 | 200 | try common.writeFooter(file, common.Footer{ 201 | .offset = runtime_content.len, 202 | .require_mapped_uids = false, 203 | }); 204 | 205 | try file.chmod(0o755); 206 | } 207 | -------------------------------------------------------------------------------- /src/extract_squashfs.zig: -------------------------------------------------------------------------------- 1 | const common = @import("common.zig"); 2 | const std = @import("std"); 3 | const assert = std.debug.assert; 4 | 5 | pub fn main() !void { 6 | var args = std.process.args(); 7 | assert(args.skip()); 8 | 9 | if (args.next()) |dockercGeneratedBinary| { 10 | if (args.next()) |squashfsOutput| { 11 | const offset = (try common.getFooter(dockercGeneratedBinary)).offset; 12 | 13 | const readFile = try std.fs.cwd().openFile(dockercGeneratedBinary, .{}); 14 | const writeFile = try std.fs.cwd().createFile(squashfsOutput, .{}); 15 | 16 | // try writeFile.writeAll(runtimes.runtime_content_x86_64); 17 | const len_to_write = try readFile.getEndPos() - offset - 8; 18 | assert(try writeFile.getPos() == 0); 19 | const len_written = try std.fs.File.copyRange(readFile, offset, writeFile, 0, len_to_write); 20 | assert(len_to_write == len_written); 21 | 22 | writeFile.close(); 23 | readFile.close(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const assert = std.debug.assert; 3 | const common = @import("common.zig"); 4 | const build_info = @import("build_info"); 5 | 6 | const mkdtemp = common.mkdtemp; 7 | const extract_file = common.extract_file; 8 | 9 | const c = @cImport({ 10 | @cInclude("libcrun/container.h"); 11 | @cInclude("libcrun/custom-handler.h"); 12 | @cInclude("subid.h"); 13 | }); 14 | 15 | extern fn squashfuse_main(argc: c_int, argv: [*:null]const ?[*:0]const u8) c_int; 16 | extern fn overlayfs_main(argc: c_int, argv: [*:null]const ?[*:0]const u8) c_int; 17 | 18 | const eql = std.mem.eql; 19 | 20 | // inspired from std.posix.getenv 21 | fn getEnvFull(key: []const u8) ?[:0]const u8 { 22 | var ptr = std.c.environ; 23 | while (ptr[0]) |line| : (ptr += 1) { 24 | var line_i: usize = 0; 25 | while (line[line_i] != 0 and line[line_i] != '=') : (line_i += 1) {} 26 | const this_key = line[0..line_i]; 27 | 28 | if (!std.mem.eql(u8, this_key, key)) continue; 29 | 30 | return std.mem.sliceTo(line, 0); 31 | } 32 | return null; 33 | } 34 | 35 | const IDMapping = struct { 36 | containerID: i64, 37 | hostID: i64, 38 | size: i64, 39 | 40 | fn toValue(self: @This(), allocator: Allocator) !std.json.Value { 41 | var object = std.json.ObjectMap.init(allocator); 42 | try object.put("containerID", std.json.Value{ 43 | .integer = self.containerID, 44 | }); 45 | try object.put("hostID", std.json.Value{ 46 | .integer = self.hostID, 47 | }); 48 | try object.put("size", std.json.Value{ 49 | .integer = self.size, 50 | }); 51 | return std.json.Value{ .object = object }; 52 | } 53 | }; 54 | 55 | const IDMappings = []IDMapping; 56 | 57 | fn intToString(allocator: Allocator, v: i64) ![]u8 { 58 | return std.fmt.allocPrint(allocator, "{}", .{v}); 59 | } 60 | 61 | fn newgidmap(allocator: Allocator, pid: i64, gid_mappings: IDMappings) !void { 62 | return uidgidmap_helper(allocator, "newgidmap", pid, gid_mappings); 63 | } 64 | 65 | fn newuidmap(allocator: Allocator, pid: i64, uid_mappings: IDMappings) !void { 66 | return uidgidmap_helper(allocator, "newuidmap", pid, uid_mappings); 67 | } 68 | 69 | fn uidgidmap_helper(child_allocator: Allocator, helper: []const u8, pid: i64, uid_mappings: IDMappings) !void { 70 | var arena = std.heap.ArenaAllocator.init(child_allocator); 71 | const allocator = arena.allocator(); 72 | defer arena.deinit(); 73 | 74 | var argv = try std.ArrayList([]const u8).initCapacity(allocator, 2 + 3 * uid_mappings.len); 75 | argv.appendAssumeCapacity(helper); 76 | // TODO: specify pid using fd:N to avoid a TOCTTOU, see newuidmap(1) 77 | argv.appendAssumeCapacity(try intToString(allocator, pid)); 78 | 79 | for (uid_mappings) |uid_mapping| { 80 | argv.appendAssumeCapacity(try intToString(allocator, uid_mapping.containerID)); 81 | argv.appendAssumeCapacity(try intToString(allocator, uid_mapping.hostID)); 82 | argv.appendAssumeCapacity(try intToString(allocator, uid_mapping.size)); 83 | } 84 | 85 | var newuidmapProcess = std.process.Child.init(argv.items, allocator); 86 | switch (try newuidmapProcess.spawnAndWait()) { 87 | .Exited => |status| if (status == 0) { 88 | return; 89 | } else { 90 | std.debug.panic("newuidmap/newgidmap failed with status: {}", .{status}); 91 | }, 92 | else => |term| { 93 | std.debug.panic("newuidmap/newgidmap terminated abnormally: {}", .{term}); 94 | }, 95 | } 96 | return error.UidGidMapFailed; 97 | } 98 | 99 | const Allocator = std.mem.Allocator; 100 | 101 | fn IDMappingsToValue(allocator: Allocator, id_mappings: IDMappings) !std.json.Value { 102 | var array = try std.json.Array.initCapacity(allocator, id_mappings.len); 103 | for (id_mappings) |id_mapping| { 104 | array.appendAssumeCapacity(try id_mapping.toValue(allocator)); 105 | } 106 | return std.json.Value{ .array = array }; 107 | } 108 | 109 | const IdMapParser = struct { 110 | bytes: []const u8, 111 | index: usize = 0, 112 | 113 | fn nextNumber(self: *IdMapParser) ?i64 { 114 | while (self.index < self.bytes.len and (self.bytes[self.index] < '0' or self.bytes[self.index] > '9')) { 115 | self.index += 1; 116 | } 117 | 118 | if (self.index == self.bytes.len) { 119 | return null; 120 | } 121 | 122 | const intStart = self.index; 123 | 124 | while (self.bytes[self.index] >= '0' and self.bytes[self.index] <= '9') { 125 | self.index += 1; 126 | 127 | if (self.index == self.bytes.len) { 128 | break; 129 | } 130 | } 131 | 132 | return std.fmt.parseInt(i64, self.bytes[intStart..self.index], 10) catch |err| { 133 | std.debug.panic("unexpected error parsing uid_map/gid_map: {}\n", .{err}); 134 | }; 135 | } 136 | }; 137 | 138 | fn parseIdmap(allocator: Allocator, bytes: []const u8) !IDMappings { 139 | var idmap_parser = IdMapParser{ .bytes = bytes }; 140 | var id_mappings = std.ArrayList(IDMapping).init(allocator); 141 | 142 | while (idmap_parser.nextNumber()) |containerID| { 143 | try id_mappings.append(IDMapping{ 144 | .containerID = containerID, 145 | .hostID = idmap_parser.nextNumber() orelse std.debug.panic("must have 3 numbers\n", .{}), 146 | .size = idmap_parser.nextNumber() orelse std.debug.panic("must have 3 numbers\n", .{}), 147 | }); 148 | } 149 | 150 | return id_mappings.toOwnedSlice(); 151 | } 152 | 153 | fn updateIdMap(id_mappings: IDMappings) void { 154 | var runningId: i64 = 0; 155 | 156 | for (id_mappings) |*id_mapping| { 157 | id_mapping.*.hostID = id_mapping.*.containerID; 158 | id_mapping.*.containerID = runningId; 159 | runningId += id_mapping.*.size; 160 | } 161 | } 162 | 163 | fn getContainerFromArgs(file: std.fs.File, rootfs_absolute_path: []const u8, parentAllocator: std.mem.Allocator) ![*c]c.libcrun_container_t { 164 | var arena = std.heap.ArenaAllocator.init(parentAllocator); 165 | defer arena.deinit(); 166 | const allocator = arena.allocator(); 167 | 168 | var jsonReader = std.json.reader(allocator, file.reader()); 169 | 170 | // TODO: having to specify max_value_len seems like a bug 171 | var root_value = try std.json.Value.jsonParse(allocator, &jsonReader, .{ .max_value_len = 99999999 }); 172 | 173 | var args_json: *std.ArrayList(std.json.Value) = undefined; 174 | var env_json: *std.ArrayList(std.json.Value) = undefined; 175 | var mounts_json: *std.ArrayList(std.json.Value) = undefined; 176 | 177 | switch (root_value) { 178 | .object => |*object| { 179 | const processVal = object.getPtr("process") orelse @panic("no process key"); 180 | switch (processVal.*) { 181 | .object => |*process| { 182 | const argsVal = process.getPtr("args") orelse @panic("no args key"); 183 | switch (argsVal.*) { 184 | .array => |*argsArr| { 185 | args_json = argsArr; 186 | }, 187 | else => return error.InvalidJSON, 188 | } 189 | 190 | if (process.getPtr("env")) |envVal| { 191 | switch (envVal.*) { 192 | .array => |*envArr| { 193 | env_json = envArr; 194 | }, 195 | else => return error.InvalidJSON, 196 | } 197 | } else { 198 | var array = std.json.Array.init(allocator); 199 | env_json = &array; 200 | try process.put("env", std.json.Value{ .array = array }); 201 | } 202 | }, 203 | else => return error.InvalidJSON, 204 | } 205 | 206 | if (object.getPtr("mounts")) |mountsVal| { 207 | switch (mountsVal.*) { 208 | .array => |*mountsArr| { 209 | mounts_json = mountsArr; 210 | }, 211 | else => return error.InvalidJSON, 212 | } 213 | } else { 214 | var array = std.json.Array.init(allocator); 215 | mounts_json = &array; 216 | try object.put("mounts", std.json.Value{ .array = array }); 217 | } 218 | 219 | const rootVal = object.getPtr("root") orelse @panic("no root key"); 220 | switch (rootVal.*) { 221 | .object => |*root| { 222 | try root.put("path", std.json.Value{ .string = rootfs_absolute_path }); 223 | }, 224 | else => return error.InvalidJSON, 225 | } 226 | 227 | const linuxVal = object.getPtr("linux") orelse @panic("no linux key"); 228 | switch (linuxVal.*) { 229 | .object => |*linux| { 230 | // In rootfull containers uidMappings is not set 231 | if (linux.getPtr("uidMappings")) |uidMappingsVal| { 232 | const uid_map = try std.fs.cwd().readFileAlloc(allocator, "/proc/self/uid_map", 1000000); 233 | const uidMappings = try parseIdmap(allocator, uid_map); 234 | 235 | updateIdMap(uidMappings); 236 | 237 | uidMappingsVal.* = try IDMappingsToValue(allocator, uidMappings); 238 | } 239 | 240 | // In rootfull containers gidMappings is not set 241 | if (linux.getPtr("gidMappings")) |gidMappingsVal| { 242 | const gid_map = try std.fs.cwd().readFileAlloc(allocator, "/proc/self/gid_map", 1000000); 243 | const gidMappings = try parseIdmap(allocator, gid_map); 244 | 245 | updateIdMap(gidMappings); 246 | 247 | gidMappingsVal.* = try IDMappingsToValue(allocator, gidMappings); 248 | } 249 | }, 250 | else => return error.InvalidJSON, 251 | } 252 | }, 253 | else => return error.InvalidJSON, 254 | } 255 | 256 | var args = std.process.args(); 257 | _ = args.next() orelse @panic("there should be an executable"); 258 | 259 | while (args.next()) |arg| { 260 | if (eql(u8, arg, "-e") or eql(u8, arg, "--env")) { 261 | const environment_variable = args.next() orelse @panic("expected environment variable"); 262 | if (std.mem.indexOfScalar(u8, environment_variable, '=')) |_| { 263 | try env_json.append(std.json.Value{ .string = environment_variable }); 264 | } else { 265 | try env_json.append(std.json.Value{ .string = getEnvFull(environment_variable) orelse @panic("environment variable does not exist") }); 266 | } 267 | } else if (eql(u8, arg, "-v") or eql(u8, arg, "--volume")) { 268 | const volume_syntax = args.next() orelse @panic("expected volume syntax"); 269 | 270 | var mount = std.json.ObjectMap.init(allocator); 271 | 272 | var options = std.json.Array.init(allocator); 273 | try options.append(std.json.Value{ .string = "rw" }); 274 | try options.append(std.json.Value{ .string = "rbind" }); 275 | try mount.put("options", std.json.Value{ .array = options }); 276 | 277 | const separator = std.mem.indexOfScalar(u8, volume_syntax, ':') orelse @panic("no volume destination specified"); 278 | 279 | if (volume_syntax[0] == '/') { 280 | try mount.put("source", std.json.Value{ .string = volume_syntax[0..separator] }); 281 | } else { 282 | try mount.put("source", std.json.Value{ .string = try std.fs.cwd().realpathAlloc(allocator, volume_syntax[0..separator]) }); 283 | } 284 | try mount.put("destination", std.json.Value{ .string = volume_syntax[separator + 1 ..] }); 285 | 286 | try mounts_json.append(std.json.Value{ .object = mount }); 287 | } else if (eql(u8, arg, "--")) { 288 | while (args.next()) |arg_inner| { 289 | try args_json.append(std.json.Value{ .string = arg_inner }); 290 | } 291 | } else { 292 | try args_json.append(std.json.Value{ .string = arg }); 293 | } 294 | } 295 | 296 | const stringified_config = stringified_config: { 297 | var list = std.ArrayList(u8).init(allocator); 298 | errdefer list.deinit(); 299 | try std.json.stringifyArbitraryDepth(allocator, root_value, .{}, list.writer()); 300 | break :stringified_config try list.toOwnedSliceSentinel(0); 301 | }; 302 | 303 | var err: c.libcrun_error_t = null; 304 | const container = c.libcrun_container_load_from_memory(stringified_config, &err); 305 | if (container == null) { 306 | std.debug.panic("failed to load config: {s}\n", .{err.*.msg}); 307 | } 308 | 309 | return container; 310 | } 311 | 312 | fn check_unprivileged_userns_permissions() void { 313 | var sysctl_paths = [_]struct { path: []const u8, expected_value: u8, expected_value_is_set: bool }{ 314 | .{ .path = "/proc/sys/kernel/unprivileged_userns_clone", .expected_value = '1', .expected_value_is_set = true }, 315 | .{ .path = "/proc/sys/kernel/apparmor_restrict_unprivileged_userns", .expected_value = '0', .expected_value_is_set = true }, 316 | }; 317 | 318 | for (&sysctl_paths) |*sysctl_path| { 319 | if (std.fs.openFileAbsolute(sysctl_path.path, .{ .mode = .read_only })) |file| { 320 | defer file.close(); 321 | 322 | var buffer: [1]u8 = undefined; 323 | const bytes_read = file.readAll(&buffer) catch |err| std.debug.panic("failed reading {s}: {}", .{ sysctl_path.path, err }); 324 | assert(bytes_read == 1); 325 | 326 | if (buffer[0] != sysctl_path.expected_value) { 327 | sysctl_path.expected_value_is_set = false; 328 | } 329 | } else |err| { 330 | if (err != std.fs.File.OpenError.FileNotFound) { 331 | std.debug.panic("error: {}\n", .{err}); 332 | } 333 | } 334 | } 335 | 336 | if (!(sysctl_paths[0].expected_value_is_set and sysctl_paths[1].expected_value_is_set)) { 337 | std.debug.print("error: User namespace creation restricted. Run as root or disable restrictions using:\n", .{}); 338 | if (!sysctl_paths[0].expected_value_is_set) { 339 | std.debug.print("sudo sysctl -w kernel.unprivileged_userns_clone=1\n", .{}); 340 | } 341 | 342 | if (!sysctl_paths[1].expected_value_is_set) { 343 | std.debug.print("sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0\n", .{}); 344 | } 345 | 346 | std.posix.exit(1); 347 | } 348 | } 349 | 350 | fn umount(path: [*:0]const u8) void { 351 | const umountRet: i64 = @bitCast(std.os.linux.umount(path)); 352 | if (umountRet != 0) { 353 | assert(umountRet < 0 and umountRet > -4096); 354 | const errno: std.posix.E = @enumFromInt(-umountRet); 355 | std.debug.panic("Failed to unmount {s}. Errno: {}\n", .{ path, errno }); 356 | } 357 | } 358 | 359 | pub fn main() !u8 { 360 | var args = std.process.args(); 361 | const executable_path = args.next() orelse @panic("unreachable: there must be a executable name"); 362 | 363 | while (args.next()) |arg| { 364 | if (eql(u8, arg, "--dockerc-version")) { 365 | std.debug.print("dockerc version: {s}\n", .{build_info.dockerc_version}); 366 | return 0; 367 | } 368 | } 369 | 370 | var gpa = std.heap.GeneralPurposeAllocator(.{}){}; 371 | defer _ = gpa.deinit(); 372 | const allocator = gpa.allocator(); 373 | 374 | // TODO: consider the case where a user can mount the filesystem but isn't root 375 | // We might only need to check for CAP_SYS_ADMIN 376 | // Also in the case where fusermount3 is present this is unnecessary 377 | const euid = std.os.linux.geteuid(); 378 | if (euid != 0) { 379 | // So that fuse filesystems can be mounted without needing fusermount3 380 | 381 | const egid = std.os.linux.getegid(); 382 | 383 | const username = try allocator.dupeZ(u8, std.mem.span((std.c.getpwuid(euid) orelse @panic("couldn't get username")).pw_name orelse @panic("couldn't get username"))); 384 | defer allocator.free(username); 385 | 386 | var subuid_ranges: [*]c.subid_range = undefined; 387 | var subgid_ranges: [*]c.subid_range = undefined; 388 | 389 | var uid_mappings = std.ArrayList(IDMapping).init(allocator); 390 | defer uid_mappings.deinit(); 391 | 392 | try uid_mappings.append(IDMapping{ 393 | .containerID = 0, 394 | .hostID = euid, 395 | .size = 1, 396 | }); 397 | 398 | var gid_mappings = std.ArrayList(IDMapping).init(allocator); 399 | defer gid_mappings.deinit(); 400 | 401 | try gid_mappings.append(IDMapping{ 402 | .containerID = 0, 403 | .hostID = egid, 404 | .size = 1, 405 | }); 406 | 407 | const subuid_ranges_len = c.subid_get_uid_ranges(username, @ptrCast(&subuid_ranges)); 408 | const subgid_ranges_len = c.subid_get_gid_ranges(username, @ptrCast(&subgid_ranges)); 409 | 410 | if (subuid_ranges_len > 0) { 411 | for (0..@intCast(subuid_ranges_len)) |i| { 412 | try uid_mappings.append(IDMapping{ 413 | .containerID = @intCast(subuid_ranges[i].start), 414 | .hostID = @intCast(subuid_ranges[i].start), 415 | .size = @intCast(subuid_ranges[i].count), 416 | }); 417 | } 418 | } 419 | 420 | if (subgid_ranges_len > 0) { 421 | for (0..@intCast(subgid_ranges_len)) |i| { 422 | try gid_mappings.append(IDMapping{ 423 | .containerID = @intCast(subgid_ranges[i].start), 424 | .hostID = @intCast(subgid_ranges[i].start), 425 | .size = @intCast(subgid_ranges[i].count), 426 | }); 427 | } 428 | } 429 | 430 | const pipe = try std.posix.pipe(); 431 | const read_fd = pipe[0]; 432 | const write_fd = pipe[1]; 433 | 434 | const pid: i64 = @bitCast(std.os.linux.clone2(std.os.linux.CLONE.NEWUSER | std.os.linux.CLONE.NEWNS | std.os.linux.SIG.CHLD, 0)); 435 | if (pid < 0) { 436 | std.debug.panic("failed to clone process: {}\n", .{std.posix.errno(pid)}); 437 | } 438 | 439 | if (pid > 0) { 440 | std.posix.close(read_fd); 441 | // inside parent process 442 | 443 | const set_groups_file = try std.fmt.allocPrint(allocator, "/proc/{}/setgroups", .{pid}); 444 | defer allocator.free(set_groups_file); 445 | 446 | newuidmap(allocator, pid, uid_mappings.items) catch { 447 | std.debug.print("newuidmap failed, falling back to single user mapping\n", .{}); 448 | const uid_map_path = try std.fmt.allocPrint(allocator, "/proc/{}/uid_map", .{pid}); 449 | defer allocator.free(uid_map_path); 450 | 451 | const uid_map_content = try std.fmt.allocPrint(allocator, "0 {} 1", .{euid}); 452 | defer allocator.free(uid_map_content); 453 | std.fs.cwd().writeFile(.{ .sub_path = uid_map_path, .data = uid_map_content }) catch |err| { 454 | if (err == std.posix.WriteError.AccessDenied) { 455 | // TODO: when using newuidmap this may not get hit until 456 | // trying to mount file system 457 | check_unprivileged_userns_permissions(); 458 | } 459 | std.debug.panic("error: {}\n", .{err}); 460 | }; 461 | }; 462 | 463 | newgidmap(allocator, pid, gid_mappings.items) catch { 464 | std.debug.print("newgidmap failed, falling back to single group mapping\n", .{}); 465 | 466 | // must be set for writing to gid_map to succeed (see user_namespaces(7)) 467 | // otherwise we want to leave it untouched so that setgroups can be used in the container 468 | try std.fs.cwd().writeFile(.{ .sub_path = set_groups_file, .data = "deny" }); 469 | 470 | const gid_map_path = try std.fmt.allocPrint(allocator, "/proc/{}/gid_map", .{pid}); 471 | defer allocator.free(gid_map_path); 472 | 473 | const gid_map_content = try std.fmt.allocPrint(allocator, "0 {} 1", .{egid}); 474 | defer allocator.free(gid_map_content); 475 | std.fs.cwd().writeFile(.{ .sub_path = gid_map_path, .data = gid_map_content }) catch |err| { 476 | if (err == std.posix.WriteError.AccessDenied) { 477 | check_unprivileged_userns_permissions(); 478 | } 479 | std.debug.panic("error: {}\n", .{err}); 480 | }; 481 | }; 482 | 483 | std.posix.close(write_fd); 484 | const wait_result = std.posix.waitpid(@intCast(pid), 0); 485 | if (std.os.linux.W.IFEXITED(wait_result.status)) { 486 | return std.os.linux.W.EXITSTATUS(wait_result.status); 487 | } 488 | std.debug.panic("did not exit normally status: {}\n", .{wait_result.status}); 489 | } 490 | 491 | std.posix.close(write_fd); 492 | 493 | var buf: [1]u8 = undefined; 494 | const bytes_read = try std.posix.read(read_fd, &buf); 495 | assert(bytes_read == 0); 496 | std.posix.close(read_fd); 497 | } 498 | 499 | var temp_dir_path = "/tmp/dockerc-XXXXXX".*; 500 | try mkdtemp(&temp_dir_path); 501 | 502 | const filesystem_bundle_dir_null = try std.fmt.allocPrintZ(allocator, "{s}/{s}", .{ temp_dir_path, "bundle.squashfs" }); 503 | defer allocator.free(filesystem_bundle_dir_null); 504 | 505 | try std.fs.makeDirAbsolute(filesystem_bundle_dir_null); 506 | 507 | const mount_dir_path = try std.fmt.allocPrintZ(allocator, "{s}/mount", .{temp_dir_path}); 508 | defer allocator.free(mount_dir_path); 509 | 510 | const footer = try common.getFooter(executable_path); 511 | const offsetArg = try std.fmt.allocPrintZ(allocator, "offset={}", .{footer.offset}); 512 | defer allocator.free(offsetArg); 513 | 514 | const args_buf = [_:null]?[*:0]const u8{ "squashfuse", "-o", offsetArg, executable_path, filesystem_bundle_dir_null }; 515 | 516 | { 517 | const pid = try std.posix.fork(); 518 | if (pid == 0) { 519 | std.process.exit(@intCast(squashfuse_main(args_buf.len, &args_buf))); 520 | } 521 | 522 | const wait_pid_result = std.posix.waitpid(pid, 0); 523 | if (wait_pid_result.status != 0) { 524 | // TODO: extract instead of failing 525 | std.debug.panic("failed to run squashfuse", .{}); 526 | } 527 | } 528 | 529 | const overlayfs_options = try std.fmt.allocPrintZ(allocator, "lowerdir={s},upperdir={s}/upper,workdir={s}/work", .{ 530 | filesystem_bundle_dir_null, 531 | temp_dir_path, 532 | temp_dir_path, 533 | }); 534 | defer allocator.free(overlayfs_options); 535 | 536 | const container = container: { 537 | // Indent so that handles to files in mounted dir are closed by the end 538 | // to avoid umounting from being blocked. 539 | var tmpDir = try std.fs.openDirAbsolute(&temp_dir_path, .{}); 540 | defer tmpDir.close(); 541 | try tmpDir.makeDir("upper"); 542 | try tmpDir.makeDir("work"); 543 | try tmpDir.makeDir("mount"); 544 | 545 | const overlayfs_args = [_:null]?[*:0]const u8{ "fuse-overlayfs", "-o", overlayfs_options, mount_dir_path }; 546 | 547 | // reap the child of fuse-overlayfs so that we can be sure fuse-overlayfs 548 | // has exited before unmounting squashfuse 549 | assert(try std.posix.prctl(std.posix.PR.SET_CHILD_SUBREAPER, .{1}) == 0); 550 | const pid = try std.posix.fork(); 551 | if (pid == 0) { 552 | _ = overlayfs_main(overlayfs_args.len, &overlayfs_args); 553 | std.debug.panic("unreachable", .{}); 554 | } 555 | 556 | const wait_pid_result = std.posix.waitpid(pid, 0); 557 | assert(try std.posix.prctl(std.posix.PR.SET_CHILD_SUBREAPER, .{0}) == 0); 558 | 559 | if (wait_pid_result.status != 0) { 560 | std.debug.panic("failed to run overlayfs", .{}); 561 | } 562 | 563 | const rootfs_absolute_path = try std.fmt.allocPrint(allocator, "{s}/mount/rootfs", .{temp_dir_path}); 564 | defer allocator.free(rootfs_absolute_path); 565 | 566 | const file = try tmpDir.openFile("mount/config.json", .{ .mode = .read_only }); 567 | defer file.close(); 568 | 569 | break :container try getContainerFromArgs(file, rootfs_absolute_path, allocator); 570 | }; 571 | defer c.libcrun_container_free(container); 572 | 573 | var crun_context = c.libcrun_context_t{ 574 | .bundle = mount_dir_path, 575 | .id = temp_dir_path[13..], 576 | .fifo_exec_wait_fd = -1, 577 | .preserve_fds = 0, 578 | .listen_fds = 0, 579 | }; 580 | 581 | var err: c.libcrun_error_t = null; 582 | if (c.libcrun_init_logging(&crun_context.output_handler, &crun_context.output_handler_arg, crun_context.id, null, &err) < 0) { 583 | std.debug.panic("unreachable but not using the unreachable keyword for forward compatibility", .{}); 584 | } 585 | 586 | crun_context.handler_manager = c.libcrun_handler_manager_create(&err); 587 | if (crun_context.handler_manager == null) { 588 | std.debug.panic("failed to create handler manager ({d}): {s}\n", .{ err.*.status, err.*.msg }); 589 | } 590 | 591 | // if XDG_RUNTIME_DIR is not set then /run/crun is used as the default which 592 | // fails because most users do not have write permission there 593 | assert(c.setenv("XDG_RUNTIME_DIR", "/tmp", 0) == 0); 594 | 595 | const pid = try std.posix.fork(); 596 | assert(pid >= 0); 597 | if (pid == 0) { 598 | // Run container in a separate process because crun will try to reap 599 | // every child including the fuse-overlayfs process still running 600 | const ret = c.libcrun_container_run(&crun_context, container, 0, &err); 601 | 602 | if (err != null) { 603 | std.debug.panic("failed to run container (status/errno: {}) ({d}): {s}\n", .{ err.*.status, ret, err.*.msg }); 604 | } 605 | 606 | return @intCast(ret); 607 | } 608 | 609 | const retStatus = std.posix.waitpid(pid, 0); 610 | if (!std.posix.W.IFEXITED(retStatus.status)) { 611 | std.debug.panic("container didn't exist normally : {}\n", .{retStatus.status}); 612 | } 613 | 614 | umount(mount_dir_path); 615 | 616 | // wait for overlayfs process to finish so that device is not busy to unmount squashfuse 617 | const overlayfs_status = std.posix.waitpid(-1, 0); 618 | if (!std.posix.W.IFEXITED(overlayfs_status.status) or std.posix.W.EXITSTATUS(overlayfs_status.status) != 0) { 619 | std.debug.panic("overlayfs failed to exit successfully, status: {}\n", .{overlayfs_status.status}); 620 | } 621 | 622 | umount(filesystem_bundle_dir_null); 623 | 624 | try std.fs.deleteTreeAbsolute(&temp_dir_path); 625 | 626 | return std.posix.W.EXITSTATUS(retStatus.status); 627 | } 628 | -------------------------------------------------------------------------------- /src/replace.zig: -------------------------------------------------------------------------------- 1 | const runtimes = @import("runtimes.zig"); 2 | const assert = std.debug.assert; 3 | const std = @import("std"); 4 | const common = @import("common.zig"); 5 | 6 | pub fn main() !void { 7 | var args = std.process.args(); 8 | assert(args.skip()); 9 | const rawPath = args.next(); 10 | const rawPathOutput = args.next(); 11 | 12 | if (rawPath) |path| { 13 | if (rawPathOutput) |path_output| { 14 | const offset = (try common.getFooter(path)).offset; 15 | 16 | const readFile = try std.fs.cwd().openFile(path, .{}); 17 | const writeFile = try std.fs.cwd().createFile(path_output, .{}); 18 | 19 | try writeFile.writeAll(runtimes.runtime_content_x86_64); 20 | const len_to_write = try readFile.getEndPos() - offset - 8; 21 | const len_written = try std.fs.File.copyRange(readFile, offset, writeFile, try writeFile.getPos(), len_to_write); 22 | assert(len_to_write == len_written); 23 | 24 | try writeFile.seekFromEnd(0); 25 | 26 | try common.writeFooter(writeFile, common.Footer{ 27 | .offset = runtimes.runtime_content_x86_64.len, 28 | }); 29 | 30 | try writeFile.chmod(0o755); 31 | 32 | writeFile.close(); 33 | readFile.close(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/runtimes.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | 3 | pub const runtime_content_x86_64 = @embedFile("runtime_x86_64"); 4 | pub const runtime_content_aarch64 = @embedFile("runtime_aarch64"); 5 | -------------------------------------------------------------------------------- /src/tools/policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "default": [ 3 | { 4 | "type": "insecureAcceptAnything" 5 | } 6 | ] 7 | } 8 | --------------------------------------------------------------------------------