Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
openSUSE:Leap:15.4:Update
greetd
greetd-0.8.0.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File greetd-0.8.0.obscpio of Package greetd
07070100000000000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001500000000greetd-0.8.0/.builds07070100000001000081A40000000000000000000000016135173A00000100000000000000000000000000000000000000002000000000greetd-0.8.0/.builds/alpine.ymlimage: alpine/edge packages: - cargo - linux-pam-dev sources: - https://git.sr.ht/~kennylevinsen/greetd tasks: - test: | cd greetd cargo check --locked --all-targets --all-features cargo test --locked --all-targets --all-features 07070100000002000081A40000000000000000000000016135173A0000012B000000000000000000000000000000000000002300000000greetd-0.8.0/.builds/archlinux.ymlimage: archlinux packages: - rust sources: - https://git.sr.ht/~kennylevinsen/greetd tasks: - rustfmt-check: | cd greetd cargo fmt -- --check - test: | cd greetd cargo check --locked --all-targets --all-features cargo test --locked --all-targets --all-features 07070100000003000081A40000000000000000000000016135173A00000013000000000000000000000000000000000000001800000000greetd-0.8.0/.gitignore/target **/*.rs.bk 07070100000004000081A40000000000000000000000016135173A00002675000000000000000000000000000000000000001800000000greetd-0.8.0/Cargo.lock# This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "agreety" version = "0.8.0" dependencies = [ "enquote", "getopts", "greetd_ipc", "inish", "nix", "rpassword", ] [[package]] name = "arc-swap" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b585a98a234c46fc563103e9278c9391fde1f4e6850334da895d27edb9580f62" [[package]] name = "async-trait" version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26c4f3195085c36ea8d24d32b2f828d23296a9370a28aa39d111f6f16bef9f3b" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "autocfg" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" [[package]] name = "bitflags" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" [[package]] name = "bytes" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" [[package]] name = "cc" version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "404b1fe4f65288577753b17e3b36a04596ee784493ec249bf81c7f2d2acd751c" [[package]] name = "cfg-if" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "enquote" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ec878a5d2f3b6e9eaee72373dd23414cfc7d353104741471bec712ef241a66e" [[package]] name = "fakegreet" version = "0.8.0" dependencies = [ "greetd_ipc", "serde", "thiserror", "tokio", ] [[package]] name = "getopts" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" dependencies = [ "unicode-width", ] [[package]] name = "greetd" version = "0.8.0" dependencies = [ "async-trait", "enquote", "getopts", "greetd_ipc", "inish", "libc", "nix", "pam-sys", "serde", "serde_json", "thiserror", "tokio", "users", ] [[package]] name = "greetd_ipc" version = "0.8.0" dependencies = [ "async-trait", "serde", "serde_json", "thiserror", "tokio", ] [[package]] name = "inish" version = "0.1.0" [[package]] name = "itoa" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" [[package]] name = "libc" version = "0.2.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89203f3fba0a3795506acaad8ebce3c80c0af93f994d5a1d7a0b1eeb23271929" [[package]] name = "log" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" dependencies = [ "cfg-if 0.1.10", ] [[package]] name = "memchr" version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" [[package]] name = "mio" version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e50ae3f04d169fcc9bde0b547d1c205219b7157e07ded9c5aff03e0637cb3ed7" dependencies = [ "libc", "log", "miow", "ntapi", "winapi", ] [[package]] name = "miow" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a33c1b55807fbed163481b5ba66db4b2fa6cde694a5027be10fb724206c5897" dependencies = [ "socket2", "winapi", ] [[package]] name = "nix" version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ccba0cfe4fdf15982d1674c69b1fd80bad427d293849982668dfe454bd61f2" dependencies = [ "bitflags", "cc", "cfg-if 1.0.0", "libc", ] [[package]] name = "ntapi" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a31937dea023539c72ddae0e3571deadc1414b300483fa7aaec176168cfa9d2" dependencies = [ "winapi", ] [[package]] name = "once_cell" version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13bd41f508810a131401606d54ac32a467c97172d74ba7662562ebba5ad07fa0" [[package]] name = "pam-sys" version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd4858311a097f01a0006ef7d0cd50bca81ec430c949d7bf95cbefd202282434" dependencies = [ "libc", ] [[package]] name = "pin-project-lite" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439697af366c49a6d0a010c56a0d97685bc140ce0d377b13a2ea2aa42d64a827" [[package]] name = "proc-macro2" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8872cf6f48eee44265156c111456a700ab3483686b3f96df4cf5481c89157319" dependencies = [ "unicode-xid", ] [[package]] name = "quote" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42934bc9c8ab0d3b273a16d8551c8f0fcff46be73276ca083ec2414c15c4ba5e" dependencies = [ "proc-macro2", ] [[package]] name = "rpassword" version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d755237fc0f99d98641540e66abac8bc46a0652f19148ac9e21de2da06b326c9" dependencies = [ "libc", "winapi", ] [[package]] name = "ryu" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed3d612bc64430efeb3f7ee6ef26d590dce0c43249217bddc62112540c7941e1" [[package]] name = "serde" version = "1.0.110" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99e7b308464d16b56eba9964e4972a3eee817760ab60d88c3f86e1fecb08204c" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.110" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818fbf6bfa9a42d3bfcaca148547aa00c7b915bec71d1757aa2d44ca68771984" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993948e75b189211a9b31a7528f950c6adc21f9720b6438ff80a7fa2f864cea2" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "signal-hook-registry" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94f478ede9f64724c5d173d7bb56099ec3e2d9fc2774aac65d34b8b890405f41" dependencies = [ "arc-swap", "libc", ] [[package]] name = "socket2" version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" dependencies = [ "cfg-if 1.0.0", "libc", "winapi", ] [[package]] name = "syn" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4696caa4048ac7ce2bcd2e484b3cef88c1004e41b8e945a277e2c25dc0b72060" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "thiserror" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "467e5ff447618a916519a4e0d62772ab14f434897f3d63f05d8700ef1e9b22c1" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e63c1091225b9834089b429bc4a2e01223470e3183e891582909e9d1c4cb55d9" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tokio" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ca04cec6ff2474c638057b65798f60ac183e5e79d3448bb7163d36a39cff6ec" dependencies = [ "autocfg", "bytes", "libc", "memchr", "mio", "once_cell", "pin-project-lite", "signal-hook-registry", "tokio-macros", "winapi", ] [[package]] name = "tokio-macros" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42517d2975ca3114b22a16192634e8241dc5cc1f130be194645970cc1c371494" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "unicode-width" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" [[package]] name = "unicode-xid" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" [[package]] name = "users" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24cc0f6d6f267b73e5a2cadf007ba8f9bc39c6a6f9666f8cf25ea809a153b032" dependencies = [ "libc", "log", ] [[package]] name = "winapi" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 07070100000005000081A40000000000000000000000016135173A000000D4000000000000000000000000000000000000001800000000greetd-0.8.0/Cargo.toml[profile.dev] panic = "abort" [profile.release] lto = "fat" panic = "abort" opt-level = 'z' incremental = false codegen-units = 1 [workspace] members = ["inish", "greetd_ipc", "greetd", "agreety", "fakegreet"] 07070100000006000081A40000000000000000000000016135173A0000894D000000000000000000000000000000000000001500000000greetd-0.8.0/LICENSE GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>. 07070100000007000081A40000000000000000000000016135173A000009CD000000000000000000000000000000000000001700000000greetd-0.8.0/README.md# greetd greetd is a minimal and flexible login manager daemon that makes no assumptions about what you want to launch. Use [gtkgreet](https://git.sr.ht/~kennylevinsen/gtkgreet) to launch [sway](https://github.com/swaywm/sway) if you want a fully graphical session, or use `agreety` to launch a shell if you want a drop-in replacement for `agetty(8)` and `login(1)`. If you can run it from your shell in a TTY, greetd can start it. If it can be taught to speak a simple JSON-based IPC protocol, then it can be a greeter. See the [wiki](https://man.sr.ht/~kennylevinsen/greetd) for FAQ, guides for common configurations, and troubleshooting information. ## List of known greetd greeters - agreety - The simple, text-based greeter living in this repo is a simple example. - [gtkgreet](https://git.sr.ht/~kennylevinsen/gtkgreet) - The flagship graphical, GTK based greeter (xdg-shell or wlr-layer-shell, to be used with something like `cage`) - [dlm](https://git.sr.ht/~kennylevinsen/dlm) - Dumb Login Manager (using fbdev) - [wlgreet](https://git.sr.ht/~kennylevinsen/wlgreet) - Wayland greeter (using wlr-layer-shell, to be used with something like `sway`) - [tuigreet](https://github.com/apognu/tuigreet) - Console UI greeter (using tui-rs) ## Installation The below will install greetd, agreety and the default configuration. This looks *just* like `agetty(8)` and `login(1)`. See the manpages and the wiki for information on how to do more interesting things. ### From packages #### Arch Linux greetd and a few greeters are available in AUR for Arch Linux. #### Gentoo ```sh emerge gui-libs/greetd ``` ### Manually from source ```sh # Compile greetd and agreety. cargo build --release # Put things into place sudo cp target/release/{greetd,agreety} /usr/local/bin/ sudo cp greetd.service /etc/systemd/system/greetd.service mkdir /etc/greetd cp config.toml /etc/greetd/config.toml # Create the greeter user sudo useradd -M -G video greeter sudo chmod -R go+r /etc/greetd/ # Look in the configuration file `/etc/greetd/config.toml` and edit as appropriate. # When done, enable and start greetd systemctl enable --now greetd ``` ## How do I write my own greeter? All you need to do is an application that can speak the greetd IPC protocol, which is documented in `greetd-ipc(7)`. See gtkgreet or agreety for inspiration. # How to discuss Go to #kennylevinsen @ irc.libera.chat to discuss, or use [~kennylevinsen/greetd-devel@lists.sr.ht](https://lists.sr.ht/~kennylevinsen/greetd-devel). 07070100000008000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001500000000greetd-0.8.0/agreety07070100000009000081A40000000000000000000000016135173A00000184000000000000000000000000000000000000002000000000greetd-0.8.0/agreety/Cargo.toml[package] name = "agreety" version = "0.8.0" authors = ["Kenny Levinsen"] edition = "2018" license = "GPL-3.0" homepage = "https://kl.wtf/projects/agreety" repository = "https://git.sr.ht/~kennylevinsen/greetd/" [dependencies] greetd_ipc = { path = "../greetd_ipc", features = ["sync-codec"]} inish = { path = "../inish"} rpassword = "5.0" getopts = "0.2" enquote = "1.0.3" nix = "0.19" 0707010000000A000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001900000000greetd-0.8.0/agreety/src0707010000000B000081A40000000000000000000000016135173A000016B4000000000000000000000000000000000000002100000000greetd-0.8.0/agreety/src/main.rsuse std::{ env, fs, io::{self, BufRead}, os::unix::net::UnixStream, }; use enquote::unquote; use getopts::Options; use nix::sys::utsname::uname; use rpassword::prompt_password_stderr; use greetd_ipc::{codec::SyncCodec, AuthMessageType, ErrorType, Request, Response}; fn maybe_unquote(s: &str) -> Result<String, Box<dyn std::error::Error>> { Ok(match s.chars().next() { Some('"') | Some('\'') => unquote(s)?, _ => s.to_string(), }) } fn prompt_stderr(prompt: &str) -> Result<String, Box<dyn std::error::Error>> { let stdin = io::stdin(); let mut stdin_iter = stdin.lock().lines(); eprint!("{}", prompt); Ok(stdin_iter.next().unwrap()?) } fn get_distro_name() -> Result<String, Box<dyn std::error::Error>> { let os_release = fs::read_to_string("/etc/os-release")?; let parsed = inish::parse(&os_release)?; let general = parsed.get("").ok_or("no general section")?; Ok(maybe_unquote( general.get("PRETTY_NAME").ok_or("no pretty name")?, )?) } fn get_issue() -> Result<String, Box<dyn std::error::Error>> { let vtnr: usize = env::var("XDG_VTNR") .unwrap_or_else(|_| "0".to_string()) .parse() .expect("unable to parse VTNR"); let uts = uname(); Ok(fs::read_to_string("/etc/issue")? .replace( "\\S", &get_distro_name().unwrap_or_else(|_| "Linux".to_string()), ) .replace("\\l", &format!("tty{}", vtnr)) .replace("\\s", &uts.sysname()) .replace("\\r", &uts.release()) .replace("\\v", &uts.version()) .replace("\\n", &uts.nodename()) .replace("\\m", &uts.machine()) .replace("\\\\", "\\")) } enum LoginResult { Success, Failure, } fn login(node: &str, cmd: &mut Option<String>) -> Result<LoginResult, Box<dyn std::error::Error>> { let username = loop { let username = prompt_stderr(&format!("{} login: ", node))?; if username.starts_with('!') { *cmd = Some(username[1..].to_string()); eprintln!("Login command changed to: {}", &username[1..]); continue; } break username; }; let mut stream = UnixStream::connect(env::var("GREETD_SOCK")?)?; let mut next_request = Request::CreateSession { username }; let mut starting = false; loop { next_request.write_to(&mut stream)?; match Response::read_from(&mut stream)? { Response::AuthMessage { auth_message, auth_message_type, } => { let response = match auth_message_type { AuthMessageType::Visible => Some(prompt_stderr(&auth_message)?), AuthMessageType::Secret => Some(prompt_password_stderr(&auth_message)?), AuthMessageType::Info => { eprintln!("info: {}", auth_message); None } AuthMessageType::Error => { eprintln!("error: {}", auth_message); None } }; next_request = Request::PostAuthMessageResponse { response }; } Response::Success => { if starting { return Ok(LoginResult::Success); } else { starting = true; let command = match cmd { Some(cmd) => cmd.clone(), None => prompt_stderr("Command: ")?, }; next_request = Request::StartSession { cmd: vec![command.to_string()], } } } Response::Error { error_type, description, } => { Request::CancelSession.write_to(&mut stream)?; match error_type { ErrorType::AuthError => return Ok(LoginResult::Failure), ErrorType::Error => { return Err(format!("login error: {:?}", description).into()) } } } } } } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); } fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optopt("c", "cmd", "command to run", "COMMAND"); opts.optopt( "f", "max-failures", "maximum number of accepted failures", "FAILURES", ); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { println!("{}", f.to_string()); print_usage(&program, opts); std::process::exit(1); } }; if matches.opt_present("h") { print_usage(&program, opts); std::process::exit(0); } let mut cmd = matches.opt_default("cmd", ""); let max_failures: usize = match matches.opt_get("max-failures") { Ok(v) => v.unwrap_or(5), Err(e) => { eprintln!("unable to parse max failures: {}", e); std::process::exit(1) } }; if let Ok(issue) = get_issue() { print!("{}", issue); } let uts = uname(); for _ in 0..max_failures { match login(uts.nodename(), &mut cmd) { Ok(LoginResult::Success) => break, Ok(LoginResult::Failure) => eprintln!("Login incorrect\n"), Err(e) => { eprintln!("error: {}", e); std::process::exit(1); } } } } 0707010000000C000081A40000000000000000000000016135173A00000216000000000000000000000000000000000000001900000000greetd-0.8.0/config.toml[terminal] # The VT to run the greeter on. Can be "next", "current" or a number # designating the VT. vt = 1 # The default session, also known as the greeter. [default_session] # `agreety` is the bundled agetty/login-lookalike. You can replace `$SHELL` # with whatever you want started, such as `sway`. command = "agreety --cmd $SHELL" # The user to run the command as. The privileges this user must have depends # on the greeter. A graphical greeter may for example require the user to be # in the `video` group. user = "greeter" 0707010000000D000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001700000000greetd-0.8.0/fakegreet0707010000000E000081A40000000000000000000000016135173A00000013000000000000000000000000000000000000002200000000greetd-0.8.0/fakegreet/.gitignore/target **/*.rs.bk 0707010000000F000081A40000000000000000000000016135173A000001A2000000000000000000000000000000000000002200000000greetd-0.8.0/fakegreet/Cargo.toml[package] name = "fakegreet" version = "0.8.0" authors = ["Kenny Levinsen"] edition = "2018" license = "GPL-3.0" homepage = "https://kl.wtf/projects/greetd" repository = "https://git.sr.ht/~kennylevinsen/greetd/" [dependencies] serde = { version = "1.0", features = ["derive"] } greetd_ipc = { path = "../greetd_ipc", features = ["tokio-codec"] } tokio = { version = "1.0", features = ["process"] } thiserror = "1.0" 07070100000010000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001B00000000greetd-0.8.0/fakegreet/src07070100000011000081A40000000000000000000000016135173A00000532000000000000000000000000000000000000002400000000greetd-0.8.0/fakegreet/src/error.rsuse std::convert::From; use serde::{Deserialize, Serialize}; use thiserror::Error as ThisError; #[derive(Debug, ThisError, Clone, Deserialize, Serialize)] pub enum Error { #[error("{0}")] Error(String), #[error("authentication error: {0}")] AuthError(String), #[error("protocol error: {0}")] ProtocolError(String), #[error("i/o error: {0}")] Io(String), #[error("configuration error: {0}")] ConfigError(String), } impl From<Box<dyn std::error::Error>> for Error { fn from(error: Box<dyn std::error::Error>) -> Self { Error::Error(format!("{}", error)) } } impl From<std::io::Error> for Error { fn from(error: std::io::Error) -> Self { Error::Io(format!("{}", error)) } } impl From<greetd_ipc::codec::Error> for Error { fn from(error: greetd_ipc::codec::Error) -> Self { match error { greetd_ipc::codec::Error::Serialization(s) => Error::ProtocolError(s), greetd_ipc::codec::Error::Io(s) => Error::Io(s), greetd_ipc::codec::Error::Eof => Error::Io("EOF".to_string()), } } } impl From<String> for Error { fn from(error: String) -> Self { Error::Error(error) } } impl From<&str> for Error { fn from(error: &str) -> Self { Error::Error(error.to_string()) } } 07070100000012000081A40000000000000000000000016135173A00001504000000000000000000000000000000000000002300000000greetd-0.8.0/fakegreet/src/main.rsmod error; use std::{cell::RefCell, env, rc::Rc, time::Duration}; use tokio::{ net::{UnixListener, UnixStream}, process::Command, task, time::sleep, }; use crate::error::Error; use greetd_ipc::{ codec::{Error as CodecError, TokioCodec}, AuthMessageType, ErrorType, Request, Response, }; fn wrap_result<T>(res: Result<T, Error>) -> Response { match res { Ok(_) => Response::Success, Err(Error::AuthError(msg)) => Response::Error { error_type: ErrorType::AuthError, description: msg, }, Err(e) => Response::Error { error_type: ErrorType::Error, description: format!("{}", e), }, } } struct InnerContext { user: Option<String>, password: Option<String>, ok: bool, } struct Context { inner: RefCell<InnerContext>, } impl Context { fn new() -> Context { Context { inner: RefCell::new(InnerContext { user: None, password: None, ok: false, }), } } async fn create_session(&self, username: String) -> Result<(), Error> { self.inner.borrow_mut().user = Some(username); Ok(()) } async fn get_question(&self) -> Result<Option<(AuthMessageType, String)>, Error> { let s = self.inner.borrow(); if s.ok { Ok(None) } else if s.user.is_none() { Ok(Some((AuthMessageType::Visible, "User:".to_string()))) } else if s.password.is_none() { Ok(Some((AuthMessageType::Secret, "Password:".to_string()))) } else { Ok(Some((AuthMessageType::Visible, "7 + 2:".to_string()))) } } async fn post_response(&self, response: Option<String>) -> Result<(), Error> { let mut s = self.inner.borrow_mut(); if s.ok { return Err(Error::Error("wat".to_string())); } if s.user.is_none() { s.user = response; } else if s.password.is_none() { s.password = response; } else { if s.user != Some("user".to_string()) || s.password != Some("password".to_string()) || response != Some("9".to_string()) { sleep(Duration::from_millis(2000)).await; return Err(Error::AuthError("nope".to_string())); } s.ok = true; } Ok(()) } async fn start(&self, _cmd: Vec<String>) -> Result<(), Error> { if !self.inner.borrow().ok { return Err(Error::Error("not yet dammit".to_string())); } sleep(Duration::from_millis(5000)).await; Ok(()) } async fn cancel(&self) -> Result<(), Error> { let mut s = self.inner.borrow_mut(); s.user = None; s.password = None; s.ok = false; Ok(()) } } async fn client_get_question(ctx: &Context) -> Response { match ctx.get_question().await { Ok(Some((auth_message_type, auth_message))) => Response::AuthMessage { auth_message_type, auth_message, }, res => wrap_result(res), } } async fn client_handler(ctx: &Context, mut s: UnixStream) -> Result<(), Error> { loop { let req = match Request::read_from(&mut s).await { Ok(req) => req, Err(CodecError::Eof) => return Ok(()), Err(e) => return Err(e.into()), }; println!("req: {:?}", req); let resp = match req { Request::CreateSession { username } => match ctx.create_session(username).await { Ok(()) => client_get_question(&ctx).await, res => wrap_result(res), }, Request::PostAuthMessageResponse { response } => { match ctx.post_response(response).await { Ok(()) => client_get_question(&ctx).await, res => wrap_result(res), } } Request::StartSession { cmd } => wrap_result(ctx.start(cmd).await), Request::CancelSession => wrap_result(ctx.cancel().await), }; println!("resp: {:?}", resp); resp.write_to(&mut s).await?; } } pub async fn server() -> Result<(), Error> { let path = "./greetd.sock"; std::env::set_var("GREETD_SOCK", path); let _ = std::fs::remove_file(path); let listener = UnixListener::bind(path).map_err(|e| format!("unable to open listener: {}", e))?; let arg = env::args().nth(1).expect("need argument"); let _ = Command::new("sh").arg("-c").arg(arg).spawn()?; let ctx = Rc::new(Context::new()); loop { match listener.accept().await { Ok((stream, _)) => { let ctx = ctx.clone(); task::spawn_local(async move { if let Err(e) = client_handler(&ctx, stream).await { eprintln!("client loop failed: {}", e); } }); } Err(err) => return Err(format!("accept: {}", err).into()), } } } #[tokio::main(flavor = "current_thread")] async fn main() { let res = task::LocalSet::new() .run_until(async move { server().await }) .await; if let Err(e) = res { eprintln!("error: {}", e); } } 07070100000013000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001400000000greetd-0.8.0/greetd07070100000014000081ED0000000000000000000000016135173A00000172000000000000000000000000000000000000001C00000000greetd-0.8.0/greetd.service[Unit] Description=Greeter daemon After=systemd-user-sessions.service plymouth-quit-wait.service After=getty@tty1.service Conflicts=getty@tty1.service [Service] Type=simple ExecStart=greetd IgnoreSIGPIPE=no SendSIGHUP=yes TimeoutStopSec=30s KeyringMode=shared Restart=always RestartSec=1 StartLimitBurst=5 StartLimitInterval=30 [Install] Alias=display-manager.service 07070100000015000081A40000000000000000000000016135173A00000013000000000000000000000000000000000000001F00000000greetd-0.8.0/greetd/.gitignore/target **/*.rs.bk 07070100000016000081A40000000000000000000000016135173A0000028B000000000000000000000000000000000000001F00000000greetd-0.8.0/greetd/Cargo.toml[package] name = "greetd" version = "0.8.0" authors = ["Kenny Levinsen"] edition = "2018" license = "GPL-3.0" homepage = "https://kl.wtf/projects/greetd" repository = "https://git.sr.ht/~kennylevinsen/greetd/" [features] debug = [] [dependencies] nix = "0.19" pam-sys = "0.5.6" users = "0.11.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" greetd_ipc = { path = "../greetd_ipc", features = ["tokio-codec"] } inish = { path = "../inish" } libc = "0.2" tokio = { version = "1.0", features = ["net", "sync", "macros", "signal", "rt", "io-util", "time"] } getopts = "0.2" thiserror = "1.0" async-trait = "0.1" enquote = "1.0.3" 07070100000017000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001800000000greetd-0.8.0/greetd/src07070100000018000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001F00000000greetd-0.8.0/greetd/src/config07070100000019000081A40000000000000000000000016135173A00003D8D000000000000000000000000000000000000002600000000greetd-0.8.0/greetd/src/config/mod.rsuse std::{collections::HashMap, default::Default, env, fs::read_to_string}; use enquote::unquote; use getopts::Options; use super::error::Error; const RUNFILE: &str = "/run/greetd.run"; #[derive(Debug, Eq, PartialEq)] pub enum VtSelection { Next, Current, None, Specific(usize), } impl Default for VtSelection { fn default() -> Self { VtSelection::None } } #[derive(Debug, Eq, PartialEq, Default)] pub struct ConfigSession { pub command: String, pub user: String, } #[derive(Debug, Eq, PartialEq, Default)] pub struct ConfigInternal { pub session_worker: usize, } #[derive(Debug, Eq, PartialEq, Default)] pub struct ConfigTerminal { pub vt: VtSelection, pub switch: bool, } #[derive(Debug, Eq, PartialEq)] pub struct ConfigGeneral { pub source_profile: bool, pub runfile: String, } impl Default for ConfigGeneral { fn default() -> Self { ConfigGeneral { source_profile: true, runfile: RUNFILE.to_string(), } } } #[derive(Debug, Eq, PartialEq, Default)] pub struct ConfigFile { pub terminal: ConfigTerminal, pub general: ConfigGeneral, pub default_session: ConfigSession, pub initial_session: Option<ConfigSession>, } #[derive(Debug, Eq, PartialEq)] pub struct Config { pub file: ConfigFile, pub internal: ConfigInternal, } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); println!("{}", opts.usage(&brief)); println!("For more details, see greetd(1)."); } fn maybe_unquote(s: &str) -> Result<String, Error> { Ok(match s.chars().next() { Some('"') | Some('\'') => unquote(s).map_err(|e| Error::ConfigError(format!("{}", e)))?, _ => s.to_string(), }) } fn parse_old_config(config: &HashMap<&str, HashMap<&str, &str>>) -> Result<ConfigFile, Error> { let general = config.get("").ok_or("no general section")?; let greeterstr = general .get("greeter") .ok_or("unable to parse configuration file: no greeter specified")?; let greeter = maybe_unquote(greeterstr)?; let greeter_userstr = general.get("greeter_user").unwrap_or(&"greeter"); let greeter_user = maybe_unquote(greeter_userstr)?; let vtstr = general .get("vt") .ok_or("unable to parse configuration file: no VT specified")?; let vt: VtSelection = match maybe_unquote(vtstr)?.as_str() { "none" | "\"none\"" => VtSelection::None, "current" | "\"current\"" => VtSelection::Current, "next" | "\"next\"" => VtSelection::Next, v => VtSelection::Specific( v.parse() .map_err(|e| format!("could not parse vt number: {}", e))?, ), }; Ok(ConfigFile { terminal: ConfigTerminal { vt, switch: true }, default_session: ConfigSession { user: greeter_user, command: greeter, }, general: Default::default(), initial_session: None, }) } fn parse_new_config(config: &HashMap<&str, HashMap<&str, &str>>) -> Result<ConfigFile, Error> { let default_session = match config.get("default_session") { Some(section) => { let commandstr = section .get("command") .ok_or("default_session contains no command")?; let command = maybe_unquote(commandstr) .map_err(|e| format!("unable to read default_session.command: {}", e))?; let userstr = section.get("user").unwrap_or(&"greeter"); let user = maybe_unquote(userstr) .map_err(|e| format!("unable to read default_session.user: {}", e))?; Ok(ConfigSession { command, user }) } None => Err("no default_session specified"), }?; let initial_session = match config.get("initial_session") { Some(section) => { let commandstr = section .get("command") .ok_or("initial_session contains no command")?; let command = maybe_unquote(commandstr) .map_err(|e| format!("unable to read initial_session.command: {}", e))?; let userstr = section .get("user") .ok_or("initial_session contains no user")?; let user = maybe_unquote(userstr) .map_err(|e| format!("unable to read initial_session.user: {}", e))?; Some(ConfigSession { command, user }) } None => None, }; let terminal = match config.get("terminal") { Some(section) => Ok(ConfigTerminal { vt: match maybe_unquote(section.get("vt").ok_or("VT not specified")?) .map_err(|e| format!("unable to read terminal.vt: {}", e))? .as_str() { "none" | "\"none\"" => VtSelection::None, "current" | "\"current\"" => VtSelection::Current, "next" | "\"next\"" => VtSelection::Next, v => VtSelection::Specific( v.parse() .map_err(|e| format!("could not parse vt number: {}", e))?, ), }, switch: section .get("switch") .unwrap_or(&"true") .parse() .map_err(|e| format!("could not parse switch: {}", e))?, }), None => Err("no terminal specified"), }?; let general = match config.get("general") { Some(section) => { let runfilestr = section.get("runfile").unwrap_or(&RUNFILE); let runfile = maybe_unquote(runfilestr) .map_err(|e| format!("unable to read general.runfile: {}", e))?; ConfigGeneral { source_profile: section .get("source_profile") .unwrap_or(&"true") .parse() .map_err(|e| format!("could not parse source_profile: {}", e))?, runfile, } } None => Default::default(), }; Ok(ConfigFile { initial_session, default_session, general, terminal, }) } fn parse_config(config_str: &str) -> Result<ConfigFile, Error> { let config_ini = inish::parse(config_str)?; match parse_new_config(&config_ini) { Ok(v) => Ok(v), Err(e) => match parse_old_config(&config_ini) { Ok(v) => { eprintln!("warning: Fallback to old config format, caused by : {}", e); Ok(v) } Err(_e) => Err(Error::ConfigError(format!( "unable to parse configuration file: {}", e ))), }, } } pub fn read_config() -> Result<Config, Error> { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optopt("s", "socket-path", "socket path to use", "SOCKET_PATH"); opts.optopt("c", "config", "config file to use", "CONFIG_FILE"); opts.optopt( "w", "session-worker", "start a session worker (internal)", "FD", ); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => return Err(format!("could not parse arguments: {}", f).into()), }; if matches.opt_present("h") { print_usage(&program, opts); std::process::exit(0); } let internal = ConfigInternal { session_worker: matches .opt_get("session-worker") .expect("unable to parse session-worker") .unwrap_or(0), }; if internal.session_worker > 0 { return Ok(Config { file: Default::default(), internal, }); } let config_str = match matches.opt_str("config") { Some(v) => read_to_string(v), None => read_to_string("/etc/greetd/greetd.conf") .or_else(|_| read_to_string("/etc/greetd/config.toml")), }?; let file = parse_config(&config_str)?; if file.default_session.command.is_empty() { return Err(Error::ConfigError( "no default session user specified".to_string(), )); } if file.default_session.user.is_empty() { return Err(Error::ConfigError( "no default session user specified".to_string(), )); } if let Some(s) = &file.initial_session { if s.user.is_empty() { return Err(Error::ConfigError( "initial session enabled but contained no user".to_string(), )); } if s.command.is_empty() { return Err(Error::ConfigError( "initial session enabled but contained no command".to_string(), )); } } Ok(Config { file, internal }) } #[cfg(test)] mod tests { use super::*; #[test] fn old_config() { let config = parse_config( " vt = 1 greeter = \"agreety\" greeter_user = \"greeter\" ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Specific(1), switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: None, } ); let config = parse_config( " vt = \"next\" greeter = \"agreety\" ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Next, switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: None, } ); } #[test] fn minimal_config() { let config = parse_config( " [terminal] vt = 1 [default_session] command = \"agreety\" ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Specific(1), switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: None, } ); } #[test] fn initial_session() { let config = parse_config( " [terminal]\nvt = 1\n[default_session]\ncommand = \"agreety\" [initial_session] command = \"sway\" user = \"john\" ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Specific(1), switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: Some(ConfigSession { command: "sway".to_string(), user: "john".to_string(), }), } ); } #[test] fn general() { let config = parse_config( " [terminal]\nvt = 1\n[default_session]\ncommand = \"agreety\" [general] source_profile = false runfile = \"/path/to/greetd.state\" ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Specific(1), switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: ConfigGeneral { source_profile: false, runfile: "/path/to/greetd.state".to_string(), }, initial_session: None, } ); } #[test] fn invalid_general() { assert!(parse_config( " [terminal]\nvt = 1\n[default_session]\ncommand = \"agreety\" [general] source_profile = fals ", ) .is_err()) } #[test] fn terminal() { let config = parse_config( " [default_session]\ncommand = \"agreety\" [terminal] vt = 1 ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Specific(1), switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: None, } ); let config = parse_config( " [default_session]\ncommand = \"agreety\" [terminal] vt = next ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Next, switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: None, } ); let config = parse_config( " [default_session]\ncommand = \"agreety\" [terminal] vt = current ", ) .expect("config didn't parse"); assert_eq!( config, ConfigFile { terminal: ConfigTerminal { vt: VtSelection::Current, switch: true, }, default_session: ConfigSession { command: "agreety".to_string(), user: "greeter".to_string(), }, general: Default::default(), initial_session: None, } ); } #[test] fn invalid_initial_session() { assert!(parse_config( " [terminal]\nvt = 1\n[default_session]\ncommand = \"agreety\" [initial_session] " ) .is_err()); assert!(parse_config( " [terminal]\nvt = 1\n[default_session]\ncommand = \"agreety\" [initial_session] command = \"sway\" " ) .is_err()); assert!(parse_config( " [terminal]\nvt = 1\n[default_session]\ncommand = \"agreety\" [initial_session] user = \"user\" " ) .is_err()); } #[test] fn invalid_default_session() { assert!(parse_config( " [terminal]\nvt = 1 [default_session] " ) .is_err()); assert!(parse_config( " [terminal]\nvt = 1 [default_session] user = \"john\" " ) .is_err()); } } 0707010000001A000081A40000000000000000000000016135173A00003666000000000000000000000000000000000000002300000000greetd-0.8.0/greetd/src/context.rsuse std::{ fs::File, path::Path, time::{Duration, Instant}, }; use nix::{ sys::wait::{waitpid, WaitPidFlag, WaitStatus}, unistd::alarm, }; use tokio::{sync::RwLock, time::sleep}; use crate::{ error::Error, session::{ interface::{Session, SessionChild, SessionState}, worker::{AuthMessageType as SessAuthMessageType, TerminalMode}, }, }; use greetd_ipc::AuthMessageType; struct SessionChildSet { child: SessionChild, time: Instant, is_greeter: bool, } struct SessionSet { session: Session, time: Instant, } struct ContextInner { current: Option<SessionChildSet>, scheduled: Option<SessionSet>, configuring: Option<SessionSet>, } /// Context keeps track of running sessions and start new ones. pub struct Context { inner: RwLock<ContextInner>, greeter_bin: String, greeter_user: String, greeter_service: String, pam_service: String, term_mode: TerminalMode, source_profile: bool, runfile: String, } impl Context { pub fn new( greeter_bin: String, greeter_user: String, greeter_service: String, pam_service: String, term_mode: TerminalMode, source_profile: bool, runfile: String, ) -> Context { Context { inner: RwLock::new(ContextInner { current: None, scheduled: None, configuring: None, }), greeter_bin, greeter_user, greeter_service, pam_service, term_mode, source_profile, runfile, } } /// Directly start an unauthenticated session, bypassing the normal /// scheduling. This function does not take the inner lock, and can thus /// be used while it is held. async fn start_unauthenticated_session( &self, class: &str, user: &str, service: &str, cmd: Vec<String>, ) -> Result<SessionChild, Error> { let mut scheduled_session = Session::new_external()?; scheduled_session .initiate( &service, class, user, false, &self.term_mode, self.source_profile, ) .await?; loop { match scheduled_session.get_state().await { Ok(SessionState::Ready) => break, Ok(SessionState::Question(_, _)) => scheduled_session.post_response(None).await?, Err(err) => return Err(format!("session start failed: {}", err).into()), } } scheduled_session.send_args(cmd).await?; scheduled_session.start().await } /// Directly start a greeter session, bypassing the normal scheduling. This /// function does not take the inner lock, and can thus be used while it is /// held. async fn start_greeter(&self) -> Result<SessionChild, Error> { self.start_unauthenticated_session( "greeter", &self.greeter_user, &self.greeter_service, vec![self.greeter_bin.to_string()], ) .await } /// Directly start a greeter session, bypassing the normal scheduling. pub async fn greet(&self) -> Result<(), Error> { { let inner = self.inner.read().await; if inner.current.is_some() { return Err("session already active".into()); } } let mut inner = self.inner.write().await; inner.current = Some(SessionChildSet { child: self.start_greeter().await?, time: Instant::now(), is_greeter: true, }); Ok(()) } /// Check if this is the first time greetd starts since boot, or if it restarted for any reason pub fn is_first_run(&self) -> bool { !Path::new(&self.runfile).exists() } /// Create runfile used to check if greetd was already started since boot pub fn create_runfile(&self) { if let Err(err) = File::create(&self.runfile) { eprintln!("could not create runfile: {}", err); } } /// Directly start an initial session, bypassing the normal scheduling. pub async fn start_user_session(&self, user: &str, cmd: Vec<String>) -> Result<(), Error> { { let inner = self.inner.read().await; if inner.current.is_some() { return Err("session already active".into()); } } let mut inner = self.inner.write().await; inner.current = Some(SessionChildSet { child: self .start_unauthenticated_session("user", user, &self.pam_service, cmd) .await?, time: Instant::now(), is_greeter: false, }); Ok(()) } /// Create a new session for configuration. pub async fn create_session(&self, username: String) -> Result<(), Error> { { let inner = self.inner.read().await; if inner.current.is_none() { return Err("session not active".into()); } if inner.configuring.is_some() { return Err("a session is already being configured".into()); } if inner.scheduled.is_some() { return Err("a session is already scheduled".into()); } } let mut session_set = SessionSet { session: Session::new_external()?, time: Instant::now(), }; session_set .session .initiate( &self.pam_service, "user", &username, true, &self.term_mode, self.source_profile, ) .await?; let mut session = Some(session_set); let mut inner = self.inner.write().await; std::mem::swap(&mut session, &mut inner.configuring); drop(inner); // If there was a session under configuration, cancel it. if let Some(mut s) = session { s.session.cancel().await?; } Ok(()) } /// Cancel the session being configured. pub async fn cancel(&self) -> Result<(), Error> { let mut inner = self.inner.write().await; if let Some(mut s) = inner.configuring.take() { s.session.cancel().await?; } Ok(()) } /// Retrieve a question from the session under configuration. pub async fn get_question(&self) -> Result<Option<(AuthMessageType, String)>, Error> { let mut inner = self.inner.write().await; match &mut inner.configuring { Some(s) => match s.session.get_state().await? { SessionState::Ready => Ok(None), SessionState::Question(style, string) => Ok(Some(( match style { SessAuthMessageType::Visible => AuthMessageType::Visible, SessAuthMessageType::Secret => AuthMessageType::Secret, SessAuthMessageType::Info => AuthMessageType::Info, SessAuthMessageType::Error => AuthMessageType::Error, }, string, ))), }, None => Err("no session under configuration".into()), } } /// Answer a question to the session under configuration. pub async fn post_response(&self, answer: Option<String>) -> Result<(), Error> { let mut inner = self.inner.write().await; match &mut inner.configuring { Some(s) => s.session.post_response(answer).await, None => Err("no session under configuration".into()), } } /// Schedule the session under configuration with the provided arguments. pub async fn start(&self, cmd: Vec<String>) -> Result<(), Error> { let mut session = self.inner.write().await.configuring.take(); match &mut session { Some(s) => match s.session.get_state().await? { SessionState::Ready => { // Send our arguments to the session. s.session.send_args(cmd).await?; let mut inner = self.inner.write().await; std::mem::swap(&mut session, &mut inner.scheduled); drop(inner); // If there was a scheduled session, cancel it. if let Some(mut p) = session { p.session.cancel().await?; } // We give the greeter 5 seconds to prove itself well-behaved before // we lose patience and shoot it in the back repeatedly. This is all // handled by our alarm handler. alarm::set(5); Ok(()) } SessionState::Question(..) => Err("session is not ready".into()), }, None => Err("no session active".into()), } } /// Notify the Context of an alarm. pub async fn alarm(&self) -> Result<(), Error> { // Keep trying to terminate the greeter until it gives up. let mut inner = self.inner.write().await; if let Some(mut p) = inner.scheduled.take() { if let Some(g) = inner.current.take() { if p.time.elapsed() > Duration::from_secs(10) { // We're out of patience. g.child.kill(); } else { // Let's try to give it a gentle nudge. g.child.term(); } inner.current = Some(g); inner.scheduled = Some(p); alarm::set(1); return Ok(()); } drop(inner); let s = match p.session.start().await { Ok(s) => s, Err(e) => return Err(format!("session start failed: {}", e).into()), }; let mut inner = self.inner.write().await; inner.current = Some(SessionChildSet { child: s, time: Instant::now(), is_greeter: false, }); } Ok(()) } /// Notify the Context that it needs to check its children for termination. /// This should be called on SIGCHLD. pub async fn check_children(&self) -> Result<(), Error> { loop { match waitpid(None, Some(WaitPidFlag::WNOHANG)) { // No scheduled exits. Ok(WaitStatus::StillAlive) => break Ok(()), // We got an exit, see if it's something we need to clean up. Ok(WaitStatus::Exited(pid, ..)) | Ok(WaitStatus::Signaled(pid, ..)) => { let mut inner = self.inner.write().await; let (was_greeter, sesion_length) = match &inner.current { Some(s) if s.child.owns_pid(pid) => { let res = (s.is_greeter, s.time.elapsed()); inner.current = None; res } _ => continue, }; match inner.scheduled.take() { Some(mut scheduled) => { // Our greeter finally bit the dust so we can // start our scheduled session. drop(inner); let s = match scheduled.session.start().await { Ok(s) => s, Err(e) => return Err(format!("session start failed: {}", e).into()), }; let mut inner = self.inner.write().await; inner.current = Some(SessionChildSet { child: s, time: Instant::now(), is_greeter: false, }); } None => { if was_greeter { return Err("greeter exited without creating a session".into()); } if sesion_length < Duration::from_secs(1) { sleep(Duration::from_secs(1)).await; } inner.current = Some(SessionChildSet { child: self.start_greeter().await?, time: Instant::now(), is_greeter: true, }); } } } // Useless status. Ok(_) => continue, // Interrupted. Err(nix::Error::Sys(nix::errno::Errno::EINTR)) => continue, // We do not have any children right now. Err(nix::Error::Sys(nix::errno::Errno::ECHILD)) => break Ok(()), // Uh, what? Err(e) => panic!("waitpid returned an unexpected error: {}", e), } } } /// Notify the Context that we want to terminate. This should be called on /// SIGTERM. pub async fn terminate(&self) -> Result<(), Error> { let mut inner = self.inner.write().await; if let Some(mut sess) = inner.configuring.take() { let _ = sess.session.cancel().await; } if let Some(mut sess) = inner.scheduled.take() { let _ = sess.session.cancel().await; } if let Some(sess) = inner.current.take() { sess.child.term(); } Ok(()) } } 0707010000001B000081A40000000000000000000000016135173A0000076E000000000000000000000000000000000000002100000000greetd-0.8.0/greetd/src/error.rsuse std::convert::From; use serde::{Deserialize, Serialize}; use thiserror::Error as ThisError; #[derive(Debug, ThisError, Clone, Deserialize, Serialize)] pub enum Error { #[error("{0}")] Error(String), #[error("authentication error: {0}")] AuthError(String), #[error("protocol error: {0}")] ProtocolError(String), #[error("i/o error: {0}")] Io(String), #[error("configuration error: {0}")] ConfigError(String), } impl From<Box<dyn std::error::Error>> for Error { fn from(error: Box<dyn std::error::Error>) -> Self { Error::Error(format!("{}", error)) } } impl From<std::io::Error> for Error { fn from(error: std::io::Error) -> Self { Error::Io(format!("{}", error)) } } impl From<crate::pam::PamError> for Error { fn from(error: crate::pam::PamError) -> Self { Error::AuthError(error.to_string()) } } impl From<greetd_ipc::codec::Error> for Error { fn from(error: greetd_ipc::codec::Error) -> Self { match error { greetd_ipc::codec::Error::Serialization(s) => Error::ProtocolError(s), greetd_ipc::codec::Error::Io(s) => Error::Io(s), greetd_ipc::codec::Error::Eof => Error::Io("EOF".to_string()), } } } impl From<String> for Error { fn from(error: String) -> Self { Error::Error(error) } } impl From<&str> for Error { fn from(error: &str) -> Self { Error::Error(error.to_string()) } } impl From<serde_json::error::Error> for Error { fn from(error: serde_json::error::Error) -> Self { Error::ProtocolError(error.to_string()) } } impl From<nix::Error> for Error { fn from(error: nix::Error) -> Self { Error::Error(error.to_string()) } } impl From<std::ffi::NulError> for Error { fn from(error: std::ffi::NulError) -> Self { Error::Error(error.to_string()) } } 0707010000001C000081A40000000000000000000000016135173A000005C8000000000000000000000000000000000000002000000000greetd-0.8.0/greetd/src/main.rsmod config; mod context; mod error; mod pam; mod scrambler; mod server; mod session; mod terminal; use std::os::unix::{ io::{FromRawFd, RawFd}, net::UnixDatagram, }; use nix::{ fcntl::{fcntl, FcntlArg, FdFlag}, sys::mman::{mlockall, MlockAllFlags}, }; use tokio::task; use crate::{error::Error, session::worker}; async fn session_worker_main(config: config::Config) -> Result<(), Error> { let raw_fd = config.internal.session_worker as RawFd; let mut cur_flags = unsafe { FdFlag::from_bits_unchecked(fcntl(raw_fd, FcntlArg::F_GETFD)?) }; cur_flags.insert(FdFlag::FD_CLOEXEC); fcntl(raw_fd, FcntlArg::F_SETFD(cur_flags))?; let sock = unsafe { UnixDatagram::from_raw_fd(raw_fd) }; worker::main(&sock) } #[tokio::main(flavor = "current_thread")] async fn main() { let config = match config::read_config() { Ok(config) => config, Err(e) => { eprintln!("{}", e); std::process::exit(1); } }; if cfg!(feature = "debug") { eprintln!("config: {:?}", config); } mlockall(MlockAllFlags::all()).expect("unable to lock pages"); let res = task::LocalSet::new() .run_until(async move { if config.internal.session_worker > 0 { session_worker_main(config).await } else { server::main(config).await } }) .await; if let Err(e) = res { eprintln!("error: {}", e); } } 0707010000001D000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001C00000000greetd-0.8.0/greetd/src/pam0707010000001E000081A40000000000000000000000016135173A0000055F000000000000000000000000000000000000002800000000greetd-0.8.0/greetd/src/pam/converse.rs/// A trait representing the PAM authentification conversation /// /// PAM authentification is done as a conversation mechanism, in which PAM /// asks several questions and the client (your code) answers them. This trait /// is a representation of such a conversation, which one method for each message /// PAM can send you. /// /// This is the trait to implement if you want to customize the conversation with /// PAM. If you just want a simple login/password authentication, you can use the /// `PasswordConv` implementation provided by this crate. pub trait Converse { /// PAM requests a value that should be echoed to the user as they type it /// /// This would typically be the username. The exact question is provided as the /// `msg` argument if you wish to display it to your user. fn prompt_echo(&self, msg: &str) -> ::std::result::Result<String, ()>; /// PAM requests a value that should be typed blindly by the user /// /// This would typically be the password. The exact question is provided as the /// `msg` argument if you wish to display it to your user. fn prompt_blind(&self, msg: &str) -> ::std::result::Result<String, ()>; /// This is an informational message from PAM fn info(&self, msg: &str) -> Result<(), ()>; /// This is an error message from PAM fn error(&self, msg: &str) -> Result<(), ()>; } 0707010000001F000081A40000000000000000000000016135173A00000426000000000000000000000000000000000000002300000000greetd-0.8.0/greetd/src/pam/env.rsuse std::ffi::CStr; use libc::c_char; use pam_sys::{getenvlist, raw, PamHandle}; pub struct PamEnvList { ptr: *const *const c_char, } pub fn get_pam_env(handle: &mut PamHandle) -> Option<PamEnvList> { let env = getenvlist(handle); if !env.is_null() { Some(PamEnvList { ptr: env }) } else { None } } impl<'a> PamEnvList { pub fn to_vec(&'a self) -> Vec<&'a CStr> { let mut vec = Vec::new(); let mut idx = 0; loop { let env_ptr: *const *const c_char = unsafe { self.ptr.offset(idx) }; if unsafe { !(*env_ptr).is_null() } { idx += 1; let env = unsafe { CStr::from_ptr(*env_ptr) }; vec.push(env); } else { // Reached the end of the env array -> break out of the loop break; } } vec } } #[cfg(target_os = "linux")] impl Drop for PamEnvList { fn drop(&mut self) { unsafe { raw::pam_misc_drop_env(self.ptr as *mut *mut c_char) }; } } 07070100000020000081A40000000000000000000000016135173A00000D87000000000000000000000000000000000000002300000000greetd-0.8.0/greetd/src/pam/ffi.rsuse std::{ ffi::{CStr, CString}, mem, pin::Pin, }; use libc::{c_int, c_void, calloc, free, size_t, strdup}; use pam_sys::{PamConversation, PamMessage, PamMessageStyle, PamResponse, PamReturnCode}; use super::converse::Converse; pub struct PamConvHandlerWrapper<'a> { pub handler: Pin<Box<dyn Converse + 'a>>, } pub fn make_conversation(conv: &mut PamConvHandlerWrapper) -> PamConversation { PamConversation { conv: Some(converse), data_ptr: conv as *mut PamConvHandlerWrapper as *mut c_void, } } pub extern "C" fn converse( num_msg: c_int, msg: *mut *mut PamMessage, out_resp: *mut *mut PamResponse, appdata_ptr: *mut c_void, ) -> c_int { // allocate space for responses let resp = unsafe { calloc(num_msg as usize, mem::size_of::<PamResponse>() as size_t) as *mut PamResponse }; if resp.is_null() { return PamReturnCode::BUF_ERR as c_int; } let wrapper = unsafe { &*(appdata_ptr as *const PamConvHandlerWrapper) }; let mut result: PamReturnCode = PamReturnCode::SUCCESS; for i in 0..num_msg as isize { // get indexed values let m: &mut PamMessage = unsafe { &mut **(msg.offset(i)) }; let r: &mut PamResponse = unsafe { &mut *(resp.offset(i)) }; let msg = unsafe { CStr::from_ptr(m.msg) }; let msg = match msg.to_str() { Ok(m) => m, Err(_) => { result = PamReturnCode::CONV_ERR; break; } }; // match on msg_style match PamMessageStyle::from(m.msg_style) { PamMessageStyle::PROMPT_ECHO_ON => { if let Ok(handler_response) = wrapper.handler.prompt_echo(msg) { let cstr = CString::new(handler_response).expect("unable to allocate response string"); r.resp = unsafe { strdup(cstr.as_ptr()) }; } else { result = PamReturnCode::CONV_ERR; } } PamMessageStyle::PROMPT_ECHO_OFF => { if let Ok(handler_response) = wrapper.handler.prompt_blind(msg) { let cstr = CString::new(handler_response).expect("unable to allocate response string"); r.resp = unsafe { strdup(cstr.as_ptr()) }; } else { result = PamReturnCode::CONV_ERR; } } PamMessageStyle::ERROR_MSG => { if wrapper.handler.error(msg).is_err() { result = PamReturnCode::CONV_ERR; } } PamMessageStyle::TEXT_INFO => { if wrapper.handler.info(msg).is_err() { result = PamReturnCode::CONV_ERR; } } } if result != PamReturnCode::SUCCESS { break; } } // free allocated memory if an error occured if result != PamReturnCode::SUCCESS { // Free any strdup'd response strings for i in 0..num_msg as isize { let r: &mut PamResponse = unsafe { &mut *(resp.offset(i)) }; if !r.resp.is_null() { unsafe { free(r.resp as *mut c_void) }; } } // Free the response array unsafe { free(resp as *mut c_void) }; } else { unsafe { *out_resp = resp }; } result as c_int } 07070100000021000081A40000000000000000000000016135173A000003CC000000000000000000000000000000000000002300000000greetd-0.8.0/greetd/src/pam/mod.rspub mod converse; mod env; mod ffi; pub mod session; use thiserror::Error as ThisError; use pam_sys::PamReturnCode; #[derive(Debug, ThisError)] pub enum PamError { #[error("{0}")] Error(String), #[error("{0}")] AuthError(String), #[error("abort error: {0}")] AbortError(String), } impl PamError { pub fn from_rc(prefix: &str, rc: PamReturnCode) -> PamError { match rc { PamReturnCode::ABORT => PamError::AbortError(format!("{}: {:?}", prefix, rc)), PamReturnCode::AUTH_ERR | PamReturnCode::MAXTRIES | PamReturnCode::CRED_EXPIRED | PamReturnCode::ACCT_EXPIRED | PamReturnCode::CRED_INSUFFICIENT | PamReturnCode::USER_UNKNOWN | PamReturnCode::PERM_DENIED | PamReturnCode::SERVICE_ERR => PamError::AuthError(format!("{}: {:?}", prefix, rc)), _ => PamError::Error(format!("{}: {:?}", prefix, rc)), } } } 07070100000022000081A40000000000000000000000016135173A000011A9000000000000000000000000000000000000002700000000greetd-0.8.0/greetd/src/pam/session.rsuse std::{ ffi::{CStr, CString}, os::raw::c_char, pin::Pin, ptr, }; use libc::c_void; use pam_sys::{PamFlag, PamHandle, PamItemType, PamReturnCode}; use super::{ converse::Converse, env::{get_pam_env, PamEnvList}, ffi::{make_conversation, PamConvHandlerWrapper}, PamError, }; pub struct PamSession<'a> { handle: &'a mut PamHandle, #[allow(unused)] lifetime_extender: Pin<Box<PamConvHandlerWrapper<'a>>>, last_code: PamReturnCode, } impl<'a> PamSession<'a> { pub fn start( service: &str, user: &'a str, pam_conv: Pin<Box<dyn Converse + 'a>>, ) -> Result<PamSession<'a>, PamError> { let mut pch = Box::pin(PamConvHandlerWrapper { handler: pam_conv }); let conv = make_conversation(&mut *pch); let mut pam_handle: *mut PamHandle = ptr::null_mut(); match pam_sys::start(service, Some(user), &conv, &mut pam_handle) { PamReturnCode::SUCCESS => Ok(PamSession { handle: unsafe { &mut *pam_handle }, lifetime_extender: pch, last_code: PamReturnCode::SUCCESS, }), rc => Err(PamError::from_rc("pam_start", rc)), } } pub fn authenticate(&mut self, flags: PamFlag) -> Result<(), PamError> { self.last_code = pam_sys::authenticate(self.handle, flags); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_authenticate", rc)), } } pub fn acct_mgmt(&mut self, flags: PamFlag) -> Result<(), PamError> { self.last_code = pam_sys::acct_mgmt(self.handle, flags); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_acct_mgmt", rc)), } } pub fn setcred(&mut self, flags: PamFlag) -> Result<(), PamError> { self.last_code = pam_sys::setcred(self.handle, flags); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_setcred", rc)), } } pub fn open_session(&mut self, flags: PamFlag) -> Result<(), PamError> { self.last_code = pam_sys::open_session(self.handle, flags); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_open_session", rc)), } } pub fn close_session(&mut self, flags: PamFlag) -> Result<(), PamError> { self.last_code = pam_sys::close_session(self.handle, flags); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_close_session", rc)), } } pub fn putenv(&mut self, v: &str) -> Result<(), PamError> { self.last_code = pam_sys::putenv(self.handle, v); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_putenv", rc)), } } pub fn set_item(&mut self, item: PamItemType, value: &str) -> Result<(), PamError> { let s = CString::new(value).unwrap(); self.last_code = PamReturnCode::from(unsafe { // pam_set_item is exposed in a weird way in pam_sys::wrapped, so // we use the raw version here instead pam_sys::raw::pam_set_item(self.handle, item as i32, s.as_ptr() as *const c_void) }); match self.last_code { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_set_item", rc)), } } pub fn get_user(&mut self) -> Result<String, PamError> { let mut p: *const c_char = ptr::null_mut(); self.last_code = pam_sys::get_user(self.handle, &mut p, ptr::null()); match self.last_code { PamReturnCode::SUCCESS => { Ok((unsafe { CStr::from_ptr(p) }).to_str().unwrap().to_string()) } rc => Err(PamError::from_rc("pam_get_user", rc)), } } pub fn getenvlist(&mut self) -> Result<PamEnvList, PamError> { match get_pam_env(self.handle) { Some(v) => Ok(v), None => Err(PamError::Error( "unable to retrieve environment".to_string(), )), } } pub fn end(&mut self) -> Result<(), PamError> { match pam_sys::end(self.handle, self.last_code) { PamReturnCode::SUCCESS => Ok(()), rc => Err(PamError::from_rc("pam_end", rc)), } } } 07070100000023000081A40000000000000000000000016135173A000002B3000000000000000000000000000000000000002500000000greetd-0.8.0/greetd/src/scrambler.rsuse std::default::Default; /// Scrambling overwrites a buffers content with the default value. Useful to /// avoid leaving behind a heap littered with old secrets. pub trait Scrambler { fn scramble(&mut self); } impl<T: Default> Scrambler for Vec<T> { fn scramble(&mut self) { let cap = self.capacity(); self.truncate(0); for _ in 0..cap { self.push(Default::default()) } self.truncate(0); } } impl Scrambler for String { fn scramble(&mut self) { let cap = self.capacity(); self.truncate(0); for _ in 0..cap { self.push(Default::default()) } self.truncate(0); } } 07070100000024000081A40000000000000000000000016135173A000027FD000000000000000000000000000000000000002200000000greetd-0.8.0/greetd/src/server.rsuse std::{path::Path, rc::Rc}; use nix::unistd::{chown, getpid, Gid, Uid}; use tokio::{ net::{UnixListener, UnixStream}, signal::unix::{signal, SignalKind}, task, }; use crate::{ config::{Config, VtSelection}, context::Context, error::Error, session::worker::TerminalMode, terminal::{self, Terminal}, }; use greetd_ipc::{ codec::{Error as CodecError, TokioCodec}, ErrorType, Request, Response, }; fn reset_vt(term_mode: &TerminalMode) -> Result<(), Error> { match term_mode { TerminalMode::Terminal { path, vt, .. } => { let term = Terminal::open(path)?; term.kd_setmode(terminal::KdMode::Text)?; term.vt_setactivate(*vt)?; } TerminalMode::Stdin => (), } Ok(()) } fn wait_vt(term_mode: &TerminalMode) -> Result<(), Error> { match term_mode { TerminalMode::Terminal { path, vt, .. } => { let term = Terminal::open(path)?; term.vt_waitactive(*vt)?; } TerminalMode::Stdin => (), } Ok(()) } fn wrap_result<T>(res: Result<T, Error>) -> Response { match res { Ok(_) => Response::Success, Err(Error::AuthError(msg)) => Response::Error { error_type: ErrorType::AuthError, description: msg, }, Err(e) => Response::Error { error_type: ErrorType::Error, description: format!("{}", e), }, } } async fn client_get_question(ctx: &Context) -> Response { match ctx.get_question().await { Ok(Some((auth_message_type, auth_message))) => Response::AuthMessage { auth_message_type, auth_message, }, res => wrap_result(res), } } async fn client_handler(ctx: &Context, mut s: UnixStream) -> Result<(), Error> { loop { let req = match Request::read_from(&mut s).await { Ok(req) => req, Err(CodecError::Eof) => return Ok(()), Err(e) => return Err(e.into()), }; let resp = match req { Request::CreateSession { username } => match ctx.create_session(username).await { Ok(()) => client_get_question(&ctx).await, res => wrap_result(res), }, Request::PostAuthMessageResponse { response } => { match ctx.post_response(response).await { Ok(()) => client_get_question(&ctx).await, res => wrap_result(res), } } Request::StartSession { cmd } => wrap_result(ctx.start(cmd).await), Request::CancelSession => wrap_result(ctx.cancel().await), }; resp.write_to(&mut s).await?; } } // Return a TTY path and the TTY/VT number, based on the configured target. // // If the target is VtSelection::Current, return the path to the TTY // referenced by stdin and the TTY number it is connected to if possible. If // the referenced TTY is a PTY, fail. Otherwise, open tty0, get the current VT // number, and return the path to that TTY and VT. // // If the target is VtSelection::Next, open tty0 and request the next VT // number. Return the TTY and VT // // If the target is VtSelection::Specific, simply return the specified TTY and // VT. // // If the target is VtSelection::None, return nothing. fn get_tty(config: &Config) -> Result<TerminalMode, Error> { const TTY_PREFIX: &str = "/dev/tty"; const PTS_PREFIX: &str = "/dev/pts"; let term = match config.file.terminal.vt { VtSelection::Current => { let term = Terminal::stdin(); match term.ttyname() { // We have a usable terminal, so let's decipher and return that Ok(term_name) if term_name.starts_with(TTY_PREFIX) && term_name.len() > TTY_PREFIX.len() => { let vt = term_name[TTY_PREFIX.len()..] .parse() .map_err(|e| Error::Error(format!("unable to parse tty number: {}", e)))?; TerminalMode::Terminal { path: term_name, vt, switch: false, } } Ok(term_name) if term_name.starts_with(PTS_PREFIX) => { return Err("cannot use current VT when started from a psuedo terminal".into()) } // We don't have a usable terminal, so we have to jump through some hoops _ => { let sys_term = Terminal::open("/dev/tty0") .map_err(|e| format!("unable to open terminal: {}", e))?; let vt = sys_term .vt_get_current() .map_err(|e| format!("unable to get current VT: {}", e))?; TerminalMode::Terminal { path: format!("/dev/tty{}", vt), vt, switch: false, } } } } VtSelection::Next => { let term = Terminal::open("/dev/tty0") .map_err(|e| format!("unable to open terminal: {}", e))?; let vt = term .vt_get_next() .map_err(|e| format!("unable to get next VT: {}", e))?; TerminalMode::Terminal { path: format!("/dev/tty{}", vt), vt, switch: config.file.terminal.switch, } } VtSelection::None => TerminalMode::Stdin, VtSelection::Specific(vt) => TerminalMode::Terminal { path: format!("/dev/tty{}", vt), vt, switch: config.file.terminal.switch, }, }; return Ok(term); } // Listener is a convenience wrapper for creating the UnixListener we need, and // for providing cleanup on Drop. struct Listener(UnixListener); impl Listener { fn create(uid: Uid, gid: Gid) -> Result<Listener, Error> { let path = format!("/run/greetd-{}.sock", getpid().as_raw()); let _ = std::fs::remove_file(&path); let listener = UnixListener::bind(&path).map_err(|e| format!("unable to open listener: {}", e))?; chown(path.as_str(), Some(uid), Some(gid)) .map_err(|e| format!("unable to chown greetd socket at {}: {}", path, e))?; std::env::set_var("GREETD_SOCK", path); Ok(Listener(listener)) } } impl Drop for Listener { fn drop(&mut self) { let addr = match self.0.local_addr() { Ok(addr) => addr, Err(_) => return, }; if let Some(path) = addr.as_pathname() { let _ = std::fs::remove_file(path); } } } pub async fn main(config: Config) -> Result<(), Error> { let service = if Path::new("/etc/pam.d/greetd").exists() { "greetd" } else if Path::new("/etc/pam.d/login").exists() { eprintln!("warning: PAM 'greetd' service missing, falling back to 'login'"); "login" } else { return Err("PAM 'greetd' service missing".into()); }; let greeter_service = if Path::new("/etc/pam.d/greetd-greeter").exists() { "greetd-greeter" } else { service }; let u = users::get_user_by_name(&config.file.default_session.user).ok_or(format!( "configured default session user '{}' not found", &config.file.default_session.user ))?; let uid = Uid::from_raw(u.uid()); let gid = Gid::from_raw(u.primary_group_id()); let listener = Listener::create(uid, gid)?; let term_mode = get_tty(&config)?; if !config.file.terminal.switch { wait_vt(&term_mode).map_err(|e| format!("unable to wait VT: {}", e))?; } let ctx = Rc::new(Context::new( config.file.default_session.command, config.file.default_session.user, greeter_service.to_string(), service.to_string(), term_mode.clone(), config.file.general.source_profile, config.file.general.runfile, )); if let (Some(s), true) = (config.file.initial_session, ctx.is_first_run()) { if let Err(e) = ctx.start_user_session(&s.user, vec![s.command]).await { eprintln!("unable to start greeter: {}", e); reset_vt(&term_mode).map_err(|e| format!("unable to reset VT: {}", e))?; std::process::exit(1); } } else if let Err(e) = ctx.greet().await { eprintln!("unable to start greeter: {}", e); reset_vt(&term_mode).map_err(|e| format!("unable to reset VT: {}", e))?; std::process::exit(1); } ctx.create_runfile(); let mut alarm = signal(SignalKind::alarm()).expect("unable to listen for SIGALRM"); let mut child = signal(SignalKind::child()).expect("unable to listen for SIGCHLD"); let mut term = signal(SignalKind::terminate()).expect("unable to listen for SIGTERM"); let mut int = signal(SignalKind::interrupt()).expect("unable to listen for SIGINT"); loop { tokio::select! { _ = child.recv() => ctx.check_children().await.map_err(|e| format!("check_children: {}", e))?, _ = alarm.recv() => ctx.alarm().await.map_err(|e| format!("alarm: {}", e))?, _ = term.recv() => { ctx.terminate().await.map_err(|e| format!("terminate: {}", e))?; break; } _ = int.recv() => { ctx.terminate().await.map_err(|e| format!("terminate: {}", e))?; break; } stream = listener.0.accept() => match stream { Ok((stream, _)) => { let client_ctx = ctx.clone(); task::spawn_local(async move { if let Err(e) = client_handler(&client_ctx, stream).await { client_ctx.cancel().await.expect("unable to cancel session"); eprintln!("client loop failed: {}", e); } }); }, Err(err) => return Err(format!("accept: {}", err).into()), } } } Ok(()) } 07070100000025000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000002000000000greetd-0.8.0/greetd/src/session07070100000026000081A40000000000000000000000016135173A00000772000000000000000000000000000000000000002800000000greetd-0.8.0/greetd/src/session/conv.rsuse super::worker::{AuthMessageType, ParentToSessionChild, SessionChildToParent}; use crate::pam::converse::Converse; /// SessionConv is a PAM conversation implementation that forwards questions /// over a socket. pub struct SessionConv<'a> { sock: &'a std::os::unix::net::UnixDatagram, } impl<'a> SessionConv<'a> { fn question(&self, msg: &str, style: AuthMessageType) -> Result<Option<String>, ()> { let msg = SessionChildToParent::PamMessage { style, msg: msg.to_string(), }; msg.send(self.sock) .map_err(|e| eprintln!("pam_conv: {}", e))?; let msg = ParentToSessionChild::recv(self.sock).map_err(|e| eprintln!("pam_conv: {}", e))?; match msg { ParentToSessionChild::PamResponse { resp, .. } => Ok(resp), ParentToSessionChild::Cancel => Err(()), _ => Err(()), } } /// Create a new `PasswordConv` handler pub fn new(sock: &'a std::os::unix::net::UnixDatagram) -> SessionConv { SessionConv { sock } } } impl<'a> Converse for SessionConv<'a> { fn prompt_echo(&self, msg: &str) -> Result<String, ()> { match self.question(msg, AuthMessageType::Visible) { Ok(Some(response)) => Ok(response), _ => Err(()), } } fn prompt_blind(&self, msg: &str) -> Result<String, ()> { match self.question(msg, AuthMessageType::Secret) { Ok(Some(response)) => Ok(response), _ => Err(()), } } fn info(&self, msg: &str) -> Result<(), ()> { match self.question(msg, AuthMessageType::Info) { Ok(None) => Ok(()), _ => Err(()), } } fn error(&self, msg: &str) -> Result<(), ()> { match self.question(msg, AuthMessageType::Error) { Ok(None) => Ok(()), _ => Err(()), } } } 07070100000027000081A40000000000000000000000016135173A00001DF9000000000000000000000000000000000000002D00000000greetd-0.8.0/greetd/src/session/interface.rsuse std::{ ffi::CString, os::unix::{io::AsRawFd, net::UnixDatagram}, }; use nix::{ fcntl::{fcntl, FcntlArg, FdFlag}, sys::signal::Signal, unistd::{execv, fork, ForkResult, Pid}, }; use async_trait::async_trait; use tokio::net::UnixDatagram as TokioUnixDatagram; use super::worker::{AuthMessageType, ParentToSessionChild, SessionChildToParent, TerminalMode}; use crate::error::Error; #[async_trait] trait AsyncRecv<T: Sized> { async fn recv(sock: &mut TokioUnixDatagram) -> Result<T, Error>; } #[async_trait] trait AsyncSend { async fn send(&self, sock: &mut TokioUnixDatagram) -> Result<(), Error>; } #[async_trait] impl AsyncSend for ParentToSessionChild { async fn send(&self, sock: &mut TokioUnixDatagram) -> Result<(), Error> { let out = serde_json::to_vec(self).map_err(|e| format!("unable to serialize message: {}", e))?; sock.send(&out) .await .map_err(|e| format!("unable to send message: {}", e))?; Ok(()) } } #[async_trait] impl AsyncRecv<SessionChildToParent> for SessionChildToParent { async fn recv(sock: &mut TokioUnixDatagram) -> Result<SessionChildToParent, Error> { let mut data = [0; 10240]; let len = sock .recv(&mut data[..]) .await .map_err(|e| format!("unable to recieve message: {}", e))?; let msg = serde_json::from_slice(&data[..len]) .map_err(|e| format!("unable to deserialize message: {}", e))?; Ok(msg) } } /// SessionChild tracks the processes spawned by a session pub struct SessionChild { pub task: Pid, pub sub_task: Pid, } impl SessionChild { /// Check if this session has this pid. pub fn owns_pid(&self, pid: Pid) -> bool { self.task == pid } /// Send SIGTERM to the session child. pub fn term(&self) { let _ = nix::sys::signal::kill(self.sub_task, Signal::SIGTERM); } /// Send SIGKILL to the session child. pub fn kill(&self) { let _ = nix::sys::signal::kill(self.sub_task, Signal::SIGKILL); let _ = nix::sys::signal::kill(self.task, Signal::SIGKILL); } } #[derive(Debug)] pub enum SessionState { Question(AuthMessageType, String), Ready, } /// A device to initiate a logged in PAM session. pub struct Session { task: Pid, sock: TokioUnixDatagram, last_msg: Option<SessionChildToParent>, } impl Session { /// Create a session started as an external process. pub fn new_external() -> Result<Session, Error> { // Pipe used to communicate the true PID of the final child. let (parentfd, childfd) = UnixDatagram::pair().map_err(|e| format!("could not create pipe: {}", e))?; let raw_child = childfd.as_raw_fd(); let mut cur_flags = unsafe { FdFlag::from_bits_unchecked(fcntl(raw_child, FcntlArg::F_GETFD)?) }; cur_flags.remove(FdFlag::FD_CLOEXEC); fcntl(raw_child, FcntlArg::F_SETFD(cur_flags))?; let cur_exe = std::env::current_exe()?; let bin = CString::new(cur_exe.to_str().expect("unable to get current exe name"))?; let child = match unsafe { fork() }.map_err(|e| format!("unable to fork: {}", e))? { ForkResult::Parent { child, .. } => child, ForkResult::Child => { execv( &bin, &[ &bin, &CString::new("--session-worker").unwrap(), &CString::new(format!("{}", raw_child as usize)).unwrap(), ], ) .expect("unable to exec"); unreachable!("after exec"); } }; Ok(Session { task: child, sock: TokioUnixDatagram::from_std(parentfd)?, last_msg: None, }) } /// Initiates the session, which will cause authentication to begin. pub async fn initiate( &mut self, service: &str, class: &str, user: &str, authenticate: bool, term_mode: &TerminalMode, source_profile: bool, ) -> Result<(), Error> { let msg = ParentToSessionChild::InitiateLogin { service: service.to_string(), class: class.to_string(), user: user.to_string(), authenticate, tty: term_mode.clone(), source_profile, }; msg.send(&mut self.sock).await?; Ok(()) } /// Return the current state of this session. pub async fn get_state(&mut self) -> Result<SessionState, Error> { let msg = match self.last_msg.take() { Some(msg) => msg, None => SessionChildToParent::recv(&mut self.sock).await?, }; self.last_msg = Some(msg.clone()); match msg { SessionChildToParent::PamMessage { style, msg } => { Ok(SessionState::Question(style, msg)) } SessionChildToParent::Success => Ok(SessionState::Ready), SessionChildToParent::Error(e) => Err(e), msg => panic!( "expected PamMessage, Success or Error from session worker, got: {:?}", msg ), } } /// Cancel the session. pub async fn cancel(&mut self) -> Result<(), Error> { self.last_msg = None; ParentToSessionChild::Cancel.send(&mut self.sock).await?; Ok(()) } /// Send a response to an authentication question, or None to cancel the /// authentication attempt. pub async fn post_response(&mut self, answer: Option<String>) -> Result<(), Error> { self.last_msg = None; ParentToSessionChild::PamResponse { resp: answer } .send(&mut self.sock) .await?; Ok(()) } /// /// Send the arguments that will be used to start the session. /// pub async fn send_args(&mut self, cmd: Vec<String>) -> Result<(), Error> { let msg = ParentToSessionChild::Args { cmd }; msg.send(&mut self.sock).await?; let msg = SessionChildToParent::recv(&mut self.sock).await?; self.last_msg = Some(msg.clone()); match msg { SessionChildToParent::Success => Ok(()), SessionChildToParent::Error(e) => Err(e), msg => panic!( "expected Success or Error from session worker, got: {:?}", msg ), } } /// /// Start the session. /// pub async fn start(&mut self) -> Result<SessionChild, Error> { let msg = ParentToSessionChild::Start; msg.send(&mut self.sock).await?; let sub_task = loop { match SessionChildToParent::recv(&mut self.sock).await? { SessionChildToParent::Error(e) => return Err(e), SessionChildToParent::FinalChildPid(raw_pid) => { break Pid::from_raw(raw_pid as i32) } SessionChildToParent::PamMessage { .. } => { // pam_conv after start, ignore ParentToSessionChild::PamResponse { resp: None } .send(&mut self.sock) .await?; continue; } msg => panic!( "expected Error or FinalChildPid from session worker, got: {:?}", msg ), }; }; self.sock.shutdown(std::net::Shutdown::Both)?; Ok(SessionChild { task: self.task, sub_task, }) } } 07070100000028000081A40000000000000000000000016135173A0000003C000000000000000000000000000000000000002700000000greetd-0.8.0/greetd/src/session/mod.rspub mod conv; pub mod interface; mod prctl; pub mod worker; 07070100000029000081A40000000000000000000000016135173A00000181000000000000000000000000000000000000002900000000greetd-0.8.0/greetd/src/session/prctl.rsuse nix::{errno::Errno, Result}; pub const PRCTL_SET_PDEATHSIG: i32 = 1; #[allow(non_camel_case_types)] pub enum PrctlOption { SET_PDEATHSIG(i32), } pub fn prctl(option: PrctlOption) -> Result<()> { Errno::result(match option { PrctlOption::SET_PDEATHSIG(sig) => unsafe { libc::prctl(PRCTL_SET_PDEATHSIG, sig, 0, 0, 0) }, }) .map(drop) } 0707010000002A000081A40000000000000000000000016135173A00002715000000000000000000000000000000000000002A00000000greetd-0.8.0/greetd/src/session/worker.rsuse std::{env, ffi::CString, os::unix::net::UnixDatagram}; use nix::{ sys::wait::waitpid, unistd::{execve, fork, initgroups, setgid, setsid, setuid, ForkResult, Gid, Uid}, }; use pam_sys::{PamFlag, PamItemType}; use serde::{Deserialize, Serialize}; use users::os::unix::UserExt; use super::{ conv::SessionConv, prctl::{prctl, PrctlOption}, }; use crate::{error::Error, pam::session::PamSession, terminal}; #[derive(Clone, Debug, Serialize, Deserialize)] pub enum AuthMessageType { Visible, Secret, Info, Error, } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum TerminalMode { Terminal { path: String, vt: usize, switch: bool, }, Stdin, } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum ParentToSessionChild { InitiateLogin { service: String, class: String, user: String, authenticate: bool, tty: TerminalMode, source_profile: bool, }, PamResponse { resp: Option<String>, }, Args { cmd: Vec<String>, }, Start, Cancel, } impl ParentToSessionChild { pub fn recv(sock: &UnixDatagram) -> Result<ParentToSessionChild, Error> { let mut data = [0; 10240]; let len = sock.recv(&mut data[..])?; let msg = serde_json::from_slice(&data[..len])?; Ok(msg) } } #[derive(Clone, Debug, Serialize, Deserialize)] pub enum SessionChildToParent { Success, Error(Error), PamMessage { style: AuthMessageType, msg: String }, FinalChildPid(u64), } impl SessionChildToParent { pub fn send(&self, sock: &UnixDatagram) -> Result<(), Error> { let out = serde_json::to_vec(self)?; sock.send(&out)?; Ok(()) } } /// The entry point for the session worker process. The session worker is /// responsible for the entirety of the session setup and execution. It is /// started by Session::start. fn worker(sock: &UnixDatagram) -> Result<(), Error> { let (service, class, user, authenticate, tty, source_profile) = match ParentToSessionChild::recv(sock)? { ParentToSessionChild::InitiateLogin { service, class, user, authenticate, tty, source_profile, } => (service, class, user, authenticate, tty, source_profile), ParentToSessionChild::Cancel => return Err("cancelled".into()), msg => return Err(format!("expected InitiateLogin or Cancel, got: {:?}", msg).into()), }; let conv = Box::pin(SessionConv::new(sock)); let mut pam = PamSession::start(&service, &user, conv)?; if authenticate { pam.authenticate(PamFlag::NONE)?; } pam.acct_mgmt(PamFlag::NONE)?; // Not the credentials you think. pam.setcred(PamFlag::ESTABLISH_CRED)?; // Mark authentication as a success. SessionChildToParent::Success.send(sock)?; // Fetch our arguments from the parent. let cmd = match ParentToSessionChild::recv(sock)? { ParentToSessionChild::Args { cmd } => cmd, ParentToSessionChild::Cancel => return Err("cancelled".into()), msg => return Err(format!("expected Args or Cancel, got: {:?}", msg).into()), }; SessionChildToParent::Success.send(sock)?; // Await start request from our parent. match ParentToSessionChild::recv(sock)? { ParentToSessionChild::Start => (), ParentToSessionChild::Cancel => return Err("cancelled".into()), msg => return Err(format!("expected Start or Cancel, got: {:?}", msg).into()), }; let pam_username = pam.get_user()?; let user = users::get_user_by_name(&pam_username).ok_or("unable to get user info")?; // Make this process a session leader. setsid().map_err(|e| format!("unable to become session leader: {}", e))?; match tty { TerminalMode::Stdin => (), TerminalMode::Terminal { path, vt, switch } => { // Tell PAM what TTY we're targetting, which is used by logind. pam.set_item(PamItemType::TTY, &format!("tty{}", vt))?; pam.putenv(&format!("XDG_VTNR={}", vt))?; // Opening our target terminal. let target_term = terminal::Terminal::open(&path)?; // Set the target VT mode to text for compatibility. Other login managers // set this to graphics, but that disallows start of textual applications, // which greetd aims to support. target_term.kd_setmode(terminal::KdMode::Text)?; // Clear TTY so that it will be empty when we switch to it. target_term.term_clear()?; // A bit more work if a VT switch is required. if switch && vt != target_term.vt_get_current()? { // Perform a switch to the target VT, simultaneously resetting it to // VT_AUTO. target_term.vt_setactivate(vt)?; } // Connect std(in|out|err), and make this our controlling TTY. target_term.term_connect_pipes()?; target_term.term_take_ctty()?; } } // Prepare some values from the user struct we gathered earlier. let username = user.name().to_str().unwrap_or(""); let home = user.home_dir().to_str().unwrap_or(""); let shell = user.shell().to_str().unwrap_or(""); let uid = Uid::from_raw(user.uid()); let gid = Gid::from_raw(user.primary_group_id()); // Change working directory let pwd = match env::set_current_dir(home) { Ok(_) => home, Err(_) => { env::set_current_dir("/") .map_err(|e| format!("unable to set working directory: {}", e))?; "/" } }; // PAM has to be provided a bunch of environment variables before // open_session. We pass any environment variables from our greeter // through here as well. This allows them to affect PAM (more // specifically, pam_systemd.so), as well as make it easier to gather // and set all environment variables later. let prepared_env = [ "XDG_SEAT=seat0".to_string(), format!("XDG_SESSION_CLASS={}", class), format!("USER={}", username), format!("LOGNAME={}", username), format!("HOME={}", home), format!("SHELL={}", shell), format!("PWD={}", pwd), format!("GREETD_SOCK={}", env::var("GREETD_SOCK").unwrap()), format!( "TERM={}", env::var("TERM").unwrap_or_else(|_| "linux".to_string()) ), ]; for e in prepared_env.iter() { pam.putenv(e)?; } // Session time! pam.open_session(PamFlag::NONE)?; // Prepare some strings in C format that we'll need. let cusername = CString::new(username)?; let command = if source_profile { format!( "[ -f /etc/profile ] && . /etc/profile; [ -f $HOME/.profile ] && . $HOME/.profile; exec {}", cmd.join(" ") ) } else { format!("exec {}", cmd.join(" ")) }; // Extract PAM environment for use with execve below. let pamenvlist = pam.getenvlist()?; let envvec = pamenvlist.to_vec(); // PAM is weird and gets upset if you exec from the process that opened // the session, registering it automatically as a log-out. Thus, we must // exec in a new child. let child = match unsafe { fork() }.map_err(|e| format!("unable to fork: {}", e))? { ForkResult::Parent { child, .. } => child, ForkResult::Child => { // It is important that we do *not* return from here by // accidentally using '?'. The process *must* exit from within // this match arm. // Drop privileges to target user initgroups(&cusername, gid).expect("unable to init groups"); setgid(gid).expect("unable to set GID"); setuid(uid).expect("unable to set UID"); // Set our parent death signal. setuid/setgid above resets the // death signal, which is why we do this here. prctl(PrctlOption::SET_PDEATHSIG(libc::SIGTERM)).expect("unable to set death signal"); // Run let cpath = CString::new("/bin/sh").unwrap(); execve( &cpath, &[ &cpath, &CString::new("-c").unwrap(), &CString::new(command).unwrap(), ], &envvec, ) .expect("unable to exec"); unreachable!("after exec"); } }; // Signal the inner PID to the parent process. SessionChildToParent::FinalChildPid(child.as_raw() as u64).send(sock)?; sock.shutdown(std::net::Shutdown::Both)?; // Set our parent death signal. setsid above resets the signal, hence our // late assignment, which is why we do this here. prctl(PrctlOption::SET_PDEATHSIG(libc::SIGTERM))?; // Wait for process to terminate, handling EINTR as necessary. loop { match waitpid(child, None) { Err(nix::Error::Sys(nix::errno::Errno::EINTR)) => continue, Err(e) => { eprintln!("session: waitpid on inner child failed: {}", e); break; } Ok(_) => break, } } // Close the session. This step requires root privileges to run, as it // will result in various forms of login teardown (including unmounting // home folders, telling logind that the session ended, etc.). This is // why we cannot drop privileges in this process, but must do it in the // inner-most child. pam.close_session(PamFlag::NONE)?; pam.setcred(PamFlag::DELETE_CRED)?; pam.end()?; Ok(()) } pub fn main(sock: &UnixDatagram) -> Result<(), Error> { if let Err(e) = worker(sock) { SessionChildToParent::Error(e.clone()).send(sock)?; Err(e) } else { Ok(()) } } 0707010000002B000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000002100000000greetd-0.8.0/greetd/src/terminal0707010000002C000081A40000000000000000000000016135173A000004EC000000000000000000000000000000000000002A00000000greetd-0.8.0/greetd/src/terminal/ioctl.rsuse nix::{ioctl_read_bad, ioctl_write_int_bad, ioctl_write_ptr_bad}; pub const KDSETMODE: u16 = 0x4B3A; pub const KDTEXT: i32 = 0x00; pub const KDGRAPHICS: i32 = 0x01; pub const VT_OPENQRY: u16 = 0x5600; pub const VT_SETMODE: u16 = 0x5602; pub const VT_GETSTATE: u16 = 0x5603; pub const VT_ACTIVATE: u16 = 0x5606; pub const VT_WAITACTIVE: u16 = 0x5607; pub const VT_SETACTIVATE: u16 = 0x560F; pub const VT_AUTO: u8 = 0; pub const TIOCSCTTY: u16 = 0x540E; ioctl_write_int_bad!(kd_setmode, KDSETMODE); ioctl_write_int_bad!(vt_activate, VT_ACTIVATE); ioctl_write_int_bad!(vt_waitactive, VT_WAITACTIVE); ioctl_write_ptr_bad!(vt_setmode, VT_SETMODE, vt_mode); ioctl_write_ptr_bad!(vt_setactivate, VT_SETACTIVATE, vt_setactivate); ioctl_read_bad!(vt_openqry, VT_OPENQRY, i64); ioctl_read_bad!(vt_getstate, VT_GETSTATE, vt_state); ioctl_write_int_bad!(term_tiocsctty, TIOCSCTTY); #[allow(dead_code)] #[repr(C)] pub struct vt_mode { pub mode: u8, pub waitv: u8, pub relsig: u16, pub acqsig: u16, pub frsig: u16, } #[allow(dead_code)] #[repr(C)] pub struct vt_setactivate { pub console: u64, pub mode: vt_mode, } #[allow(dead_code)] #[repr(C)] pub struct vt_state { pub v_active: u16, pub v_signal: u16, pub v_state: u16, } 0707010000002D000081A40000000000000000000000016135173A00001E53000000000000000000000000000000000000002800000000greetd-0.8.0/greetd/src/terminal/mod.rsmod ioctl; use crate::error::Error; use nix::{ fcntl::{open, OFlag}, sys::stat::Mode, unistd::{close, dup2, write}, }; use std::{ffi::CStr, os::unix::io::RawFd}; #[allow(dead_code)] pub enum KdMode { Text, Graphics, } impl KdMode { fn to_const(&self) -> i32 { match self { KdMode::Text => ioctl::KDTEXT, KdMode::Graphics => ioctl::KDGRAPHICS, } } } pub struct Terminal { fd: RawFd, autoclose: bool, } impl Drop for Terminal { fn drop(&mut self) { if self.autoclose { close(self.fd).unwrap(); } } } fn ttyname_r(fd: RawFd) -> Result<String, Error> { let mut arr: [u8; 32] = [0; 32]; let res = unsafe { libc::ttyname_r( fd as libc::c_int, &mut arr[0] as *mut u8 as *mut libc::c_char, 31, ) }; if res != 0 { return Err("ttyname_r failed".into()); } let len = unsafe { libc::strnlen(&arr[0] as *const u8 as *const libc::c_char, 31) }; let s = CStr::from_bytes_with_nul(&arr[..len + 1]) .map_err(|e| Error::Error(format!("ttyname_r result conversion failed: {}", e)))?; Ok(s.to_str() .map_err(|e| Error::Error(format!("ttyname_r result conversion failed: {}", e)))? .to_string()) } impl Terminal { /// Open the terminal file for the specified terminal number. pub fn open(terminal: &str) -> Result<Terminal, Error> { let res = open( terminal, OFlag::O_RDWR | OFlag::O_NOCTTY, Mode::from_bits_truncate(0o666), ); match res { Ok(fd) => Ok(Terminal { fd, autoclose: true, }), Err(e) => return Err(format!("terminal: unable to open: {}", e).into()), } } /// Open the terminal from stdin pub fn stdin() -> Terminal { Terminal { fd: 0 as RawFd, autoclose: false, } } /// Returns the name of the TTY pub fn ttyname(&self) -> Result<String, Error> { ttyname_r(self.fd) } /// Set the kernel display to either graphics or text mode. Graphivs mode /// disables the kernel console on this VT, and also disables blanking /// between VT switches if both source and target VT is in graphics mode. pub fn kd_setmode(&self, mode: KdMode) -> Result<(), Error> { let mode = mode.to_const(); let ret = unsafe { ioctl::kd_setmode(self.fd, mode) }; if let Err(v) = ret { Err(format!("terminal: unable to set kernel display mode: {}", v).into()) } else { Ok(()) } } /// Switches to the specified VT and waits for completion of switch. fn vt_activate(&self, target_vt: usize) -> Result<(), Error> { if let Err(v) = unsafe { ioctl::vt_activate(self.fd, target_vt as i32) } { return Err(format!("terminal: unable to activate: {}", v).into()); } if let Err(v) = unsafe { ioctl::vt_waitactive(self.fd, target_vt as i32) } { return Err(format!("terminal: unable to wait for activation: {}", v).into()); } Ok(()) } /// Waits for specified VT to become active. pub fn vt_waitactive(&self, target_vt: usize) -> Result<(), Error> { if let Err(v) = unsafe { ioctl::vt_waitactive(self.fd, target_vt as i32) } { return Err(format!("terminal: unable to wait for activation: {}", v).into()); } Ok(()) } /// Set the VT mode to VT_AUTO with everything cleared. fn vt_mode_clean(&self) -> Result<(), Error> { let mode = ioctl::vt_mode { mode: ioctl::VT_AUTO, waitv: 0, relsig: 0, acqsig: 0, frsig: 0, }; let res = unsafe { ioctl::vt_setmode(self.fd, &mode) }; if let Err(v) = res { Err(format!("terminal: unable to set vt mode: {}", v).into()) } else { Ok(()) } } /// Set a VT mode, switch to the VT and wait for its activation. On Linux, /// this will use VT_SETACTIVATE, which will both set the mode and switch /// to the VT under the kernel console lock. On other platforms, /// VT_SETMODE followed by VT_ACTIVATE is used. For all platforms, /// VT_WAITACTIVE is used to wait for shell activation. pub fn vt_setactivate(&self, target_vt: usize) -> Result<(), Error> { if cfg!(target_os = "linux") { let arg = ioctl::vt_setactivate { console: target_vt as u64, mode: ioctl::vt_mode { mode: ioctl::VT_AUTO, waitv: 0, relsig: 0, acqsig: 0, frsig: 0, }, }; if let Err(v) = unsafe { ioctl::vt_setactivate(self.fd, &arg) } { return Err(format!("terminal: unable to setactivate: {}", v).into()); } if let Err(v) = unsafe { ioctl::vt_waitactive(self.fd, target_vt as i32) } { return Err(format!("terminal: unable to wait for activation: {}", v).into()); } } else { self.vt_mode_clean()?; self.vt_activate(target_vt)?; } Ok(()) } /// Retrieves the current VT number. pub fn vt_get_current(&self) -> Result<usize, Error> { let mut state = ioctl::vt_state { v_active: 0, v_signal: 0, v_state: 0, }; let res = unsafe { ioctl::vt_getstate(self.fd, &mut state as *mut ioctl::vt_state) }; if let Err(v) = res { Err(format!("terminal: unable to get current vt: {}", v).into()) } else if state.v_active < 1 { Err(format!("terminal: current vt invalid: {}", state.v_active).into()) } else { Ok(state.v_active as usize) } } /// Find the next unallocated VT, allocate it and return the number. Note /// that allocation does not mean exclusivity, and another process may take /// and use the VT before you get to it. pub fn vt_get_next(&self) -> Result<usize, Error> { let mut next_vt: i64 = 0; let res = unsafe { ioctl::vt_openqry(self.fd, &mut next_vt as *mut i64) }; if let Err(v) = res { Err(format!("terminal: unable to get next vt: {}", v).into()) } else if next_vt < 1 { Err(format!("terminal: next vt invalid: {}", next_vt).into()) } else { Ok(next_vt as usize) } } /// Hook up stdin, stdout and stderr of the current process ot this /// terminal. pub fn term_connect_pipes(&self) -> Result<(), Error> { let res = dup2(self.fd, 0) .and_then(|_| dup2(self.fd, 1)) .and_then(|_| dup2(self.fd, 2)); if let Err(v) = res { Err(format!("terminal: unable to connect pipes: {}", v).into()) } else { Ok(()) } } /// Clear this terminal by sending the appropciate escape codes to it. Only /// affects text mode. pub fn term_clear(&self) -> Result<(), Error> { let res = write(self.fd, b"\x1B[H\x1B[2J"); if let Err(v) = res { Err(format!("terminal: unable to clear: {}", v).into()) } else { Ok(()) } } // Forcibly take control of the terminal referred to by this fd. pub fn term_take_ctty(&self) -> Result<(), Error> { let res = unsafe { ioctl::term_tiocsctty(self.fd, 1) }; match res { Err(e) => Err(format!("terminal: unable to take controlling terminal: {}", e).into()), Ok(_) => Ok(()), } } } 0707010000002E000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001800000000greetd-0.8.0/greetd_ipc0707010000002F000081A40000000000000000000000016135173A000002C1000000000000000000000000000000000000002300000000greetd-0.8.0/greetd_ipc/Cargo.toml[package] name = "greetd_ipc" version = "0.8.0" authors = ["Kenny Levinsen"] edition = "2018" license = "GPL-3.0" homepage = "https://kl.wtf/projects/greetd" repository = "https://git.sr.ht/~kennylevinsen/greetd/" description = "An implementation of the greetd IPC protocol" keywords = ["greetd"] [package.metadata.docs.rs] all-features = true [features] codec = ["thiserror"] sync-codec = ["codec"] tokio-codec = ["codec", "tokio", "async-trait"] [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tokio = { version = "1.0", features = ["io-util"], optional = true } async-trait = { version = "0.1", optional = true } thiserror = { version = "1.0", optional = true } 07070100000030000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001C00000000greetd-0.8.0/greetd_ipc/src07070100000031000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000002200000000greetd-0.8.0/greetd_ipc/src/codec07070100000032000081A40000000000000000000000016135173A00000514000000000000000000000000000000000000002900000000greetd-0.8.0/greetd_ipc/src/codec/mod.rs//! Reader/writer codecs for Request/Response. //! //! This is implemented in the form of two traits, SyncCodec and TokioCodec, //! which operate on the `std` and `tokio` implementations of reader/writer //! traits. The former is intended as the name suggests for synchronous //! operation, while the latter is for asynchronous operation when using tokio. //! //! These codecs are hidden behind the `sync-codec` and `tokio-codec` features, //! respectively. These features also implicitly enable the `codec` feature, //! which controls the entire `codec` module. //! use thiserror::Error as ThisError; #[derive(Debug, ThisError)] pub enum Error { #[error("serialization error: {0}")] Serialization(String), #[error("i/o error: {0}")] Io(String), #[error("EOF")] Eof, } impl From<serde_json::error::Error> for Error { fn from(error: serde_json::error::Error) -> Self { Error::Serialization(error.to_string()) } } impl From<std::io::Error> for Error { fn from(error: std::io::Error) -> Self { Error::Io(format!("{}", error)) } } #[cfg(feature = "sync-codec")] mod sync; #[cfg(feature = "sync-codec")] pub use self::sync::SyncCodec; #[cfg(feature = "tokio-codec")] mod tokio; #[cfg(feature = "tokio-codec")] pub use self::tokio::TokioCodec; 07070100000033000081A40000000000000000000000016135173A00000A3A000000000000000000000000000000000000002A00000000greetd-0.8.0/greetd_ipc/src/codec/sync.rs//! Synchronous reader/writer implementation, operating on an implementor of std::io::{Read, Write}. //! //! # Example //! //! ```no_run //! use std::env; //! use std::os::unix::net::UnixStream; //! use greetd_ipc::{Request, Response}; //! use greetd_ipc::codec::SyncCodec; //! //! fn main() -> Result<(), Box<dyn std::error::Error>> { //! let mut stream = UnixStream::connect(env::var("GREETD_SOCK")?)?; //! Request::CreateSession { username: "john".to_string() }.write_to(&mut stream)?; //! let resp = Response::read_from(&mut stream)?; //! Ok(()) //! } //! ``` use crate::{codec::Error, Request, Response}; use std::io::{Read, Write}; /// Reader/writer implementation over std::io::{Read,Write}. pub trait SyncCodec { fn read_from<T: Read>(stream: &mut T) -> Result<Self, Error> where Self: std::marker::Sized; fn write_to<T: Write>(&self, stream: &mut T) -> Result<(), Error>; } impl SyncCodec for Request { fn read_from<T: Read>(stream: &mut T) -> Result<Self, Error> { let mut len_bytes = [0; 4]; stream .read_exact(&mut len_bytes) .map_err(|e| match e.kind() { std::io::ErrorKind::UnexpectedEof => Error::Eof, _ => e.into(), })?; let len = u32::from_ne_bytes(len_bytes); let mut resp_buf = vec![0; len as usize]; stream.read_exact(&mut resp_buf)?; serde_json::from_slice(&resp_buf).map_err(|e| e.into()) } fn write_to<T: Write>(&self, stream: &mut T) -> Result<(), Error> { let body_bytes = serde_json::to_vec(self)?; let len_bytes = (body_bytes.len() as u32).to_ne_bytes(); stream.write_all(&len_bytes)?; stream.write_all(&body_bytes)?; Ok(()) } } impl SyncCodec for Response { fn read_from<T: Read>(stream: &mut T) -> Result<Self, Error> { let mut len_bytes = [0; 4]; stream .read_exact(&mut len_bytes) .map_err(|e| match e.kind() { std::io::ErrorKind::UnexpectedEof => Error::Eof, _ => e.into(), })?; let len = u32::from_ne_bytes(len_bytes); let mut resp_buf = vec![0; len as usize]; stream.read_exact(&mut resp_buf)?; serde_json::from_slice(&resp_buf).map_err(|e| e.into()) } fn write_to<T: Write>(&self, stream: &mut T) -> Result<(), Error> { let body_bytes = serde_json::to_vec(self)?; let len_bytes = (body_bytes.len() as u32).to_ne_bytes(); stream.write_all(&len_bytes)?; stream.write_all(&body_bytes)?; Ok(()) } } 07070100000034000081A40000000000000000000000016135173A00000CD2000000000000000000000000000000000000002B00000000greetd-0.8.0/greetd_ipc/src/codec/tokio.rs//! Asynchronous reader/writer implementation, operating on an implementor of tokio::io::{AsyncReadExt, AsyncWriteExt}. //! //! # Example //! //! ```no_run //! use std::env; //! use tokio::net::UnixStream; //! use greetd_ipc::{Request, Response}; //! use greetd_ipc::codec::TokioCodec; //! //! #[tokio::main(flavor = "current_thread")] //! async fn main() -> Result<(), Box<dyn std::error::Error>> { //! let mut stream = UnixStream::connect(env::var("GREETD_SOCK")?).await?; //! Request::CreateSession { username: "john".to_string() }.write_to(&mut stream).await?; //! let resp = Response::read_from(&mut stream).await?; //! Ok(()) //! } //! ``` use crate::{codec::Error, Request, Response}; use async_trait::async_trait; use tokio::io::{AsyncReadExt, AsyncWriteExt}; /// Reader/writer implementation over tokio::io::{AsyncReadExt, AsyncWriteExt}. #[async_trait] pub trait TokioCodec { async fn read_from<T: AsyncReadExt + std::marker::Unpin + Send>( stream: &mut T, ) -> Result<Self, Error> where Self: std::marker::Sized; async fn write_to<T: AsyncWriteExt + std::marker::Unpin + Send>( &self, stream: &mut T, ) -> Result<(), Error>; } #[async_trait] impl TokioCodec for Request { async fn read_from<T: AsyncReadExt + std::marker::Unpin + Send>( stream: &mut T, ) -> Result<Self, Error> { let mut len_bytes = [0; 4]; stream .read_exact(&mut len_bytes) .await .map_err(|e| match e.kind() { std::io::ErrorKind::UnexpectedEof => Error::Eof, _ => e.into(), })?; let len = u32::from_ne_bytes(len_bytes); let mut body_bytes = vec![0; len as usize]; stream.read_exact(&mut body_bytes).await?; let body = serde_json::from_slice(&body_bytes)?; Ok(body) } async fn write_to<T: AsyncWriteExt + std::marker::Unpin + Send>( &self, stream: &mut T, ) -> Result<(), Error> { let body_bytes = serde_json::to_vec(self)?; let len_bytes = (body_bytes.len() as u32).to_ne_bytes(); stream.write_all(&len_bytes).await?; stream.write_all(&body_bytes).await?; Ok(()) } } #[async_trait] impl TokioCodec for Response { async fn read_from<T: AsyncReadExt + std::marker::Unpin + Send>( stream: &mut T, ) -> Result<Self, Error> { let mut len_bytes = [0; 4]; stream .read_exact(&mut len_bytes) .await .map_err(|e| match e.kind() { std::io::ErrorKind::UnexpectedEof => Error::Eof, _ => e.into(), })?; let len = u32::from_ne_bytes(len_bytes); let mut body_bytes = vec![0; len as usize]; stream.read_exact(&mut body_bytes).await?; let body = serde_json::from_slice(&body_bytes)?; Ok(body) } async fn write_to<T: AsyncWriteExt + std::marker::Unpin + Send>( &self, stream: &mut T, ) -> Result<(), Error> { let body_bytes = serde_json::to_vec(self)?; let len_bytes = (body_bytes.len() as u32).to_ne_bytes(); stream.write_all(&len_bytes).await?; stream.write_all(&body_bytes).await?; Ok(()) } } 07070100000035000081A40000000000000000000000016135173A00001415000000000000000000000000000000000000002300000000greetd-0.8.0/greetd_ipc/src/lib.rs//! # `greetd` IPC protocol library //! //! This library implements the [greetd](https://git.sr.ht/~kennylevinsen/greetd) IPC protocol. //! //! The library exposes a [Request](enum.Request.html) and a //! [Response](enum.Response.html) enum, representing the valid protocol //! messages. Furthermore, codec implementations are available to serialize //! these to/from both sync and async readers/writers. The availability of //! these are controlled by feature flags. //! //! Additional types are part of the different request and response values. //! //! See `agreety` for a simple example use of this library. //! //! # Format //! //! The message format is as follows: //! //! ```text //! +----------+-------------------+ //! | len: u32 | JSON payload: str | //! +----------+-------------------+ //! ``` //! //! Length is in native byte-order. The JSON payload is a variant of the //! Request or Response enums. //! //! # Request and response types //! //! See [Request](enum.Request.html) and [Response](enum.Response.html) for //! information about the request and response types, as well as their //! serialization. //! use serde::{Deserialize, Serialize}; #[cfg(feature = "codec")] #[cfg_attr(docsrs, doc(cfg(feature = "codec")))] pub mod codec; /// A request from a greeter to greetd. The request type is internally tagged /// with the"type" field, with the type written in snake_case. /// /// Example serialization: /// /// ```json /// { /// "type": "create_session", /// "username": "bob" /// } /// ``` #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] #[serde(tag = "type")] pub enum Request { /// CreateSession initiates a login attempt for the given user. /// CreateSession returns either a Response::AuthMessage, /// Response::Success or Response::Failure. /// /// If an auth message is returned, it should be answered with a /// Request::PostAuthMessageResponse. If a success is returned, the session /// can then be started with Request::StartSession. /// /// If a login flow needs to be aborted at any point, send /// Request::CancelSession. Note that the session is cancelled /// automatically on error. CreateSession { username: String }, /// PostAuthMessageResponse responds to the last auth message, and returns /// either a Response::AuthMessage, Response::Success or Response::Failure. /// /// If an auth message is returned, it should be answered with a /// Request::PostAuthMessageResponse. If a success is returned, the session /// can then be started with Request::StartSession. PostAuthMessageResponse { response: Option<String> }, /// Start a successfully logged in session. This will fail if the session /// has pending messages or has encountered an error. StartSession { cmd: Vec<String> }, /// Cancel a session. This can only be done if the session has not been /// started. Cancel does not have to be called if an error has been /// encountered in its setup or login flow. CancelSession, } /// An error type for Response::Error. Serialized as snake_case. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorType { /// A generic error. See the error description for more details. Error, /// An error caused by failed authentication. AuthError, } /// A message type for a Response::AuthMessage. Serialized as snake_case. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum AuthMessageType { /// A question whose answer should be visible during input. Visible, /// A question whose answer should be kept secret during input. Secret, /// An information message. Info, /// An error message. Error, } /// A response from greetd to a greeter. The request type is internally tagged /// with the"type" field, with the type written in snake_case. /// /// Example serialization: /// /// ```json /// { /// "type": "auth_message", /// "message": "Password:", /// "message_type": "secret" /// } /// ``` #[derive(Debug, Deserialize, Serialize)] #[serde(tag = "type")] #[serde(rename_all = "snake_case")] pub enum Response { /// The request was successful. Success, /// The request failed. See the type and/or description for more /// information about this failure. Error { error_type: ErrorType, description: String, }, /// An authentication message needs to be answered to continue through the /// authentication flow. /// /// An authentication message can consist of anything. While it will /// commonly just be a request for the users' password, it could also ask /// for TOTP codes, or whether or not you felt sad when Littlefoot's mother /// died in the original "Land Before Time". It is therefore important that /// no assumptions are made about the questions that will be asked, and /// attempts to automatically answer these questions should not be made. AuthMessage { auth_message_type: AuthMessageType, auth_message: String, }, } 07070100000036000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001300000000greetd-0.8.0/inish07070100000037000081A40000000000000000000000016135173A0000006D000000000000000000000000000000000000001E00000000greetd-0.8.0/inish/Cargo.toml[package] name = "inish" version = "0.1.0" authors = ["Kenny Levinsen"] edition = "2018" license = "GPL-3.0" 07070100000038000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001700000000greetd-0.8.0/inish/src07070100000039000081A40000000000000000000000016135173A00000DEE000000000000000000000000000000000000001E00000000greetd-0.8.0/inish/src/lib.rsuse std::{collections::HashMap, error::Error}; fn parse_field<'a>(line: &'a str) -> Result<(&'a str, &'a str), Box<dyn Error>> { let split = match line.find('=') { Some(v) => v, None => return Err("expected equals sign on line, but found none".into()), }; let (key, value) = line.split_at(split); let (key, value) = (key.trim(), value.trim_matches('=').trim()); Ok((key, value)) } type InishSection<'a> = HashMap<&'a str, &'a str>; type Inish<'a> = HashMap<&'a str, InishSection<'a>>; pub fn parse<'a>(s: &'a str) -> Result<Inish<'a>, Box<dyn Error>> { let mut sections: Inish<'a> = HashMap::new(); let mut current_section = HashMap::new(); let mut current_section_name = ""; for line in s.lines() { let line = line.trim(); let mut chars = line.chars(); let start = chars.next(); let end = chars.last(); match (start, end) { (Some('#'), _) => continue, (Some('['), Some(']')) => { sections.insert(current_section_name, current_section); current_section = HashMap::new(); let len = line.bytes().count(); current_section_name = &line[1..len - 1].trim(); } (Some('['), v) => { return Err(format!( "expected Some(']') to terminate section name, but got {:?}", v ) .into()); } _ if line.is_empty() => continue, _ => { let (key, value) = parse_field(line)?; current_section.insert(key, value); } } } sections.insert(current_section_name, current_section); Ok(sections) } #[cfg(test)] mod tests { use super::*; #[test] fn sections() { let config = parse( " [section_a] [section_b] ", ) .expect("config didn't parse"); if !config.contains_key("section_a") { panic!("named section did not exist"); } if !config.contains_key("section_b") { panic!("named section did not exist"); } if !config.contains_key("") { panic!("unnamed section did not exist"); } } #[test] fn fields() { let config = parse( " field_outside = 'hello' [section_a] field_a = 1234 ", ) .expect("config didn't parse"); let section_a = match config.get("section_a") { Some(v) => v, None => panic!("named section did not exist"), }; assert_eq!(section_a.get("field_a"), Some(&"1234")); let section_unnamed = match config.get("") { Some(v) => v, None => panic!("unnamed section did not exist"), }; assert_eq!(section_unnamed.get("field_outside"), Some(&"'hello'")); } #[test] fn whitespaces() { let config = parse( " field outside = 'hello' [ section a ] field a = 1234 ", ) .expect("config didn't parse"); let section_a = match config.get("section a") { Some(v) => v, None => panic!("named section did not exist"), }; assert_eq!(section_a.get("field a"), Some(&"1234")); let section_unnamed = match config.get("") { Some(v) => v, None => panic!("unnamed section did not exist"), }; assert_eq!(section_unnamed.get("field outside"), Some(&"'hello'")); } } 0707010000003A000041ED0000000000000000000000016135173A00000000000000000000000000000000000000000000001100000000greetd-0.8.0/man0707010000003B000081A40000000000000000000000016135173A00000367000000000000000000000000000000000000001A00000000greetd-0.8.0/man/MakefileSCDOC=$(shell pkg-config --variable=scdoc scdoc) PREFIX?=/usr/local MANDIR?=$(PREFIX)/share/man DESTDIR?= agreety.1: agreety-1.scd $(SCDOC) < agreety-1.scd > agreety.1 greetd.1: greetd-1.scd $(SCDOC) < greetd-1.scd > greetd.1 greetd.5: greetd-5.scd $(SCDOC) < greetd-5.scd > greetd.5 greetd-ipc.7: greetd-ipc-7.scd $(SCDOC) < greetd-ipc-7.scd > greetd-ipc.7 all: agreety.1 greetd.1 greetd.5 greetd-ipc.7 install: mkdir -p $(DESTDIR)$(MANDIR)/man1 mkdir -p $(DESTDIR)$(MANDIR)/man5 mkdir -p $(DESTDIR)$(MANDIR)/man7 install -m644 agreety.1 $(DESTDIR)$(MANDIR)/man1/agreety.1 install -m644 greetd.1 $(DESTDIR)$(MANDIR)/man1/greetd.1 install -m644 greetd.5 $(DESTDIR)$(MANDIR)/man5/greetd.5 install -m644 greetd-ipc.7 $(DESTDIR)$(MANDIR)/man7/greetd-ipc.7 clean: rm -f agreety.1 greetd.1 greetd.5 greetd-ipc.7 .DEFAULT_GOAL=all .PHONY: all install clean 0707010000003C000081A40000000000000000000000016135173A0000031C000000000000000000000000000000000000001F00000000greetd-0.8.0/man/agreety-1.scdagreety(1) # NAME agreety - A text-based greeter for greetd # SYNOPSIS *agreety* [options] # OPTIONS *-h, --help* Show help message and quit. *-c, --cmd <command>* Specifies the command to run on successful login. agreety will ask if none is specified. *-f, --max-failures <num>* Specifies the maximum number of login failures to accept before terminating. Defaults to 5. # DESCRIPTION agreety is a very simple text-based greeter, with an appearance similar to *agetty*(8) and *login*(1). It is bundled with *greetd*(1). To use agreety, configure it as your greeter in your greetd config file. # AUTHORS Maintained by Kenny Levinsen <contact@kl.wtf>. For more information about greetd development, see https://git.sr.ht/~kennylevinsen/greetd. # SEE ALSO *greetd*(1) *greetd*(5)0707010000003D000081A40000000000000000000000016135173A00000828000000000000000000000000000000000000001E00000000greetd-0.8.0/man/greetd-1.scdgreetd(1) # NAME greetd - A login manager daemon # SYNOPSIS *greetd* [options] # OPTIONS *-h, --help* Show help message and quit. *-c, --config <config>* Specifies the configuration file to use. # DESCRIPTION greetd was created to fill the need for a simple login manager that makes no assumptions about the applications it starts, thus being equally suitable for starting console sessions, Wayland sessions, or something else entirely. greetd does not itself interact with the user, but relies on an external greeter process like agreety(1) to handle that aspect. # OPERATION greetd operates on *sessions*. A greeter creates a session, attempts to authenticate a user in it, and finally, uses it start an arbitrary application. There are two types of preconfigured sessions: The default session, also known as the *greeter*, and the optional initial session, serving the purpose of "auto-login". The initial session, if configured, is started once when greetd launches. The default session is started on launch if an initial session is not configured, and started again whenever no session is running, such as when the user logs out. An IPC socket is exposed to this greeter, as reported by *GREETD_SOCK*. The greeter can use this to create, authenticate and finally start a session. For more information about the IPC layer, see greetd-ipc(7). Once the greeter has requested the start of a session and terminated itself, greetd will start the new session. Once this session terminates, the process starts over. greetd makes no assumptions about any sessions, including the greeter. They can be text-based, running in the active console, or full-on graphical environments. # CONFIGURATION greetd looks for a configuration file in /etc/greetd/config.toml by default. This can be overriden with a command-line argument. For information on the config file format, see greetd(5). # AUTHORS Maintained by Kenny Levinsen <contact@kl.wtf>. For more information about greetd development, see https://git.sr.ht/~kennylevinsen/greetd. # SEE ALSO *greetd*(5) *greetd-ipc*(7)0707010000003E000081A40000000000000000000000016135173A00000D9C000000000000000000000000000000000000001E00000000greetd-0.8.0/man/greetd-5.scdgreetd(5) # NAME greetd - configuration file # DESCRIPTION greetd uses a simple TOML configuration file to define its behavior. # CONFIGURATION The configuration is divided into *sections*. Sections are delimited like so: ``` [section_name] config_key = value ``` Configuration keys can be integer literals, or quote-delimited strings. The configuration sections are described below. ## terminal This section contains terminal configuration. *vt* = num|"next"|"current" The VT to run on. Can be the number of a specific VT, "next" to select the next available VT, or "current" to stay wherever greetd was started. The specific VT is evaluated at startup, and does not change during the execution of greetd. If using the current or a specific VT, you must ensure that there are no other users of that VT. If using systemd with autovt and getty, conflict avoidance can be handled in the service unit with "Conflicts=getty@ttyN.service", where N is the VT number. Use of a specific VT with appropriate conflict avoidance is recommended. *switch* = true|false Whether or not to switch to *vt*. If set to false and *vt* is not currently active VT, greetd will wait for *vt* to become active, before doing anything including starting greeter. If set to true, greetd will switch current VT to *vt*, Default is true. ## general This section contains general configuration that does not fit in other sections nor deserved its own section. *source_profile* = true|false Whether or not to source ~/.profile and /etc/profile if present when running commands. Defaults to true. *runfile* = path-to-runfile Location of greetd's runfile that is created during the first run to prevent the initial session from being run again on session termination or on greetd restart. This file should be in a location that is cleared during a reboot. ## default_session This section describes the default session, also referred to as the *greeter*. *command* = command-line The command-line to run to start the default session, e.g. "agreety -c sway". The default session is automatically started when no other session is running, such as when user session terminate, and when greetd is initially started with no initial session configured. See *greetd-ipc*(7) for information on how a greeter can create sessions. *user* = user The user to use for running the greeter. Defaults to "greeter". ## initial_session This optional section describes the initial session, commonly referred to as "auto-login". The initial session will only be executed during the first run of greetd since boot in order to ensure signing out works properly and to prevent security issues whenever greetd or the greeter exit. This is checked through the presence of the runfile. *command* = command-line The command-line to run to start the initial session, e.g. "sway". The initial session will be run when exactly once when greetd is initially launched. *user* = user The user to use for running the initial session. # EXAMPLES ## Regular setup with agreety and sway ``` [terminal] vt = 1 [default_session] command = "agreety -c sway" ``` ## Auto-login ``` [terminal] vt = 1 [default_session] command = "agreety -c sway" [initial_session] command = "sway" user = "john" ``` # AUTHORS Maintained by Kenny Levinsen <contact@kl.wtf>. For more information about greetd development, see https://git.sr.ht/~kennylevinsen/greetd. # SEE ALSO *greetd*(1) *greetd-ipc*(7) 0707010000003F000081A40000000000000000000000016135173A00000C87000000000000000000000000000000000000002200000000greetd-0.8.0/man/greetd-ipc-7.scdgreetd-ipc(7) # NAME greetd-ipc - IPC protocol for greetd # DESCRIPTION This details the interprocess communication (IPC) protocol for *greetd*(1). This IPC protocol can be used to create and manage sessions under greetd. The IPC protocol uses a UNIX socket as a method of communication. The path to the socket is stored in the environment variable _GREETD_SOCK_. # MESSAGE AND REPLY FORMAT The format for messages and replies is: ``` <payload-length> <payload> ``` Where ``` <payload-length> is a 32-bit integer in native byte order <payload> is a UTF-8-encoded JSON string. ``` For example, sending the "create_session" command would look like the following hexdump: ``` 00000000 2c 00 00 00 7b 22 74 79 70 65 22 3a 20 22 63 72 |,...{"type": "cr| 00000010 65 61 74 65 5f 73 65 73 73 69 6f 6e 22 2c 20 22 |eate_session", "| 00000020 75 73 65 72 6e 61 6d 65 22 3a 20 22 6d 65 22 7d |username": "me"}| ``` # MESSAGES ## Requests [[ *MESSAGE TYPE* :[ *FIELDS* :< *PURPOSE* | create_session : username (string) : Creates a session and initiates a login attempted for the given user. The session is ready to be started if a success is returned. | post_auth_message_response : response (string, optional) : Answers an authentication message. If the message was informative (info, error), then a response does not need to be set in this message. The session is ready to be started if a success is returned. | start_session : cmd (array of strings) : Requests for the session to be started using the provided command line. The session will start after the greeter process terminates. | cancel_session : : Cancels the session that is currently under configuration. ## Responses [[ *MESSAGE TYPE* :[ *FIELDS* :< *PURPOSE* |[ success : : Indicates that the request succeeded. | error : error_type (enum as string), description (string) : Indicates that the request failed. | auth_message : auth_message_type (enum as string), auth_message (string) : Indicates that an authentication message needs to be answered to continue through the authentication flow. There are no limits on the number and type of messages that may be required for authentication to succeed, and a greeter should not make any assumptions about the messages. Must be answered with either post_auth_message_response or cancel_session. ## Authentication message type enums [[ *AUTH MESSAGE TYPE* :[ *PURPOSE* | visible : Indicates that input from the user should be visible when they answer this question. | secret : Indicates that input from the user should be considered secret when they answer this question. | info : Indicates that this message is informative, not a question. | error : Indicates that this message is an error, not a question. ## Error enums [[ *ERROR TYPE* :[ *PURPOSE* | auth_error : Indicates that authentication failed. This is not a fatal error, and is likely caused by incorrect credentials. Handle as appropriate. | error : A general error. See the error description for more information. # AUTHORS Maintained by Kenny Levinsen <contact@kl.wtf>. For more information about greetd development, see https://git.sr.ht/~kennylevinsen/greetd. # SEE ALSO *greetd*(1)07070100000040000081A40000000000000000000000016135173A00000037000000000000000000000000000000000000001A00000000greetd-0.8.0/rustfmt.tomlunstable_features = true imports_granularity = "Crate" 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!361 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor