Repository: billziss-gh/winfuse Branch: master Commit: 8cdd7634c22d Files: 83 Total size: 487.9 KB Directory structure: gitextract_o7pwrk8z/ ├── .gitmodules ├── Contributors.asciidoc ├── License.txt ├── README.md ├── appveyor.yml ├── doc/ │ ├── component.puml │ ├── winseq.puml │ └── wslseq.puml ├── ext/ │ └── tlib/ │ ├── Commit.txt │ ├── callstack.c │ ├── callstack.h │ ├── injected/ │ │ ├── allfunc.h │ │ ├── curlfunc.c │ │ ├── curlfunc.h │ │ ├── stdfunc.c │ │ └── stdfunc.h │ ├── injection.c │ ├── injection.h │ ├── testsuite.c │ └── testsuite.h ├── src/ │ ├── fusermount/ │ │ ├── fusermount-helper.c │ │ ├── fusermount.c │ │ ├── install.sh │ │ └── uninstall.sh │ ├── shared/ │ │ ├── km/ │ │ │ ├── cache.c │ │ │ ├── context.c │ │ │ ├── coro.h │ │ │ ├── debug.c │ │ │ ├── errno.i │ │ │ ├── errnosym.i │ │ │ ├── file.c │ │ │ ├── fuseop.c │ │ │ ├── instance.c │ │ │ ├── ioq.c │ │ │ ├── path.c │ │ │ ├── proto.c │ │ │ ├── proto.h │ │ │ ├── shared.h │ │ │ └── util.c │ │ └── ku/ │ │ └── wslfuse.h │ ├── winfuse/ │ │ ├── device.c │ │ ├── driver.c │ │ ├── driver.h │ │ ├── driver.inf.in │ │ └── version.rc │ └── wslfuse/ │ ├── device.c │ ├── driver.c │ ├── driver.h │ ├── driver.inf.in │ └── version.rc ├── tools/ │ ├── DigiCert High Assurance EV Root CA.crt │ ├── build-libfuse.bat │ ├── build-lxdk.bat │ ├── build-sample.bat │ ├── build-winfsp.bat │ ├── build.bat │ ├── debug.bat │ ├── deploy.bat │ ├── deploy.ps1 │ ├── gensrc/ │ │ ├── errno.sh │ │ └── errno.txt │ ├── ioc.c │ ├── license-headers/ │ │ ├── fix.ps1 │ │ ├── header.c │ │ ├── header.cpp │ │ └── header.h │ ├── nmake-ext-test.bat │ └── run-tests.bat └── tst/ ├── lockdly/ │ └── lockdly.c ├── memfs-fuse3/ │ ├── .gitignore │ ├── compat.h │ ├── memfs-fuse3.cpp │ ├── memfs-fuse3.exe.vcxproj │ ├── memfs-fuse3.exe.vcxproj.filters │ ├── memfs-fuse3.out.vcxproj │ ├── memfs-fuse3.out.vcxproj.filters │ └── memfs-fuse3.sln ├── winfuse-tests/ │ ├── coro-test.c │ ├── path-test.c │ ├── transact-test.c │ └── winfuse-tests.c └── wslfuse-tests/ ├── mount-test.c └── wslfuse-tests.c ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitmodules ================================================ [submodule "ext/libfuse"] path = ext/libfuse url = https://github.com/billziss-gh/libfuse.git [submodule "ext/winfsp"] path = ext/winfsp url = https://github.com/billziss-gh/winfsp.git [submodule "ext/lxdk"] path = ext/lxdk url = https://github.com/billziss-gh/lxdk.git ================================================ FILE: Contributors.asciidoc ================================================ CONTRIBUTORS ============ This document contains a list of all contributors to this project. Contributors that submit changes to this project MUST also change this document to identify themselves by adding their name and email address to the CONTRIBUTOR LIST. The CONTRIBUTOR LIST is maintained in alphabetical order. A contributor who adds themselves to this list indicates their acceptance of the terms of the CONTRIBUTOR AGREEMENT below. There are NO EXCEPTIONS to this rule. If you do not wish to accept the CONTRIBUTOR AGREEMENT, please do not submit any changes. This CONTRIBUTOR AGREEMENT is based on the Oracle Contributor Agreement and is used under the Creative Commons Attribution-Share Alike 3.0 Unported License. The original agreement and an FAQ can be found at this location: http://www.oracle.com/technetwork/community/oca-486395.html This document uses the asciidoc format: http://asciidoc.org. CONTRIBUTOR AGREEMENT --------------------- This CONTRIBUTOR AGREEMENT applies to any contribution that you make to the WinFuse project (the "project"), and sets out the intellectual property rights you grant to us in the contributed materials. The term “us” shall mean the original author of this project: Bill Zissimopoulos . The term “you” shall mean the persons or entities identified below. If you agree to be bound by these terms, add your name and email address to the CONTRIBUTOR LIST below; this action will constitute signing this CONTRIBUTOR AGREEMENT. These terms and conditions constitute a binding legal agreement. 1. The term 'contribution' or ‘contributed materials’ means any source code, object code, patch, tool, sample, graphic, specification, manual, documentation, or any other material posted or submitted by you to the project. 2. With respect to any worldwide copyrights, or copyright applications and registrations, in your contribution: * you hereby assign to us joint ownership, and to the extent that such assignment is or becomes invalid, ineffective or unenforceable, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free, unrestricted license to exercise all rights under those copyrights. This includes, at our option, the right to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements; * you agree that each of us can do all things in relation to your contribution as if each of us were the sole owners, and if one of us makes a derivative work of your contribution, the one who makes the derivative work (or has it made) will be the sole owner of that derivative work; * you agree that you will not assert any moral rights in your contribution against us, our licensees or transferees; * you agree that we may register a copyright in your contribution and exercise all ownership rights associated with it; and * you agree that neither of us has any duty to consult with, obtain the consent of, pay or render an accounting to the other for any use or distribution of your contribution. 3. With respect to any patents you own, or that you can license without payment to any third party, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free license to: * make, have made, use, sell, offer to sell, import, and otherwise transfer your contribution in whole or in part, alone or in combination with or included in any product, work or materials arising out of the project to which your contribution was submitted, and * at our option, to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements. 4. Except as set out above, you keep all right, title, and interest in your contribution. The rights that you grant to us under these terms are effective on the date you first submitted a contribution to us, even if your submission took place before the date you sign these terms. Any contribution we make available under any license will also be made available under a suitable FSF (Free Software Foundation) or OSI (Open Source Initiative) approved license. 5. You covenant, represent, warrant and agree that: * each contribution that you submit is and shall be an original work of authorship and you can legally grant the rights set out in this CONTRIBUTOR AGREEMENT; * to the best of your knowledge, each contribution will not violate any third party's copyrights, trademarks, patents, or other intellectual property rights; and * each contribution shall be in compliance with U.S. export control laws and other applicable export and import laws. * You agree to notify us if you become aware of any circumstance which would make any of the foregoing representations inaccurate in any respect. 6. This CONTRIBUTOR AGREEMENT is governed by the laws of the State of Washington and applicable U.S. Federal law. Any choice of law rules will not apply. 7. Please add your name and email address in the CONTRIBUTOR LIST below: * Either "I am signing on behalf of myself as an individual and no other person or entity, including my employer, has or will have rights with respect my contributions". In this case add your name using the following format: + ---- |First Last |name at example.com ---- * Or "I am signing on behalf of my employer or a legal entity and I have the actual authority to contractually bind that entity". In this case add your name using the following format: + ---- |First Last (Company and/or URL) |name at example.com ---- CONTRIBUTOR LIST ---------------- |=== |Bill Zissimopoulos |billziss at navimatics.com |=== ================================================ FILE: License.txt ================================================ The WinFuse project is Copyright (C) Bill Zissimopoulos. It is licensed under the terms of the AGPLv3. As a special exception to AGPLv3, Bill Zissimopoulos grants additional permissions to Free/Libre and Open Source Software ("FLOSS") without requiring that such software is covered by the AGPLv3. 1. Permission to use the WinFuse DeviceIoControl interface, which allows programs running on native Windows to interact with WinFuse using the FUSE protocol. 2. Permission to use the WinFuse /dev/fuse interface, which allows programs running on the Windows Subsystem for Linux to interact with WinFuse using the FUSE protocol. These permissions (and no other) are granted provided that the software: 1. Is distributed under a license that satisfies the Free Software Definition Version 1.141 (https://www.gnu.org/philosophy/free-sw.en.html) or the Open Source Definition Version 1.9 (https://opensource.org/osd). 2. Includes the copyright notice "WinFuse - FUSE for Windows, Copyright (C) Bill Zissimopoulos" and a link to the WinFuse repository in its user-interface and any user-facing documentation. 3. Is not linked or distributed with proprietary (non-FLOSS) software. [You cannot mix FLOSS and proprietary software while using WinFuse under this special exception.] Commercial licensing options are also available: Please contact Bill Zissimopoulos . The full text of the AGPLv3 license follows below. ----------------------------------------------------------------------- GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see . ================================================ FILE: README.md ================================================

WinFuse · FUSE for the Windows kernel

Download


WinFuse is a suite of software components that allows FUSE file systems to run on Windows. Both Windows and Linux (WSL1) FUSE file systems are supported. Windows FUSE file systems are supported via a kernel driver that exposes the FUSE protocol via DeviceIoControl and a port of the libfuse library compiled as a Windows DLL. Linux FUSE file systems are expected to run in the WSL1 environment and are supported via a kernel driver that exposes /dev/fuse.

## ARCHITECTURE ### Structural Diagram The following component diagram shows the WinFuse project components and their relations to the Windows OS (NTOS), WSL (LXCORE) and components that are provided by other projects. ![Component Diagram](doc/component.svg) The components and their interfaces are: - The **winfsp** component which is provided by the [WinFsp](https://github.com/billziss-gh/winfsp) project. - The component is an NTOS File System Driver (FSD). - The component provides an **FSP_FSCTL_TRANSACT** `DeviceIoControl` interface. - The component is responsible for loading the **winfuse** component. - The **winfuse** component which is provided by the WinFuse project (this project). - The component is an NTOS driver. - The component provides an **FUSE_FSCTL_TRANSACT** `DeviceIoControl` interface. - The component connects to the **FSP_FSCTL_TRANSACT** interface. WinFsp file system requests retrieved via this interface are translated to FUSE file system requests and become available via **FUSE_FSCTL_TRANSACT**. - The **wslfuse** component which is provided by the WinFuse project (this project). - The component is an LXCORE driver. - The component provides a **/dev/fuse** Linux interface. - The component connects to the **FSP_FSCTL_TRANSACT** interface. WinFsp file system requests retrieved via this interface are translated to FUSE file system requests and become available via **/dev/fuse**. - The **lxldr** component which is provided by the [LxDK](https://github.com/billziss-gh/lxdk) project. - The component is an LXCORE driver. - The component is responsible for loading the **wslfuse** component. - The file system (**FS**) components which are user-mode programs provided by third parties. - A Windows WinFsp file system connects to the **FSP_FSCTL_TRANSACT** interface. - A Windows FUSE file system connects to the **FUSE_FSCTL_TRANSACT** interface. - A Linux FUSE file system connects to the **/dev/fuse** interface. ### Behavioral Diagrams The following sequence diagrams show how the WinFuse project components interact with other components in two scenarios: (1) I/O handled by a Windows FUSE file system, and (2) I/O handled by a Linux FUSE file system. #### I/O handled by a Windows FUSE file system: ![Windows FS Sequence Diagram](doc/winseq.svg) - The I/O originates with one of: - A Windows process which uses a familiar API like `ReadFile` or `WriteFile`. - A WSL (Linux) process which uses an API like `read(2)` or `write(2)` that LXCORE translates into the equivalent `NtReadFile` or `NtWriteFile`. - The Windows OS (NTOS) packages this I/O into an IRP (I/O Request Packet) and routes it to the **winfsp** FSD. - The **winfsp** FSD posts the request into an internal I/O queue. This request is retrieved at a later time and in a different process context via an `FSP_FSCTL_TRANSACT` (issued via `DeviceIoControl`) by the **winfuse** driver. - The **winfuse** driver translates the request to equivalent FUSE requests, which are then retrieved via an `FUSE_FSCTL_TRANSACT` (issued via `DeviceIoControl`) by the Windows FUSE file system. - The Windows FUSE file system processes the request and prepares a response, which it sends to the **winfuse** driver via another `FUSE_FSCTL_TRANSACT`. - The **winfuse** driver processes the FUSE response and it may issue additional FUSE requests or it may translate it to a final WinFsp response, which it sends to the **winfsp** FSD via another `FSP_FSCTL_TRANSACT`. - The **winfsp** FSD completes the corresponding I/O, which allows the Originating Process to resume and retrieve the response. #### I/O handled by a Linux FUSE file system: ![Linux FS Sequence Diagram](doc/wslseq.svg) This case is similar to the previous case except that the **winfuse** driver is replaced by the **wslfuse** driver that exposes the FUSE protocol via the **/dev/fuse** interface that the Linux FUSE file system understands. ================================================ FILE: appveyor.yml ================================================ version: '{build}' image: Visual Studio 2019 environment: matrix: - CONFIGURATION: Debug WINFSP: rel LXDK: rel - CONFIGURATION: Release WINFSP: rel LXDK: rel init: #- ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) install: - git submodule update --init --recursive # install WinFsp - appveyor AddMessage "Install WinFsp" -Category Information - if %WINFSP%==rel appveyor DownloadFile https://github.com/billziss-gh/winfsp/releases/download/v1.8B2/winfsp-1.8.20221.msi - if %WINFSP%==rel appveyor DownloadFile https://github.com/billziss-gh/winfsp/releases/download/v1.8B2/winfsp-tests-1.8.20221.zip - if %WINFSP%==src tools\build-winfsp.bat %CONFIGURATION% - if %WINFSP%==src copy ext\winfsp\build\VStudio\build\%CONFIGURATION%\winfsp-*.msi . - if %WINFSP%==src copy ext\winfsp\build\VStudio\build\%CONFIGURATION%\winfsp-tests-*.zip . - for %%f in ("winfsp-*.msi") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000 - for %%f in ("winfsp-tests-*.zip") do powershell -command "Expand-Archive -Path %%f -DestinationPath 'C:\Program Files (x86)\WinFsp\bin'" # install LxDK - appveyor AddMessage "Install LxDK" -Category Information - if %LXDK%==rel appveyor DownloadFile https://github.com/billziss-gh/lxdk/releases/download/v0.3/lxdk-0.3.20228.msi - if %LXDK%==src tools\build-lxdk.bat %CONFIGURATION% - if %LXDK%==src copy ext\lxdk\build\VStudio\build\%CONFIGURATION%\lxdk-*.msi . - for %%f in ("lxdk-*.msi") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000 # install WSL Ubuntu 20.04 - adapted from appveyor/build-images:scripts/Windows/install_wsl.ps1 - appveyor AddMessage "Install WSL Ubuntu 20.04" -Category Information - ps: (New-Object Net.WebClient).DownloadFile('https://aka.ms/wslubuntu2004', "$env:TEMP\wsl-ubuntu-2004.zip") - ps: Expand-Archive -Path "$env:TEMP\wsl-ubuntu-2004.zip" -DestinationPath "C:\WSL\WinFuse-Ubuntu2004" -Force - ps: Remove-Item "$env:TEMP\wsl-ubuntu-2004.zip" - ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" install --root - ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run adduser appveyor --gecos `"First,Last,RoomNumber,WorkPhone,HomePhone`" --disabled-password - ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run "echo 'appveyor:Password12!' | sudo chpasswd" - ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run usermod -aG sudo appveyor - ps: | . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run "echo -e `"`"appveyor\tALL=(ALL)\tNOPASSWD: ALL`"`" > /etc/sudoers.d/appveyor" - ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run chmod 0755 /etc/sudoers.d/appveyor - ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" config --default-user appveyor - wslconfig /setdefault Ubuntu-20.04 - wsl -- lsb_release -a # install WSL tools - appveyor AddMessage "Install WSL tools" -Category Information - wsl -- sudo apt-get update; sudo apt-get install -y g++ gdb make ninja-build rsync zip libfuse3-dev # enable test-signing and verifier and reboot - appveyor AddMessage "Change boot configuration and reboot" -Category Information - bcdedit /set testsigning on - verifier /standard /driver winfuse-x64.sys || ver>nul - if exist %SystemRoot%\memory.dmp del %SystemRoot%\memory.dmp - ps: Restart-Computer -Force - ps: Start-Sleep -s 60 build_script: - appveyor AddMessage "Reboot complete" -Category Information - tools\build.bat %CONFIGURATION% - for %%f in ("build\VStudio\build\%CONFIGURATION%\winfuse-*-x64.msi") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000 - copy ext\libfuse\build\%CONFIGURATION%\x86\lib\fuse3-x86.dll "C:\Program Files\WinFuse\opt\libfuse\bin" - copy ext\libfuse\build\%CONFIGURATION%\x86\lib\fuse3-x86.lib "C:\Program Files\WinFuse\opt\libfuse\lib" test_script: - tools\nmake-ext-test.bat - tools\run-tests.bat %CONFIGURATION% - tools\run-tests.bat %CONFIGURATION% sample - if exist %SystemRoot%\memory.dmp exit 1 on_finish: - if exist %SystemRoot%\memory.dmp (7z a memory.dmp.zip %SystemRoot%\memory.dmp && appveyor PushArtifact memory.dmp.zip) - verifier /query #- ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) ================================================ FILE: doc/component.puml ================================================ left to right direction skinparam componentStyle uml2 skinparam nodesep 50 skinparam ranksep 30 skinparam shadowing false skinparam rectangle { fontcolor grey borderColor grey shadowing false } skinparam linetype ortho rectangle NTOS { together dummy { component winfuse #Salmon interface "FUSE_FSCTL\nTRANSACT" as FUSE_FSCTL_TRANSACT #Salmon winfuse -right- FUSE_FSCTL_TRANSACT component winfsp interface "FSP_FSCTL\nTRANSACT" as FSP_FSCTL_TRANSACT winfsp -right- FSP_FSCTL_TRANSACT winfsp .up.> winfuse: loads winfuse -down-( FSP_FSCTL_TRANSACT } rectangle LXCORE { component wslfuse #Salmon interface "/dev/fuse" as devfuse #Salmon wslfuse -right- devfuse component lxldr lxldr .up.> wslfuse: loads } winfsp -[hidden]- wslfuse wslfuse -up-( FSP_FSCTL_TRANSACT } component "Windows\nWinFsp FS" as fspfs fspfs -left-( FSP_FSCTL_TRANSACT component "Windows\nFUSE FS" as winfs winfs -left-( FUSE_FSCTL_TRANSACT component "Linux\nFUSE FS" as wslfs wslfs -left-( devfuse ================================================ FILE: doc/winseq.puml ================================================ skinparam shadowing false hide footbox box "Originating Process Context" participant "Originating\nProcess" as OP participant "winfsp" as winfspOP end box box "File System Process Context" participant "winfsp" as winfspFS participant winfuse #Salmon participant "Windows\nFUSE FS" as FS end box activate OP OP->winfspOP: I/O deactivate OP activate winfspOP winfspOP-->winfspFS: Context Switch deactivate winfspOP activate winfspFS winfspFS->winfuse: FSP_FSCTL_TRANSACT Req deactivate winfspFS activate winfuse winfuse->FS: FUSE_FSCTL_TRANSACT Req deactivate winfuse activate FS FS->FS: Process activate FS deactivate FS FS->winfuse: FUSE_FSCTL_TRANSACT Rsp deactivate FS activate winfuse winfuse->winfspFS: FSP_FSCTL_TRANSACT Rsp deactivate winfuse activate winfspFS winfspFS-->OP: Context Switch and Return deactivate winfspFS activate OP ================================================ FILE: doc/wslseq.puml ================================================ skinparam shadowing false hide footbox box "Originating Process Context" participant "Originating\nProcess" as OP participant "winfsp" as winfspOP end box box "File System Process Context" participant "winfsp" as winfspFS participant wslfuse #Salmon participant "Linux\nFUSE FS" as FS end box activate OP OP->winfspOP: I/O deactivate OP activate winfspOP winfspOP-->winfspFS: Context Switch deactivate winfspOP activate winfspFS winfspFS->wslfuse: FSP_FSCTL_TRANSACT Req deactivate winfspFS activate wslfuse wslfuse->FS: /dev/fuse read deactivate wslfuse activate FS FS->FS: Process activate FS deactivate FS FS->wslfuse: /dev/fuse write deactivate FS activate wslfuse wslfuse->winfspFS: FSP_FSCTL_TRANSACT Rsp deactivate wslfuse activate winfspFS winfspFS-->OP: Context Switch and Return deactivate winfspFS activate OP ================================================ FILE: ext/tlib/Commit.txt ================================================ Taken from github.com/billziss-gh/winfsp/ext/tlib codebase: commit 847eab3da4e558e2c88504edfe18a51e4450f9e0 Originally from secfs.core/src/tlib codebase: commit 16296d2ac64a7d532b1c486dd3c44af5865d4851 ================================================ FILE: ext/tlib/callstack.c ================================================ /** * @file tlib/callstack.c * * @copyright 2014-2019 Bill Zissimopoulos */ #include #include #include #if defined(_WIN32) || defined(_WIN64) #include #include #pragma comment(lib, "dbghelp.lib") #elif defined(__APPLE__) || defined(__linux__) #include #include #else #error tlib/callstack.c not implemented for this platform #endif void tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *stack) { if (count > TLIB_MAX_SYMRET) count = TLIB_MAX_SYMRET; size_t naddrs = skip + count; if (naddrs > TLIB_MAX_SYMCAP) naddrs = TLIB_MAX_SYMCAP; memset((void *)stack->syms, 0, sizeof stack->syms); #if defined(_WIN32) || defined(_WIN64) /* SymInitialize()/SymFromAddr() are not thread-safe. Furthermore SymInitialize() should * not be called more than once per process. */ HANDLE hproc = GetCurrentProcess(); static SYMBOL_INFO *syminfo = 0; void *addrs[TLIB_MAX_SYMCAP]; size_t i = 0; if (0 == syminfo) { syminfo = (SYMBOL_INFO *)malloc(sizeof(SYMBOL_INFO) + TLIB_MAX_SYMLEN); if (0 == syminfo) return; SymInitialize(hproc, 0, TRUE); } memset(syminfo, 0, sizeof(SYMBOL_INFO)); syminfo->SizeOfStruct = sizeof(SYMBOL_INFO); syminfo->MaxNameLen = TLIB_MAX_SYMLEN; naddrs = CaptureStackBackTrace(0, naddrs, addrs, 0); for (void **p = addrs + skip, **endp = addrs + naddrs; endp > p; p++) { DWORD64 displacement = 0; if (SymFromAddr(hproc, (DWORD64)*p, &displacement, syminfo)) { stack->syms[i] = stack->symbuf[i]; strncpy(stack->symbuf[i], syminfo->Name, TLIB_MAX_SYMLEN); stack->symbuf[i][TLIB_MAX_SYMLEN] = '\0'; i++; } } #elif defined(__APPLE__) || defined(__linux__) void *addrs[TLIB_MAX_SYMCAP]; naddrs = backtrace(addrs, naddrs); size_t i = 0; Dl_info syminfo; for (void **p = addrs + skip, **endp = addrs + naddrs; endp > p; p++) { if (dladdr(*p, &syminfo) && 0 != syminfo.dli_sname) { stack->syms[i] = stack->symbuf[i]; strncpy(stack->symbuf[i], syminfo.dli_sname, TLIB_MAX_SYMLEN); stack->symbuf[i][TLIB_MAX_SYMLEN] = '\0'; i++; } } #endif } ================================================ FILE: ext/tlib/callstack.h ================================================ /** * @file tlib/callstack.h * * @copyright 2014-2019 Bill Zissimopoulos */ #ifndef TLIB_CALLSTACK_H_INCLUDED #define TLIB_CALLSTACK_H_INCLUDED #include enum { TLIB_MAX_SYMLEN = 63, TLIB_MAX_SYMRET = 8, TLIB_MAX_SYMCAP = 62, /* max number of frames to capture (Windows restriction) */ }; struct tlib_callstack_s { const char *syms[TLIB_MAX_SYMRET + 1]; char symbuf[TLIB_MAX_SYMRET][TLIB_MAX_SYMLEN + 1]; }; void tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *stack); #endif ================================================ FILE: ext/tlib/injected/allfunc.h ================================================ /** * @file tlib/injected/allfunc.h * * @copyright 2014-2019 Bill Zissimopoulos */ #ifndef TLIB_INJECTED_ALLFUNC_H_INCLUDED #define TLIB_INJECTED_ALLFUNC_H_INCLUDED #include #include #endif ================================================ FILE: ext/tlib/injected/curlfunc.c ================================================ /** * @file tlib/injected/curlfunc.c * * @copyright 2014-2019 Bill Zissimopoulos */ #include #define TLIB_INJECTIONS_ENABLED #include #undef curl_easy_init #undef curl_multi_init #undef curl_multi_add_handle #undef curl_multi_perform CURL *tlib_curl_easy_init(void) { TLIB_INJECT("curl_easy_init", return 0); return curl_easy_init(); } CURLM *tlib_curl_multi_init(void) { TLIB_INJECT("curl_multi_init", return 0); return curl_multi_init(); } CURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh) { TLIB_INJECT("curl_multi_add_handle", return CURLM_INTERNAL_ERROR); return curl_multi_add_handle(mh, eh); } CURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles) { TLIB_INJECT("curl_multi_perform", return CURLM_INTERNAL_ERROR); return curl_multi_perform(mh, running_handles); } ================================================ FILE: ext/tlib/injected/curlfunc.h ================================================ /** * @file tlib/injected/curlfunc.h * * @copyright 2014-2019 Bill Zissimopoulos */ #ifndef TLIB_INJECTED_CURLFUNC_H_INCLUDED #define TLIB_INJECTED_CURLFUNC_H_INCLUDED #include #if defined(TLIB_INJECTIONS_ENABLED) #define curl_easy_init() tlib_curl_easy_init() #define curl_multi_init() tlib_curl_multi_init() #define curl_multi_add_handle(mh, eh) tlib_curl_multi_add_handle(mh, eh) #define curl_multi_perform(mh, rh) tlib_curl_multi_perform(mh, rh) #endif CURL *tlib_curl_easy_init(void); CURLM *tlib_curl_multi_init(void); CURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh); CURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles); #endif ================================================ FILE: ext/tlib/injected/stdfunc.c ================================================ /** * @file tlib/injected/stdfunc.c * * @copyright 2014-2019 Bill Zissimopoulos */ #include #define TLIB_INJECTIONS_ENABLED #include #undef calloc #undef malloc #undef realloc void *tlib_calloc(size_t count, size_t size) { TLIB_INJECT("calloc", return 0); return calloc(count, size); } void *tlib_malloc(size_t size) { TLIB_INJECT("malloc", return 0); return malloc(size); } void *tlib_realloc(void *ptr, size_t size) { TLIB_INJECT("realloc", return 0); return realloc(ptr, size); } ================================================ FILE: ext/tlib/injected/stdfunc.h ================================================ /** * @file tlib/injected/stdfunc.h * * @copyright 2014-2019 Bill Zissimopoulos */ #ifndef TLIB_INJECTED_STDFUNC_H_INCLUDED #define TLIB_INJECTED_STDFUNC_H_INCLUDED #include #include #if defined(TLIB_INJECTIONS_ENABLED) #define calloc(count, size) tlib_calloc(count, size) #define malloc(size) tlib_malloc(size) #define realloc(ptr, size) tlib_realloc(ptr, size) #endif void *tlib_calloc(size_t count, size_t size); void *tlib_malloc(size_t size); void *tlib_realloc(void *ptr, size_t size); #endif ================================================ FILE: ext/tlib/injection.c ================================================ /** * @file tlib/injection.c * * @copyright 2014-2019 Bill Zissimopoulos */ #include #include #include #include #include #undef NDEBUG #include #define NBUCKETS 256 struct injection_cond_s { struct injection_cond_s *cnext; char *sym; unsigned trigger, count; }; struct injection_entry_s { struct injection_entry_s *hnext; char *name; struct injection_cond_s *clist; }; struct injection_htab_s { struct injection_entry_s **buckets; }; static inline size_t hash_chars(const char *s, size_t length) { /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */ size_t h = 5381; for (const char *t = s + length; t > s; ++s) h = 33 * h + *s; return h; } static struct injection_htab_s *injection_htab() { static struct injection_htab_s *htab; if (0 == htab) { htab = calloc(1, sizeof *htab); assert(0 != htab); htab->buckets = calloc(NBUCKETS, sizeof(struct injection_entry_s *)); } return htab; } static struct injection_entry_s *injection_lookup(const char *name) { struct injection_htab_s *htab = injection_htab(); size_t i = hash_chars(name, strlen(name)) & (NBUCKETS - 1); for (struct injection_entry_s *entry = htab->buckets[i]; entry; entry = entry->hnext) if (0 == strcmp(entry->name, name)) return entry; return 0; } static struct injection_entry_s *injection_insert(const char *name) { struct injection_htab_s *htab = injection_htab(); size_t i = hash_chars(name, strlen(name)) & (NBUCKETS - 1); struct injection_entry_s *entry = calloc(1, sizeof *entry); assert(0 != entry); entry->name = strdup(name); entry->hnext = htab->buckets[i]; htab->buckets[i] = entry; return entry; } static struct injection_cond_s *injection_cond_get(struct injection_entry_s *entry, const char **syms) { struct injection_cond_s *deinjection_centry = 0; for (struct injection_cond_s *centry = entry->clist; centry; centry = centry->cnext) if ('*' == centry->sym[0] && '\0' == centry->sym[1]) deinjection_centry = centry; else { for (const char *sym; 0 != (sym = *syms); syms++) if (0 == strcmp(centry->sym, sym)) return centry; } return deinjection_centry; } static void injection_cond_set(struct injection_entry_s *entry, const char *sym, unsigned trigger) { for (struct injection_cond_s *centry = entry->clist; centry; centry = centry->cnext) if (0 == strcmp(centry->sym, sym)) { centry->trigger = trigger; return; } struct injection_cond_s *centry = calloc(1, sizeof *centry); assert(0 != centry); centry->sym = strdup(sym); centry->trigger = trigger; centry->cnext = entry->clist; entry->clist = centry; } static void injection_cond_remove(struct injection_entry_s *entry, const char *sym) { struct injection_cond_s **p = &entry->clist; for (; *p; p = &(*p)->cnext) if (0 == strcmp((*p)->sym, sym)) break; if (*p) /* did we find the condition? */ { struct injection_cond_s *q = *p; *p = q->cnext; free(q->sym); free(q); } } void *tlib_injection(const char *name) { struct injection_entry_s *entry = injection_lookup(name); if (0 == entry) entry = injection_insert(name); return entry; } int tlib_injection_trace(void *injection) { if (0 == ((struct injection_entry_s *)injection)->clist) return 0; struct tlib_callstack_s stack; tlib_callstack(2, TLIB_MAX_SYMRET, &stack); struct injection_cond_s *centry = injection_cond_get(injection, stack.syms); if (0 == centry) return 0; return centry->count++ == centry->trigger || ~0 == centry->trigger; } void tlib_injection_enable(const char *name, const char *sym, unsigned trigger) { struct injection_entry_s *entry = tlib_injection(name); injection_cond_set(entry, sym, trigger); } void tlib_injection_disable(const char *name, const char *sym) { struct injection_entry_s *entry = tlib_injection(name); injection_cond_remove(entry, sym); } ================================================ FILE: ext/tlib/injection.h ================================================ /** * @file tlib/injection.h * * @copyright 2014-2019 Bill Zissimopoulos */ /* NOTE: This header may usefully be included multiple times. * The TLIB_INJECT() macro will be redefined based on whether * TLIB_INJECTIONS_ENABLED is defined. */ #undef TLIB_INJECT #if defined(TLIB_INJECTIONS_ENABLED) #define TLIB_INJECT(name, stmt) \ do\ {\ static void *injection = 0;\ if (0 == injection)\ injection = tlib_injection(name);\ if (tlib_injection_trace(injection))\ stmt;\ } while (0) #else #define TLIB_INJECT(name, stmt) do {} while (0) #endif void *tlib_injection(const char *name); int tlib_injection_trace(void *injection); void tlib_injection_enable(const char *name, const char *sym, unsigned trigger); void tlib_injection_disable(const char *name, const char *sym); ================================================ FILE: ext/tlib/testsuite.c ================================================ /** * @file tlib/testsuite.c * * @copyright 2014-2019 Bill Zissimopoulos */ #include #include #include #include #include #include #include #include struct test { char name[64]; void (*fn)(void); int optional; struct test *next; }; static struct test test_suite_sentinel = { .next = &test_suite_sentinel }; static struct test *test_suite_tail = &test_suite_sentinel; static struct test test_sentinel = { .next = &test_sentinel }; static struct test *test_tail = &test_sentinel; static void add_test_to_list(const char *name, void (*fn)(void), int optional, struct test **tail) { struct test *test = calloc(1, sizeof *test); strncpy(test->name, name, sizeof test->name - 1); test->name[sizeof test->name - 1] = '\0'; test->fn = fn; test->optional = optional; test->next = (*tail)->next; (*tail)->next = test; (*tail) = test; } void tlib_add_test_suite(const char *name, void (*fn)(void)) { add_test_to_list(name, fn, 0, &test_suite_tail); } void tlib_add_test(const char *name, void (*fn)(void)) { add_test_to_list(name, fn, 0, &test_tail); } void tlib_add_test_opt(const char *name, void (*fn)(void)) { add_test_to_list(name, fn, 1, &test_tail); } static FILE *tlib_out, *tlib_err; static jmp_buf test_jmp_buf, *test_jmp; static char assert_buf[256]; static void test_printf(const char *fmt, ...); static double run_test(struct test *test) { #if defined(_WIN64) || defined(_WIN32) #pragma comment(lib, "winmm.lib") unsigned long __stdcall timeGetTime(void); unsigned long t0 = timeGetTime(); test->fn(); unsigned long t1 = timeGetTime(); return (t1 - t0) / 1000.0; #else time_t t0 = time(0); test->fn(); time_t t1 = time(0); return difftime(t1, t0); #endif } static void do_test_default(struct test *test, int testno) { if (0 != test) { snprintf(assert_buf, sizeof assert_buf, "KO\n "); char dispname[39 + 1]; size_t displen = strlen(test->name); if (displen > sizeof dispname - 1) displen = sizeof dispname - 1; memcpy(dispname, test->name, displen); memset(dispname + displen, '.', sizeof dispname - 1 - displen); dispname[sizeof dispname - 1] = '\0'; test_printf("%s ", dispname); double d = run_test(test); test_printf("OK %.2fs\n", d); } else test_printf("--- COMPLETE ---\n"); } static void do_test_list(struct test *test, int testno) { if (0 != test) test_printf("%s\n", test->name); } static void do_test_tap(struct test *test, int testno) { if (0 != test) { snprintf(assert_buf, sizeof assert_buf, "not ok %d %s\n# ", testno + 1, test->name); run_test(test); test_printf("ok %d %s\n", testno + 1, test->name); } else test_printf("1..%d\n", testno); } static void test_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); FILE *f = tlib_out ? tlib_out : stdout; vfprintf(f, fmt, ap); fflush(f); va_end(ap); } void tlib_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); FILE *f = tlib_err ? tlib_err : stderr; vfprintf(f, fmt, ap); fflush(f); va_end(ap); } void tlib_run_tests(int argc, char *argv[]) { argc--; argv++; void (*do_test)(struct test *, int) = do_test_default; int match_any = 1, no_abort = 0; unsigned long repeat = 1; for (char **ap = argv, **aendp = ap + argc; aendp > ap; ap++) { const char *a = *ap; if ('-' == a[0]) { if (0 == strcmp("--list", a)) do_test = do_test_list; else if (0 == strcmp("--tap", a)) do_test = do_test_tap; else if (0 == strcmp("--no-abort", a)) no_abort = 1; else if (0 == strcmp("--repeat-forever", a)) repeat = ULONG_MAX; else if ('-' == a[1]) { fprintf(stderr, "tlib_run_tests: unknown option %s\n", a); exit(2); } } else match_any = 0; } for (struct test *test = test_suite_tail->next->next; 0 != test->fn; test = test->next) test->fn(); while (repeat--) { int testno = 0; for (struct test *test = test_tail->next->next; 0 != test->fn; test = test->next) { int match_arg = match_any && !test->optional; for (char **ap = argv, **aendp = ap + argc; aendp > ap; aendp--) { const char *a = aendp[-1]; int sign = a[0]; if ('+' == sign) a++; else if ('-' == sign) { if ('-' == a[1]) continue; a++; } size_t l = strlen(a); if (0 == (0 < l && '*' == a[l - 1] ? strncmp(test->name, a, l - 1) : strcmp(test->name, a))) { if ('+' == sign) match_arg = 1; else if ('-' == sign) match_arg = 0; else match_arg = !test->optional; break; } } if (!match_arg) continue; assert_buf[0] = '\0'; if (no_abort) { test_jmp = &test_jmp_buf; if (0 == setjmp(*test_jmp)) do_test(test, testno); test_jmp = 0; } else do_test(test, testno); testno++; } do_test(0, testno); } } void tlib__assert(const char *func, const char *file, int line, const char *expr) { #if defined(_WIN64) || defined(_WIN32) const char *p = strrchr(file, '\\'); #else const char *p = strrchr(file, '/'); #endif file = 0 != p ? p + 1 : file; if (0 == func) test_printf("%sASSERT(%s) failed at: %s:%d\n", assert_buf, expr, file, line); else test_printf("%sASSERT(%s) failed at %s:%d:%s\n", assert_buf, expr, file, line, func); if (0 != test_jmp) longjmp(*test_jmp, 1); } ================================================ FILE: ext/tlib/testsuite.h ================================================ /** * @file tlib/testsuite.h * * @copyright 2014-2019 Bill Zissimopoulos */ #ifndef TLIB_TESTSUITE_H_INCLUDED #define TLIB_TESTSUITE_H_INCLUDED #include /** * Assert macro * * This macro works similarly to the Standard C assert macro, except for the following differences: * *
    *
  • The macro always checks the specified expression regardless of the NDEBUG macro.
  • *
  • The macro aborts the execution of the current test, but not necessarily the execution of the * whole testsuite.
  • *
*/ #define ASSERT(expr)\ (!(expr) ? (tlib__assert(__func__, __FILE__, __LINE__, #expr), abort()) : (void)0) /** * Register a test suite for execution. * * Test suites are simple functions with prototype void testsuite(). When executed * they register individual test cases for execution. */ #define TESTSUITE(fn)\ do\ {\ void fn(void);\ tlib_add_test_suite(#fn, fn);\ } while (0) /** * Register a test case for execution. * * Test cases are simple functions with prototype void testcase(). */ #define TEST(fn)\ do\ {\ void fn(void);\ tlib_add_test(#fn, fn);\ } while (0) /** * Register an optional test case for execution. * * Test cases are simple functions with prototype void testcase(). * Optional tests are not executed by default. */ #define TEST_OPT(fn)\ do\ {\ void fn(void);\ tlib_add_test_opt(#fn, fn);\ } while (0) void tlib_add_test_suite(const char *name, void (*fn)(void)); void tlib_add_test(const char *name, void (*fn)(void)); void tlib_add_test_opt(const char *name, void (*fn)(void)); /** * Printf function. * * Use this to produce output in the appropriate tlib file stream. This function uses the local * printf facilities and understands the same format strings. */ #if defined(__GNUC__) void tlib_printf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); #else void tlib_printf(const char *fmt, ...); #endif /** * Run tests. * * This function will first execute all registered test suites, thus giving them the chance to * register any test cases. It will then execute all registered test cases according to the * command line arguments passed in argv. The command line syntax is a follows: * * Usage: testprog [--list][[--tap][--no-abort][--repeat-forever] [[+-]TESTNAME...] * *
    *
  • --list - list tests only
  • *
  • --tap - produce output in TAP format
  • *
  • --no-abort - do not abort all tests when an ASSERT fails * (only the current test is aborted)
  • *
  • --repeat-forever - repeat tests forever
  • *
* * By default all test cases are executed unless specific test cases are named. By default optional * test cases are not executed. To execute a specific test case specify its TESTNAME; if it is an * optional test case specify +TESTNAME. To excluse a test case specify -TESTNAME. * * TESTNAME may also contain a single asterisk at the end; for example, mytest* will match all test * cases that have names starting with "mytest". * * @param argc * Argument count. * @param argv * Argument vector. */ void tlib_run_tests(int argc, char *argv[]); void tlib__assert(const char *func, const char *file, int line, const char *expr); #endif ================================================ FILE: src/fusermount/fusermount-helper.c ================================================ /** * @file fusermount-helper.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include #define PROGNAME "fusermount-helper" #undef RtlFillMemory #undef RtlMoveMemory NTSYSAPI VOID NTAPI RtlFillMemory(VOID *Destination, DWORD Length, BYTE Fill); NTSYSAPI VOID NTAPI RtlMoveMemory(VOID *Destination, CONST VOID *Source, DWORD Length); #pragma function(memset) #pragma function(memcpy) static inline void *memset(void *dst, int val, size_t siz) { RtlFillMemory(dst, (DWORD)siz, val); return dst; } static inline void *memcpy(void *dst, const void *src, size_t siz) { RtlMoveMemory(dst, src, (DWORD)siz); return dst; } #define warn(format, ...) \ printlog(GetStdHandle(STD_ERROR_HANDLE), PROGNAME ": " format, __VA_ARGS__) #define fatal(ExitCode, format, ...) (warn(format, __VA_ARGS__), ExitProcess(ExitCode)) static void vprintlog(HANDLE h, const char *format, va_list ap) { char buf[1024]; /* wvsprintf is only safe with a 1024 byte buffer */ size_t len; DWORD BytesTransferred; wvsprintfA(buf, format, ap); buf[sizeof buf - 1] = '\0'; len = lstrlenA(buf); buf[len++] = '\n'; WriteFile(h, buf, (DWORD)len, &BytesTransferred, 0); } static void printlog(HANDLE h, const char *format, ...) { va_list ap; va_start(ap, format); vprintlog(h, format, ap); va_end(ap); } NTSTATUS NTAPI NtOpenSymbolicLinkObject(PHANDLE LinkHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes); NTSTATUS NTAPI NtMakeTemporaryObject(HANDLE Handle); NTSTATUS NTAPI NtClose(HANDLE Handle); static BOOL MountSet_Drive(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountHandle) { WCHAR SymlinkBuf[6]; UNICODE_STRING Symlink; OBJECT_ATTRIBUTES Obja; NTSTATUS Result; *PMountHandle = 0; if (!DefineDosDeviceW(DDD_RAW_TARGET_PATH, MountPoint, VolumeName)) return FALSE; memcpy(SymlinkBuf, L"\\??\\X:", sizeof SymlinkBuf); SymlinkBuf[4] = MountPoint[0]; Symlink.Length = Symlink.MaximumLength = sizeof SymlinkBuf; Symlink.Buffer = SymlinkBuf; memset(&Obja, 0, sizeof Obja); Obja.Length = sizeof Obja; Obja.ObjectName = &Symlink; Obja.Attributes = OBJ_CASE_INSENSITIVE; Result = NtOpenSymbolicLinkObject(PMountHandle, DELETE, &Obja); if (NT_SUCCESS(Result)) { Result = NtMakeTemporaryObject(*PMountHandle); if (!NT_SUCCESS(Result)) { NtClose(*PMountHandle); *PMountHandle = 0; } } return TRUE; } static BOOL MountSet(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountHandle) { *PMountHandle = 0; if (L'*' == MountPoint[0] && ':' == MountPoint[1] && L'\0' == MountPoint[2]) { DWORD Drives; WCHAR Drive; Drives = GetLogicalDrives(); if (0 == Drives) return FALSE; for (Drive = 'Z'; 'D' <= Drive; Drive--) if (0 == (Drives & (1 << (Drive - 'A')))) { MountPoint[0] = Drive; if (MountSet_Drive(VolumeName, MountPoint, PMountHandle)) return TRUE; } MountPoint[0] = L'*'; SetLastError(ERROR_NO_SUCH_DEVICE); /* error code chosen for WinFsp compatibility (FspMountSet) */ return FALSE; } else if ( ( (L'A' <= MountPoint[0] && MountPoint[0] <= L'Z') || (L'a' <= MountPoint[0] && MountPoint[0] <= L'z') ) && L':' == MountPoint[1] && L'\0' == MountPoint[2]) return MountSet_Drive(VolumeName, MountPoint, PMountHandle); else { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } } int wmain(int argc, wchar_t **argv) { PWSTR VolumeName; PWSTR MountPoint; HANDLE MountHandle; WCHAR WildMountPoint[] = L"*:"; UINT8 MountPointU8[MAX_PATH]; UINT8 Buffer[1]; DWORD BytesTransferred; if (2 > argc || 3 < argc) fatal(2, "usage: VolumeName [WinMountPoint]"); VolumeName = argv[1]; MountPoint = 2 < argc ? argv[2] : WildMountPoint; if (!MountSet(VolumeName, MountPoint, &MountHandle)) fatal(1, "cannot set Windows mount point %S (LastError=%lu)", MountPoint, GetLastError()); if (0 == WideCharToMultiByte(CP_UTF8, 0, MountPoint, -1, MountPointU8, MAX_PATH, 0, 0)) fatal(1, "invalid Windows mount point (LastError=%lu)", GetLastError()); BytesTransferred = lstrlenA(MountPointU8) + 1; if (!WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), MountPointU8, BytesTransferred, &BytesTransferred, 0)) fatal(1, "cannot write to stdout (LastError=%lu)", GetLastError()); if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE), Buffer, sizeof Buffer, &BytesTransferred, 0)) fatal(1, "cannot read from stdin (LastError=%lu)", GetLastError()); return 0; } void wmainCRTStartup(void) { DWORD Argc; PWSTR *Argv; Argv = CommandLineToArgvW(GetCommandLineW(), &Argc); if (0 == Argv) ExitProcess(GetLastError()); ExitProcess(wmain(Argc, Argv)); } ================================================ FILE: src/fusermount/fusermount.c ================================================ /** * @file fusermount.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const char *progname; static struct { const char *mountpoint; const char *opts; int unmount; int lazy; int quiet; } args; struct mount_opts { FSP_FSCTL_VOLUME_PARAMS VolumeParams; char WinMountPoint[260]; int set_attr_timeout, attr_timeout; int set_FileInfoTimeout, set_DirInfoTimeout, set_EaTimeout, set_VolumeInfoTimeout, set_KeepFileCache; unsigned max_read; }; static void warn(const char *format, ...) { va_list ap; va_start(ap, format); if (!args.quiet) { fprintf(stderr, "%s: ", progname); vfprintf(stderr, format, ap); fprintf(stderr, "\n"); } va_end(ap); } static const char *opt_parse_arg(const char *opt, char *buf, size_t siz) { const char *p = opt; char *q = buf, *endq = q + siz; if (0 == p) return 0; while (endq > q && '\0' != *p && ',' != *p) { if ('\\' == p[0] && '\0' != p[1]) p++; *q++ = *p++; } if (endq == q || (buf == q && '\0' == *p)) return 0; *q++ = '\0'; if ('\0' != *p) p++; return p; } static void utf8_to_utf16(const char *src0, uint16_t *dst, size_t siz) { const uint8_t *src = src0; uint16_t *dstend = dst + siz / sizeof(uint16_t); while (dstend > dst) { uint32_t c = *src++; uint32_t w = 0xfffd; /* unicode replacement char */ if (0x80 > c) w = c; else if (0xc0 > c) ; else if (0xe0 > c) { c = (c & 0x1f) << 6; if (0x80 != (*src & 0x80)) goto copy; c |= *src++ & 0x3f; w = c; } else if (0xf0 > c) { c = (c & 0x0f) << 12; if (0x80 != (*src & 0x80)) goto copy; c |= (uint32_t)(*src++ & 0x3f) << 6; if (0x80 != (*src & 0x80)) goto copy; c |= *src++ & 0x3f; w = c; } else if (0xf8 > c) { /* we do not support true UTF-16; just skip over 3 continuation bytes */ if (0x80 != (*src & 0x80)) goto copy; src++; if (0x80 != (*src & 0x80)) goto copy; src++; if (0x80 != (*src & 0x80)) goto copy; src++; } copy: *dst++ = (uint16_t)w; if (0 == c) break; } if (sizeof(uint16_t) <= siz) dstend[-1] = 0; } static int get_mnt_id(const char *mountpoint) { FILE *file = 0; char line[4096]; char path[4096]; int mnt_id = -1, m; file = fopen("/proc/self/mountinfo", "rb"); if (0 == file) goto exit; while (0 != fgets(line, sizeof line, file)) { if (2 == sscanf(line, "%d %*d %*s %*s %4096s %*s", &m, path) && 0 == strcmp(mountpoint, path)) { mnt_id = m; break; } } if (-1 == mnt_id) errno = ENODEV; exit: if (0 != file) fclose(file); return mnt_id; } static void mount_opt_parse(struct mount_opts *mo) { const char *opt; char optbuf[4096], *optarg, *optval, empty = '\0'; memset(mo, 0, sizeof *mo); mo->VolumeParams.Version = sizeof(FSP_FSCTL_VOLUME_PARAMS); mo->VolumeParams.FileInfoTimeout = 1000; mo->VolumeParams.FlushAndPurgeOnCleanup = 1; /* * Libfuse does not recognize any of our options and rejects them. * So (for now at least) prefix our options with "context=", which * Libfuse accepts (to support SELinux). * * So to pass "Volume=X:" use "context=Volume=X:". */ for ( opt = opt_parse_arg(args.opts, optbuf, sizeof optbuf); 0 != opt; opt = opt_parse_arg(opt, optbuf, sizeof optbuf)) { optarg = optbuf; optval = strchr(optarg, '='); if (0 != optval) *optval++ = '\0'; else optval = ∅ if (0 == strcmp(optarg, "context")) { optarg = optval; optval = strchr(optarg, '='); if (0 != optval) *optval++ = '\0'; else optval = ∅ } if (0 == strcmp(optarg, "Volume")) { strncpy(mo->WinMountPoint, optval, sizeof mo->WinMountPoint); mo->WinMountPoint[sizeof mo->WinMountPoint - 1] = '\0'; for (char *P = mo->WinMountPoint; *P; P++) if ('/' == *P) *P = '\\'; } else if (0 == strcmp(optarg, "attr_timeout")) { mo->set_attr_timeout = 1; mo->attr_timeout = (int)strtol(optval, 0, 10); } else if (0 == strcmp(optarg, "SectorSize")) mo->VolumeParams.SectorSize = (UINT16)strtoul(optval, 0, 10); else if (0 == strcmp(optarg, "SectorsPerAllocationUnit")) mo->VolumeParams.SectorsPerAllocationUnit = (UINT16)strtoul(optval, 0, 10); else if (0 == strcmp(optarg, "MaxComponentLength")) mo->VolumeParams.MaxComponentLength = (UINT16)strtoul(optval, 0, 10); else if (0 == strcmp(optarg, "VolumeCreationTime")) mo->VolumeParams.VolumeCreationTime = (UINT64)strtol(optval, 0, 0); else if (0 == strcmp(optarg, "VolumeSerialNumber")) mo->VolumeParams.VolumeSerialNumber = (UINT32)strtoul(optval, 0, 16); else if (0 == strcmp(optarg, "FileInfoTimeout")) { mo->set_FileInfoTimeout = 1; mo->VolumeParams.FileInfoTimeout = (UINT32)strtol(optval, 0, 10); } else if (0 == strcmp(optarg, "DirInfoTimeout")) { mo->set_DirInfoTimeout = 1; mo->VolumeParams.DirInfoTimeout = (UINT32)strtol(optval, 0, 10); } else if (0 == strcmp(optarg, "EaTimeout")) { mo->set_EaTimeout = 1; mo->VolumeParams.EaTimeout = (UINT32)strtol(optval, 0, 10); } else if (0 == strcmp(optarg, "VolumeInfoTimeout")) { mo->set_VolumeInfoTimeout = 1; mo->VolumeParams.VolumeInfoTimeout = (UINT32)strtol(optval, 0, 10); } else if (0 == strcmp(optarg, "KeepFileCache")) mo->set_KeepFileCache = 1; else if (0 == strcmp(optarg, "UNC") || 0 == strcmp(optarg, "VolumePrefix")) { utf8_to_utf16(optval, mo->VolumeParams.Prefix, sizeof mo->VolumeParams.Prefix); for (WCHAR *P = mo->VolumeParams.Prefix; *P; P++) if ('/' == *P) *P = '\\'; } else if (0 == strcmp(optarg, "FileSystemName")) { utf8_to_utf16("FUSE-", mo->VolumeParams.FileSystemName, sizeof mo->VolumeParams.FileSystemName); utf8_to_utf16(optval, mo->VolumeParams.FileSystemName + 5, sizeof mo->VolumeParams.FileSystemName - 5 * sizeof(WCHAR)); } } if (!mo->set_FileInfoTimeout && mo->set_attr_timeout) mo->VolumeParams.FileInfoTimeout = (UINT32)(mo->attr_timeout * 1000); if (mo->set_DirInfoTimeout) mo->VolumeParams.DirInfoTimeoutValid = 1; if (mo->set_EaTimeout) mo->VolumeParams.EaTimeoutValid = 1; if (mo->set_VolumeInfoTimeout) mo->VolumeParams.VolumeInfoTimeoutValid = 1; if (mo->set_KeepFileCache) mo->VolumeParams.FlushAndPurgeOnCleanup = 0; mo->VolumeParams.CaseSensitiveSearch = 1; mo->VolumeParams.CasePreservedNames = 1; mo->VolumeParams.PersistentAcls = 1; mo->VolumeParams.ReparsePoints = 1; mo->VolumeParams.ReparsePointsAccessCheck = 0; mo->VolumeParams.NamedStreams = 0; mo->VolumeParams.ReadOnlyVolume = 0; mo->VolumeParams.PostCleanupWhenModifiedOnly = 1; mo->VolumeParams.PassQueryDirectoryFileName = 1; mo->VolumeParams.DeviceControl = 1; if ('\0' == mo->VolumeParams.FileSystemName[0]) utf8_to_utf16("FUSE", mo->VolumeParams.FileSystemName, sizeof mo->VolumeParams.FileSystemName); if (mo->VolumeParams.SectorSize < 512 || mo->VolumeParams.SectorSize > 4096) mo->VolumeParams.SectorSize = 4096; if (mo->VolumeParams.SectorsPerAllocationUnit == 0) mo->VolumeParams.SectorsPerAllocationUnit = 1; if (0 == mo->VolumeParams.MaxComponentLength || mo->VolumeParams.MaxComponentLength > 255) mo->VolumeParams.MaxComponentLength = 255; if (0 == mo->VolumeParams.VolumeCreationTime) { struct timeval tv = { 0 }; gettimeofday(&tv, 0); mo->VolumeParams.VolumeCreationTime = (UINT64) ((int64_t)tv.tv_sec * 10000000 + (int64_t)tv.tv_usec * 10 + 116444736000000000LL); } if (0 == mo->VolumeParams.VolumeSerialNumber) mo->VolumeParams.VolumeSerialNumber = (UINT32)(mo->VolumeParams.VolumeCreationTime >> 32) ^ (UINT32)(mo->VolumeParams.VolumeCreationTime & 0xffffffff); } static int start_winmount_helper(const char *VolumeName, char WinMountPoint[260], pid_t *pidp, int *ofdp) { int success = 0; pid_t pid; int ifd[2] = { -1, -1 }; int ofd[2] = { -1, -1 }; char *argv[4]; char *p, *endp; ssize_t bytes; *pidp = -1; *ofdp = -1; if (-1 == pipe(ifd) || -1 == pipe(ofd)) { warn("winmount: cannot create pipe: %s", strerror(errno)); goto exit; } argv[0] = "/usr/bin/fusermount-helper.exe"; argv[1] = (char *)VolumeName; argv[2] = '\0' != WinMountPoint[0] ? (char *)WinMountPoint : 0; argv[3] = 0; pid = fork(); if (-1 == pid) { warn("winmount: cannot fork: %s", strerror(errno)); goto exit; } else if (0 != pid) *pidp = pid; else { /* drop privileges */ uid_t uid = getuid(); gid_t gid = getgid(); setgroups(1, &gid); setreuid(uid, uid); setregid(gid, gid); if (-1 == dup2(ifd[1], 1) || -1 == dup2(ofd[0], 0)) { warn("winmount: cannot dup2: %s", strerror(errno)); exit(1); } close(ofd[1]); close(ofd[0]); close(ifd[1]); close(ifd[0]); if (-1 == execv(argv[0], argv)) warn("winmount: cannot execute %s: %s", argv[0], strerror(errno)); exit(1); } close(ifd[1]); ifd[1] = -1; close(ofd[0]); ofd[0] = -1; for (p = WinMountPoint, endp = WinMountPoint + 260 - 1; endp > p; p += bytes) { bytes = read(ifd[0], p, (size_t)(endp - p)); if (-1 == bytes) { if (EINTR != errno) { warn("winmount: cannot read output: %s", strerror(errno)); goto exit; } bytes = 0; } else if (0 == bytes || 0 != memchr(p, 0, (size_t)bytes)) { p += bytes; break; } } *p = '\0'; if (WinMountPoint == p) { warn("winmount: no output"); goto exit; } close(ifd[0]); ifd[0] = -1; *ofdp = ofd[1]; ofd[1] = -1; success = 1; exit: if (-1 != ofd[1]) close(ofd[1]); if (-1 != ofd[0]) close(ofd[0]); if (-1 != ifd[1]) close(ifd[1]); if (-1 != ifd[0]) close(ifd[0]); return success ? 0 : -1; } static void stop_winmount_helper(pid_t pid, int ofd) { ssize_t bytes; (void)bytes; bytes = write(ofd, "STOP", 4 + 1); close(ofd); waitpid(pid, 0, 0); } static int spawn_lxmount_helper(char WinMountPoint[260], const char *mountpoint, int fusefd, UINT64 VolumeId) { /* * Spawn a child process to perform a Linux mount of the WinFsp volume asynchronously. * * This is necessary to avoid the deadlock described below. * * First observe that when mount(2) happens the FUSE file system is not yet ready to * accept file system requests. So any file system request will be queued within WinFsp * and will not be retrieved by the FUSE file system until after (it thinks that) the * mount(2) has completed. * * Now when mount(2) is invoked with type "drvfs", LXCORE attempts to open the volume * passed in the source argument (e.g. if the source argument is "Z:", then LXCORE will * attempt to open volume "Z:"). This should normally not be a problem because WinFsp * handles volume opens without forwarding them to the user mode file system. Unfortunately * some system filters convert a volume ("Z:") open request to a root directory ("Z:\") * open request, which is a request that must be handled by the user mode file system. * But the user mode file system is waiting for the mount/fusermount to complete, before it * can process requests. Hence deadlock! * * In order to work around this problem we perform the mount(2) asynchronously in a child * process. This of course means that we lie to the FUSE file system that the mount(2) was * successful, thus allowing it to process the root directory open request, which then * allows the mount(2) call to complete. The drawback is that if the mount(2) fails for * some reason the FUSE file system never hears about it. (However this is not considered * a huge problem, because the FUSE file system will still service the Windows drive that * we allocated for it correctly (see start_winmount_helper).) */ pid_t pid; int status; /* fork the intermediate process */ pid = fork(); if (-1 == pid) { warn("lxmount: cannot fork intermediate process: %s", strerror(errno)); return -1; } else if (0 != pid) { /* wait for the intermediate process */ return pid == waitpid(pid, &status, 0) && WIFEXITED(status) && 0 == WEXITSTATUS(status) ? 0 : -1; } /* become a session leader and ignore SIGHUP */ setsid(); signal(SIGHUP, SIG_IGN); /* fork a second time to get the process that will perform the Linux mount */ pid = fork(); if (-1 == pid) { warn("lxmount: cannot fork mount process: %s", strerror(errno)); exit(1); } else if (0 != pid) /* exit the intermediate process; our child will be reaped by the init process */ exit(0); /* * MOUNT PROCESS * * Grand-child of original fusermount process. */ int success = 0; int mounted = 0, mnt_id; WSLFUSE_IOCTL_LXMOUNT_ARG LxMountArg; /* * Close the passed fusefd and reopen /dev/fuse. We will use the reopened fd * to communicate with WslFuse using special ioctl's. * * The reason for this is subtle: consider the earlier discussed deadlock and * the case where the FUSE file system fails to service the root directory open * request (e.g. because it crashed). Now we are in a situation where mount(2) * is waiting for a root directory open request to complete; this request is stuck * inside WinFsp; it has been retrieved by wslfuse and is either pending or * processing within the FUSE file system. Suppose now that the file system * terminates abruptly for some reason. The open request will never complete and * hence (a form of) deadlock again! * * Normally this is not a problem because upon termination of the FUSE process * all its file descriptors will be closed and WslFuse and WinFsp will have a * chance to purge their internal I/O queues thus canceling the root directory * open request, which allows mount(2) to complete. However when we forked our * mount process, the original fusefd was cloned and this keeps our internal I/O * queues alive. For this reason we have to close the fusefd in the mount process. */ close(fusefd); fusefd = open("/dev/fuse", O_RDWR); if (-1 == fusefd) { warn("lxmount: cannot open /dev/fuse: %s", strerror(errno)); goto exit; } /* * Mount the WinFsp volume using drvfs. */ if (-1 == mount(WinMountPoint, mountpoint, "drvfs", 0, 0)) { warn("lxmount: cannot mount %s: %s", mountpoint, strerror(errno)); goto exit; } mounted = 1; /* * Get the mnt_id of the newly mounted file system. */ mnt_id = get_mnt_id(mountpoint); if (-1 == mnt_id) { warn("lxmount: cannot get mnt_id: %s", strerror(errno)); goto exit; } /* * Associate the WSL mnt_id with the /dev/fuse fd. */ memset(&LxMountArg, 0, sizeof LxMountArg); LxMountArg.Operation = '+'; LxMountArg.VolumeId = VolumeId; LxMountArg.LxMountId = (UINT64)mnt_id; if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg)) { warn("lxmount: cannot ioctl(m) /dev/fuse: %s", strerror(errno)); goto exit; } success = 1; exit: if (!success) { if (mounted) umount2(mountpoint, UMOUNT_NOFOLLOW); } exit(success ? 0 : 1); /* should not happen */ return -1; } static void do_mount(void) { int success = 0; struct mount_opts mo; const char *env; int commfd, fusefd = -1; WSLFUSE_IOCTL_CREATEVOLUME_ARG CreateArg; WSLFUSE_IOCTL_WINMOUNT_ARG WinMountArg; pid_t winmount_pid = -1; int winmount_fd = -1; struct msghdr msg; struct cmsghdr *cmsg; char cmsgbuf[CMSG_SPACE(sizeof fusefd)]; struct iovec iov; char dummy = 0; mount_opt_parse(&mo); /* * Get the socket fd sent to us by the file system (via libfuse) from the environment. * We will use this fd to send our /dev/fuse fd to the file system once mounting completes. */ env = getenv("_FUSE_COMMFD"); if (0 == env) { warn("mount: environment variable _FUSE_COMMFD missing"); goto exit; } commfd = atoi(env); /* * Open the /dev/fuse device. We use the returned fd to communicate with WslFuse using * special ioctl's. We will also return the fd to the file system via COMMFD. */ fusefd = open("/dev/fuse", O_RDWR); if (-1 == fusefd) { warn("mount: cannot open /dev/fuse: %s", strerror(errno)); goto exit; } /* * Send an ioctl to instruct WslFuse to create a new WinFsp volume. */ memset(&CreateArg, 0, sizeof CreateArg); memcpy(&CreateArg.VolumeParams, &mo.VolumeParams, sizeof mo.VolumeParams); if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_CREATEVOLUME, &CreateArg)) { warn("mount: cannot ioctl(C) /dev/fuse: %s", strerror(errno)); goto exit; } /* * Start the Windows side helper process to create the Windows mount point. */ if (-1 == start_winmount_helper(CreateArg.VolumeName, mo.WinMountPoint, &winmount_pid, &winmount_fd)) goto exit; /* * Associate the Windows mount point with the /dev/fuse fd. */ memset(&WinMountArg, 0, sizeof WinMountArg); memcpy(WinMountArg.WinMountPoint, mo.WinMountPoint, sizeof WinMountArg.WinMountPoint); if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_WINMOUNT, &WinMountArg)) { warn("mount: cannot ioctl(M) /dev/fuse: %s", strerror(errno)); goto exit; } /* * Send the /dev/fuse fd to the file system using COMMFD. */ memset(&msg, 0, sizeof msg); msg.msg_control = cmsgbuf; msg.msg_controllen = sizeof cmsgbuf; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof fusefd); memcpy(CMSG_DATA(cmsg), &fusefd, sizeof fusefd); msg.msg_controllen = cmsg->cmsg_len; msg.msg_iov = &iov; msg.msg_iovlen = 1; iov.iov_base = &dummy; iov.iov_len = sizeof dummy; while (-1 == sendmsg(commfd, &msg, 0)) if (EINTR != errno) { warn("mount: cannot sendmsg to _FUSE_COMMFD: %s", strerror(errno)); goto exit; } /* * Spawn a child process to perform a Linux mount of the WinFsp volume asynchronously. */ if (-1 == spawn_lxmount_helper(mo.WinMountPoint, args.mountpoint, fusefd, CreateArg.VolumeId)) goto exit; success = 1; exit: if (-1 != winmount_pid) stop_winmount_helper(winmount_pid, winmount_fd); if (-1 != fusefd) close(fusefd); if (!success) exit(1); exit(0); } static void do_unmount(void) { int success = 0; int fusefd = -1; int mnt_id; WSLFUSE_IOCTL_LXMOUNT_ARG LxMountArg; /* * Open the /dev/fuse device. */ fusefd = open("/dev/fuse", O_RDWR); if (-1 == fusefd) { warn("unmount: cannot open /dev/fuse: %s", strerror(errno)); goto exit; } /* * Get the mnt_id of the previously mounted file system. */ mnt_id = get_mnt_id(args.mountpoint); if (-1 == mnt_id) { warn("unmount: cannot get mnt_id: %s", strerror(errno)); goto exit; } /* * Verify the WSL mnt_id with WslFuse. */ memset(&LxMountArg, 0, sizeof LxMountArg); LxMountArg.Operation = '?'; LxMountArg.LxMountId = (UINT64)mnt_id; if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg)) { warn("unmount: unknown mountpoint %s", args.mountpoint); goto exit; } /* * Unmount the previously mounted file system. */ if (-1 == umount2(args.mountpoint, args.lazy ? MNT_DETACH : 0)) /* UMOUNT_NOFOLLOW not supported in WSL1 */ { warn("unmount: cannot unmount %s: %s", args.mountpoint, strerror(errno)); goto exit; } /* * Disassociate the WSL mnt_id from the /dev/fuse fd. */ memset(&LxMountArg, 0, sizeof LxMountArg); LxMountArg.Operation = '-'; LxMountArg.LxMountId = (UINT64)mnt_id; if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg) && ENOENT != errno) { warn("unmount: cannot ioctl(m) /dev/fuse: %s", strerror(errno)); goto exit; } success = 1; exit: if (-1 != fusefd) close(fusefd); if (!success) exit(1); exit(0); } static char *realpath_parent(const char *path) { char *resolved = 0; char *pathcopy[2] = { 0, 0 }; const char *parent, *leaf; char linkbuf[PATH_MAX]; size_t rlen, llen; pathcopy[0] = strdup(path); if (0 == pathcopy[0]) goto fail; pathcopy[1] = strdup(path); if (0 == pathcopy[1]) goto fail; resolved = malloc(PATH_MAX); if (0 == resolved) goto fail; parent = dirname(pathcopy[0]); leaf = basename(pathcopy[1]); if (0 == realpath(parent, resolved)) goto fail; rlen = strlen(resolved); llen = strlen(leaf); if (PATH_MAX < rlen + llen + 2) { errno = ENAMETOOLONG; goto fail; } resolved[rlen] = '/'; memcpy(resolved + rlen + 1, leaf, llen); resolved[rlen + 1 + llen] = '\0'; if (-1 != readlink(resolved, linkbuf, sizeof linkbuf)) { errno = EINVAL; goto fail; } else if (EINVAL != errno) goto fail; free(pathcopy[1]); free(pathcopy[0]); return resolved; fail: free(resolved); free(pathcopy[1]); free(pathcopy[0]); return 0; } static void do_version(void) { fprintf(stdout, "%s version: %s\n", progname, "wslfuse"); exit(0); } static void usage(void) { warn( "%s: [options] mountpoint\n" "Options:\n" " -h print help\n" " -V print version\n" " -o opt[,opt...] mount options\n" " -u unmount\n" " -z lazy unmount\n" " -q quiet\n" "", progname); exit(2); } int main(int argc, char *argv[]) { progname = basename(argv[0]); static struct option longopts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'V' }, { "unmount", no_argument, 0, 'u' }, { "lazy", no_argument, 0, 'z' }, { "quiet", no_argument, 0, 'q' }, { 0 }, }; int quiet = 0; int opt; while (-1 != (opt = getopt_long(argc, argv, "hVo:uzq", longopts, 0))) switch (opt) { default: case 'h': usage(); break; case 'V': do_version(); break; case 'o': args.opts = optarg; break; case 'u': args.unmount = 1; break; case 'z': args.lazy = 1; break; case 'q': quiet = 1; break; } if (argc != optind + 1) usage(); args.quiet = quiet; if (!args.unmount) args.mountpoint = realpath(argv[optind], 0); else args.mountpoint = realpath_parent(argv[optind]); if (0 == args.mountpoint) { warn("mountpoint: %s", strerror(errno)); exit(1); } if (!args.unmount) do_mount(); do_unmount(); return 0; } ================================================ FILE: src/fusermount/install.sh ================================================ set -e if [ "$(id -u)" != "0" ]; then echo "must be run as superuser" 1>&2; exit 1 fi cd "$(dirname "$0")" # fusermount cmp_install() { local src="" local dst="" for arg in "$@"; do src="$dst"; dst="$arg"; done cmp -s "$src" "$dst" || install "$@" } cmp_install --backup=numbered -o0 -g0 -mu=srwx,go=rx fusermount.out /usr/bin/fusermount cmp_install --backup=numbered -o0 -g0 -mu=srwx,go=rx fusermount.out /usr/bin/fusermount3 cmp_install -o0 -g0 -mu=rwx,go=rx fusermount-helper.exe /usr/bin/fusermount-helper.exe # /dev/fuse echo c /dev/fuse 0666 root root - 10:229 > /etc/tmpfiles.d/wslfuse.conf systemd-tmpfiles --create wslfuse.conf echo FUSE for WSL1 user space components installed ================================================ FILE: src/fusermount/uninstall.sh ================================================ #set -x if [ "$(id -u)" != "0" ]; then echo "must be run as superuser" 1>&2; exit 1 fi cd "$(dirname "$0")" # /dev/fuse rm -f /etc/tmpfiles.d/wslfuse.conf rm -f /dev/fuse # fusermount uninstall() { local src="$1" local dst="$2" if cmp -s "$src" "$dst"; then local bak=$(ls -1rv "$dst".~*~ 2>/dev/null | head -1) if [ -n "$bak" ]; then mv -f "$bak" "$dst" else rm -f "$dst" fi fi } uninstall fusermount.out /usr/bin/fusermount uninstall fusermount.out /usr/bin/fusermount3 rm -f /usr/bin/fusermount-helper.exe echo FUSE for WSL1 user space components uninstalled ================================================ FILE: src/shared/km/cache.c ================================================ /** * @file shared/km/cache.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include /* * FUSE "entry" cache * * The cache is implemented as a hash table that maps parent inode number, child name * tuples to FUSE protocol "entries": * -> ("entry") * * There are two important complications: * * (1) Entries have an expiration time after which they may no longer be valid. * Entries that have expired must not be returned to users of this class and must eventually * be "forgotten" (i.e. a FUSE FORGET message must be sent to the user mode file system). * * (2) Entries may be in use when they become expired/invalid. In this case the * corresponding FORGET message must be delayed to ensure that the user mode file system * keeps the relevant inode information around (even if the associated information is * expired). * * To accommodate complication (1) this implementation maintains cached entries in an LRU * (least-recently-used) list and expires them periodically. It should be noted that this * implementation does not sort entries by expiration time; so it is possible for an entry * that has not expired but was not recently used to be purged prior to an entry that has * expired, but was recently used. * * To accommodate complication (2) this implementation maintains a list of monotonic * "generations" that control when entries are actually "forgotten". As file system * operations arrive, the current generation is computed from the "interrupt time" * and a reference is taken on that generation (i.e. a reference count is incremented). * When the operation is complete the reference on the associated generation is released * (i.e. the reference count is decremented). If there are no remaining references on the * generation (i.e. the reference count is zero) the generation can be "forgotten", which * means that all entries that have expired and have not been used since the generation's * time can now be "forgotten" (i.e. the corresponding FUSE messages can be sent). * * These two primary complications together with the fact that the implementation must * deal with failures and re-setting existing entries make the code rather complicated. */ NTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache); VOID FuseCacheDelete(FUSE_CACHE *Cache); VOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache, FUSE_INSTANCE *Instance, UINT64 ExpirationTime); NTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen); VOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen); BOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name, FUSE_PROTO_ENTRY *Entry, PVOID *PItem); VOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name, FUSE_PROTO_ENTRY *Entry, PVOID *PItem); VOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name); VOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item); VOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item); VOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item); VOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList); BOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseCacheCreate) #pragma alloc_text(PAGE, FuseCacheDelete) #pragma alloc_text(PAGE, FuseCacheExpirationRoutine) #pragma alloc_text(PAGE, FuseCacheReferenceGen) #pragma alloc_text(PAGE, FuseCacheDereferenceGen) #pragma alloc_text(PAGE, FuseCacheGetEntry) #pragma alloc_text(PAGE, FuseCacheSetEntry) #pragma alloc_text(PAGE, FuseCacheRemoveEntry) #pragma alloc_text(PAGE, FuseCacheReferenceItem) #pragma alloc_text(PAGE, FuseCacheDereferenceItem) #pragma alloc_text(PAGE, FuseCacheQuickExpireItem) #pragma alloc_text(PAGE, FuseCacheDeleteForgotten) #pragma alloc_text(PAGE, FuseCacheForgetOne) #endif typedef struct _FUSE_CACHE_ITEM FUSE_CACHE_ITEM; struct _FUSE_CACHE { ULONG Capacity; BOOLEAN CaseInsensitive; FAST_MUTEX Mutex; LIST_ENTRY GenList; LIST_ENTRY ItemList; LIST_ENTRY ForgetList; ULONG ItemCount; ULONG ItemBucketCount; PVOID ItemBuckets[]; }; struct _FUSE_CACHE_GEN { LIST_ENTRY ListEntry; LONG RefCount; UINT64 InterruptTime; }; struct _FUSE_CACHE_ITEM { struct _FUSE_CACHE_ITEM *DictNext; LIST_ENTRY ListEntry; BOOLEAN NoForget; ULONG Hash; UINT64 ParentIno; STRING Name; UINT64 NLookup; UINT64 ExpirationTime; UINT64 LastUsedTime; FUSE_PROTO_ENTRY Entry; LONG QuickExpiry; LONG RefCount; CHAR NameBuf[]; }; static inline UINT64 FuseCacheForgetTime(FUSE_CACHE *Cache, UINT64 InterruptTime) { if (!IsListEmpty(&Cache->GenList)) { FUSE_CACHE_GEN *Gen = CONTAINING_RECORD(Cache->GenList.Flink, FUSE_CACHE_GEN, ListEntry); if (InterruptTime >= Gen->InterruptTime) InterruptTime = Gen->InterruptTime - 1; } return InterruptTime; } static inline BOOLEAN FuseCacheForgetNextItem(FUSE_CACHE *Cache, UINT64 ExpirationTime, PLIST_ENTRY ForgetList) { if (!IsListEmpty(&Cache->ForgetList)) { FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Cache->ForgetList.Flink, FUSE_CACHE_ITEM, ListEntry); if (FuseCacheForgetTime(Cache, ExpirationTime) >= Item->LastUsedTime) { RemoveEntryList(&Item->ListEntry); InsertTailList(ForgetList, &Item->ListEntry); return TRUE; } } return FALSE; } static inline BOOLEAN FuseCacheExpireItem(FUSE_CACHE *Cache, FUSE_CACHE_ITEM *Item) { ULONG HashIndex = Item->Hash % Cache->ItemBucketCount; for (FUSE_CACHE_ITEM **P = (PVOID)&Cache->ItemBuckets[HashIndex]; *P; P = &(*P)->DictNext) if (*P == Item) { *P = (*P)->DictNext; RemoveEntryList(&Item->ListEntry); Cache->ItemCount--; if (0 == InterlockedDecrement(&Item->RefCount)) InsertTailList(&Cache->ForgetList, &Item->ListEntry); return TRUE; } return FALSE; } static inline BOOLEAN FuseCacheExpireNextItem(FUSE_CACHE *Cache, UINT64 ExpirationTime) { if (!IsListEmpty(&Cache->ItemList)) { FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Cache->ItemList.Flink, FUSE_CACHE_ITEM, ListEntry); if (ExpirationTime >= Item->ExpirationTime || InterlockedCompareExchange(&Item->QuickExpiry, 1, 1)) return FuseCacheExpireItem(Cache, Item); } return FALSE; } static inline size_t hash_chars(const char *s, size_t length) { /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */ size_t h = 5381; for (const char *t = s + length; t > s; ++s) h = 33 * h + *s; return h; } static inline size_t hash_upper_chars(const char *s, size_t length) { /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */ size_t h = 5381; for (const char *t = s + length; t > s; ++s) h = 33 * h + RtlUpperChar(*s); return h; } static inline ULONG FuseCacheHash(UINT64 ParentIno, PSTRING Name, BOOLEAN CaseInsensitive) { return (ULONG)FuseHashMix64(ParentIno) ^ (0 != Name ? (ULONG)(CaseInsensitive ? hash_upper_chars(Name->Buffer, Name->Length) : hash_chars(Name->Buffer, Name->Length)) : 0); } static inline FUSE_CACHE_ITEM *FuseCacheLookupHashedItem(FUSE_CACHE *Cache, ULONG Hash, UINT64 ParentIno, PSTRING Name) { FUSE_CACHE_ITEM *Item = 0; ULONG HashIndex = Hash % Cache->ItemBucketCount; for (FUSE_CACHE_ITEM *ItemX = Cache->ItemBuckets[HashIndex]; ItemX; ItemX = ItemX->DictNext) if (ItemX->Hash == Hash && ItemX->ParentIno == ParentIno && RtlEqualString(&ItemX->Name, Name, Cache->CaseInsensitive)) { Item = ItemX; break; } return Item; } static inline VOID FuseCacheAddItem(FUSE_CACHE *Cache, FUSE_CACHE_ITEM *Item) { ULONG HashIndex = Item->Hash % Cache->ItemBucketCount; #if DBG for (FUSE_CACHE_ITEM *ItemX = Cache->ItemBuckets[HashIndex]; ItemX; ItemX = ItemX->DictNext) if (ItemX->Hash == Item->Hash && ItemX->ParentIno == Item->ParentIno && RtlEqualString(&ItemX->Name, &Item->Name, Cache->CaseInsensitive)) { ASSERT(0); } #endif Item->DictNext = Cache->ItemBuckets[HashIndex]; Cache->ItemBuckets[HashIndex] = Item; /* mark as most-recently used */ InsertTailList(&Cache->ItemList, &Item->ListEntry); Cache->ItemCount++; } static inline FUSE_CACHE_ITEM *FuseCacheUpdateHashedItem(FUSE_CACHE *Cache, ULONG Hash, UINT64 ParentIno, PSTRING Name, UINT64 ExpirationTime, UINT64 LastUsedTime, FUSE_PROTO_ENTRY *Entry) { FUSE_CACHE_ITEM *Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name); if (0 != Item) { if (Entry->nodeid == Item->Entry.nodeid && !InterlockedCompareExchange(&Item->QuickExpiry, 1, 1)) { Item->NLookup++; Item->ExpirationTime = ExpirationTime; Item->LastUsedTime = LastUsedTime; RtlCopyMemory(&Item->Entry, Entry, sizeof Item->Entry); /* mark as most-recently used */ RemoveEntryList(&Item->ListEntry); InsertTailList(&Cache->ItemList, &Item->ListEntry); } else { FuseCacheExpireItem(Cache, Item); Item = 0; } } return Item; } NTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache) { PAGED_CODE(); FUSE_CACHE *Cache; ULONG CacheSize; *PCache = 0; if (0 == Capacity) Capacity = ((PAGE_SIZE - sizeof *Cache) / sizeof Cache->ItemBuckets[0]) * 3 / 4; CacheSize = (Capacity * 4 / 3) * sizeof Cache->ItemBuckets[0] + sizeof *Cache; CacheSize = FSP_FSCTL_ALIGN_UP(CacheSize, PAGE_SIZE); Cache = FuseAllocNonPaged(CacheSize); /* FAST_MUTEX's must be in non-paged memory */ if (0 == Cache) return STATUS_INSUFFICIENT_RESOURCES; RtlZeroMemory(Cache, CacheSize); Cache->Capacity = Capacity; Cache->CaseInsensitive = CaseInsensitive; ExInitializeFastMutex(&Cache->Mutex); InitializeListHead(&Cache->GenList); InitializeListHead(&Cache->ItemList); InitializeListHead(&Cache->ForgetList); Cache->ItemBucketCount = (CacheSize - sizeof *Cache) / sizeof Cache->ItemBuckets[0]; *PCache = Cache; return STATUS_SUCCESS; } VOID FuseCacheDelete(FUSE_CACHE *Cache) { PAGED_CODE(); for (PLIST_ENTRY Entry = Cache->GenList.Flink; &Cache->GenList != Entry;) { FUSE_CACHE_GEN *Gen = CONTAINING_RECORD(Entry, FUSE_CACHE_GEN, ListEntry); Entry = Entry->Flink; FuseFree(Gen); } FuseCacheDeleteForgotten(&Cache->ItemList); FuseCacheDeleteForgotten(&Cache->ForgetList); FuseFree(Cache); } VOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache, FUSE_INSTANCE *Instance, UINT64 ExpirationTime) { PAGED_CODE(); LIST_ENTRY ForgetList; InitializeListHead(&ForgetList); ExAcquireFastMutex(&Cache->Mutex); while (FuseCacheExpireNextItem(Cache, ExpirationTime)) ; while (FuseCacheForgetNextItem(Cache, ExpirationTime, &ForgetList)) ; ExReleaseFastMutex(&Cache->Mutex); for (PLIST_ENTRY Entry = ForgetList.Flink; &ForgetList != Entry;) { FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry); Entry = Entry->Flink; if (Item->NoForget) { RemoveEntryList(&Item->ListEntry); FuseFree(Item); } } if (!IsListEmpty(&ForgetList)) { BOOLEAN Success = DEBUGTEST(90) && NT_SUCCESS(FuseProtoPostForget(Instance, &ForgetList)); if (!Success) { ASSERT(!IsListEmpty(&ForgetList)); ExAcquireFastMutex(&Cache->Mutex); /* re-add forgotten items in the "forget list" */ RemoveEntryList(&ForgetList); /* see AppendTailList comments */ #if 0 /* append */ AppendTailList(&Cache->ForgetList, &ForgetList); #else /* prepend */ PLIST_ENTRY ListToPrepend = ForgetList.Flink; PLIST_ENTRY ListHead = &Cache->ForgetList; PLIST_ENTRY ListBegin = ListHead->Flink; ListBegin->Blink = ListToPrepend->Blink; ListHead->Flink = ListToPrepend; ListToPrepend->Blink->Flink = ListBegin; ListToPrepend->Blink = ListHead; #endif ExReleaseFastMutex(&Cache->Mutex); } } } NTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen) { PAGED_CODE(); UINT64 InterruptTime = KeQueryInterruptTime() / 10000000 * 10000000; FUSE_CACHE_GEN *Gen = 0, *NewGen = 0; *PGen = 0; ExAcquireFastMutex(&Cache->Mutex); if (!IsListEmpty(&Cache->GenList)) { Gen = CONTAINING_RECORD(Cache->GenList.Blink, FUSE_CACHE_GEN, ListEntry); if (InterruptTime <= Gen->InterruptTime) Gen->RefCount++; else Gen = 0; } ExReleaseFastMutex(&Cache->Mutex); if (0 == Gen) { NewGen = FuseAlloc(sizeof *NewGen); if (0 == NewGen) return STATUS_INSUFFICIENT_RESOURCES; RtlZeroMemory(NewGen, sizeof *NewGen); NewGen->RefCount = 1; NewGen->InterruptTime = InterruptTime; ExAcquireFastMutex(&Cache->Mutex); if (!IsListEmpty(&Cache->GenList)) { Gen = CONTAINING_RECORD(Cache->GenList.Blink, FUSE_CACHE_GEN, ListEntry); if (InterruptTime <= Gen->InterruptTime) Gen->RefCount++; else Gen = 0; } if (0 == Gen) { InsertTailList(&Cache->GenList, &NewGen->ListEntry); Gen = NewGen; NewGen = 0; } ExReleaseFastMutex(&Cache->Mutex); } *PGen = Gen; if (0 != NewGen) FuseFree(NewGen); return STATUS_SUCCESS; } VOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen0) { PAGED_CODE(); FUSE_CACHE_GEN *Gen = Gen0; LONG RefCount; if (0 == Gen) return; ExAcquireFastMutex(&Cache->Mutex); RefCount = --Gen->RefCount; if (0 == RefCount) RemoveEntryList(&Gen->ListEntry); ExReleaseFastMutex(&Cache->Mutex); if (0 == RefCount) FuseFree(Gen); } BOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name, FUSE_PROTO_ENTRY *Entry, PVOID *PItem) { PAGED_CODE(); UINT64 InterruptTime = KeQueryInterruptTime(); FUSE_CACHE_ITEM *Item; ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive); ExAcquireFastMutex(&Cache->Mutex); Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name); if (0 != Item) { if (InterruptTime < Item->ExpirationTime && !InterlockedCompareExchange(&Item->QuickExpiry, 1, 1)) { Item->LastUsedTime = InterruptTime; RtlCopyMemory(Entry, &Item->Entry, sizeof Item->Entry); /* mark as most-recently used */ RemoveEntryList(&Item->ListEntry); InsertTailList(&Cache->ItemList, &Item->ListEntry); } else { FuseCacheExpireItem(Cache, Item); Item = 0; } } ExReleaseFastMutex(&Cache->Mutex); *PItem = Item; return 0 != Item; } VOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name, FUSE_PROTO_ENTRY *Entry, PVOID *PItem) { PAGED_CODE(); UINT64 InterruptTime = KeQueryInterruptTime(); UINT64 EntryTimeout = Entry->entry_valid * 10000000 + Entry->entry_valid_nsec / 100; UINT64 AttrTimeout = Entry->attr_valid * 10000000 + Entry->attr_valid_nsec / 100; UINT64 ExpirationTime = InterruptTime + (EntryTimeout < AttrTimeout ? EntryTimeout : AttrTimeout); FUSE_CACHE_ITEM *Item = 0, *NewItem = 0; ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive); ExAcquireFastMutex(&Cache->Mutex); Item = FuseCacheUpdateHashedItem(Cache, Hash, ParentIno, Name, ExpirationTime, InterruptTime, Entry); ExReleaseFastMutex(&Cache->Mutex); if (0 == Item) { NewItem = FuseAllocMustSucceed(FIELD_OFFSET(FUSE_CACHE_ITEM, NameBuf) + Name->Length); RtlZeroMemory(NewItem, FIELD_OFFSET(FUSE_CACHE_ITEM, NameBuf)); NewItem->NoForget = /* the root is not LOOKUP'ed; free without FORGET */ ParentIno == FUSE_PROTO_ROOT_INO && 1 == Name->Length && '/' == Name->Buffer[0]; NewItem->Hash = Hash; NewItem->ParentIno = ParentIno; NewItem->Name.Length = NewItem->Name.MaximumLength = Name->Length; NewItem->Name.Buffer = NewItem->NameBuf; NewItem->NLookup = 1; NewItem->ExpirationTime = ExpirationTime; NewItem->LastUsedTime = InterruptTime; NewItem->RefCount = 1; RtlCopyMemory(&NewItem->Entry, Entry, sizeof NewItem->Entry); RtlCopyMemory(&NewItem->NameBuf, Name->Buffer, Name->Length); ExAcquireFastMutex(&Cache->Mutex); Item = FuseCacheUpdateHashedItem(Cache, Hash, ParentIno, Name, ExpirationTime, InterruptTime, Entry); if (0 == Item) { if (Cache->ItemCount >= Cache->Capacity) FuseCacheExpireNextItem(Cache, (UINT64)-1LL); FuseCacheAddItem(Cache, NewItem); Item = NewItem; NewItem = 0; } ExReleaseFastMutex(&Cache->Mutex); } if (0 != NewItem) FuseFree(NewItem); *PItem = Item; } VOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name) { PAGED_CODE(); FUSE_CACHE_ITEM *Item; ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive); ExAcquireFastMutex(&Cache->Mutex); Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name); if (0 != Item) FuseCacheExpireItem(Cache, Item); ExReleaseFastMutex(&Cache->Mutex); } VOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item0) { PAGED_CODE(); FUSE_CACHE_ITEM *Item = Item0; InterlockedIncrement(&Item->RefCount); } VOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item0) { PAGED_CODE(); FUSE_CACHE_ITEM *Item = Item0; LONG RefCount; if (0 == Item) return; RefCount = InterlockedDecrement(&Item->RefCount); if (0 == RefCount) { ExAcquireFastMutex(&Cache->Mutex); InsertTailList(&Cache->ForgetList, &Item->ListEntry); ExReleaseFastMutex(&Cache->Mutex); } } VOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item0) { PAGED_CODE(); FUSE_CACHE_ITEM *Item = Item0; InterlockedExchange(&Item->QuickExpiry, 1); } VOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList) { PAGED_CODE(); for (PLIST_ENTRY Entry = ForgetList->Flink; ForgetList != Entry;) { FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry); Entry = Entry->Flink; FuseFree(Item); } } BOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne) { PAGED_CODE(); PLIST_ENTRY Entry = RemoveHeadList(ForgetList); if (ForgetList == Entry) return FALSE; FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry); ASSERT(!Item->NoForget); PForgetOne->nodeid = Item->Entry.nodeid; PForgetOne->nlookup = Item->NLookup; FuseFree(Item); return TRUE; } ================================================ FILE: src/shared/km/context.c ================================================ /** * @file shared/km/context.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include VOID FuseContextCreate(FUSE_CONTEXT **PContext, FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest); VOID FuseContextDelete(FUSE_CONTEXT *Context); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseContextCreate) #pragma alloc_text(PAGE, FuseContextDelete) #endif VOID FuseContextCreate(FUSE_CONTEXT **PContext, FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest) { PAGED_CODE(); FUSE_CONTEXT *Context; UINT32 Kind = 0 == InternalRequest ? FspFsctlTransactReservedKind : InternalRequest->Kind; ASSERT(FspFsctlTransactKindCount > Kind); if (0 == FuseOperations[Kind].Proc) { *PContext = FuseContextStatus(STATUS_INVALID_DEVICE_REQUEST); return; } Context = FuseAlloc(sizeof *Context); if (0 == Context) { *PContext = FuseContextStatus(STATUS_INSUFFICIENT_RESOURCES); return; } RtlZeroMemory(Context, sizeof *Context); Context->Instance = Instance; Context->InternalRequest = InternalRequest; Context->InternalResponse = (PVOID)&Context->InternalResponseBuf; Context->InternalResponse->Size = sizeof(FSP_FSCTL_TRANSACT_RSP); Context->InternalResponse->Kind = Kind; Context->InternalResponse->Hint = 0 != InternalRequest ? InternalRequest->Hint : 0; *PContext = Context; } VOID FuseContextDelete(FUSE_CONTEXT *Context) { PAGED_CODE(); if (FuseOpGuardTrue == Context->OpGuardResult) { UINT32 Kind = 0 == Context->InternalRequest ? FspFsctlTransactReservedKind : Context->InternalRequest->Kind; FuseOperations[Kind].Guard(Context, FALSE); } if (0 != Context->Fini) Context->Fini(Context); if (0 != Context->InternalRequest) FuseFree(Context->InternalRequest); if ((PVOID)&Context->InternalResponseBuf != Context->InternalResponse) FuseFree(Context->InternalResponse); DEBUGFILL(Context, sizeof *Context); FuseFree(Context); } ================================================ FILE: src/shared/km/coro.h ================================================ /** * @file shared/km/coro.h * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef SHARED_KM_CORO_H_INCLUDED #define SHARED_KM_CORO_H_INCLUDED /* * Nested coroutines * * This is a simple implementation of nested coroutines for C using macros. It introduces * the macros coro_block, coro_await, coro_yield and coro_break that are used to create coroutines, * suspend/resume them and exit them. This implementation supports nested coroutines in that * a coroutine may invoke another coroutine and the whole stack of coroutines may be suspended * and later resumed. * * The implementation is able to do this by maintaining a stack of program "points" where * coroutine execution may be suspended and later resumed. The implementation achieves this by * (ab)using a peculiarity of the C switch statement in that it allows case: labels to appear * anywhere within the body of a switch statement including nested compound statements. * * While this implementation is able to maintain the stack of program "points" where execution * may be resumed, it is not able to automatically maintain important state such as activation * records (local variables). It is the responsibility of the programmer using these macros * to maintain this state. Usually this is done by moving all local variables together with the * space for the program "points" stack into a heap allocation that is then passed as an argument * to the coroutines. * * The original coroutine implementation was done some time around 2010 and did not support * nesting. It was used to facilitate the implementation of complex iterators in a C++ library. * It was inspired by Simon Tatham's "Coroutines in C": * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html * * Reference * * The coroutine state is maintained in an integer array (S) whose address is passed to the * "block" statement. The array's number of elements must be 2 plus the number of expected * coroutines (e.g. if you expect to have up to 3 nested coroutines, the array must have at * least 5 elements). The array must be initialized to 0 on initial entry to a coroutine block. * * coro_block(S) * This macro introduces a coroutine statement block { ... } where the "await", "yield", * and "break" statements can be used. There can only be one such block within a function. * coro_await(E) * This macro executes the expression E, which should be an invocation of a coroutine. * The nested coroutine may suspend itself, in which case the "await" statement exits * the current coroutine statement block. The coroutine block can be reentered in which * case execution will continue within the coroutine invoked by E, unless the coroutine * is complete. It is an error to use "await" outside of a coroutine block. * coro_yield * This macro exits the current coroutine statement block. The coroutine block can be * reentered in which case execution will continue after the "yield" statement. It is * an error to use "yield" outside of a coroutine block. * coro_break * This macro exits the current coroutine statement block and marks it as "complete". * If the coroutine block is reentered it exits immediately. It is an error to use "break" * outside of a coroutine block. */ #define coro_block(S) short *coro_S__ = (S); if (!coro_active()) coro_X__:; else \ switch (coro_enter__()) for (; 0,0; coro_leave__(-1)) case 0: #define coro_await__(N, E) do { E; coro_cond_leave__(N); goto coro_X__; case N:; } while (1,1) #define coro_yield__(N) do { coro_leave__(N); goto coro_X__; case N:; } while (0,0) #define coro_break do { coro_leave__(-1); goto coro_X__; } while (0,0) #define coro_active() (-1 != coro_below__) #define coro_below__ (coro_S__[coro_S__[0] + 1]) #define coro_enter__() (coro_S__[++coro_S__[0]]) #define coro_leave__(N) (coro_below__ = 0, coro_S__[coro_S__[0]--] = N) #define coro_cond_leave__(N)if (!coro_active()) { coro_below__ = 0; break; } (coro_S__[coro_S__[0]--] = N) #if defined(__COUNTER__) #define coro_await(...) coro_await__((__COUNTER__ + 1), (__VA_ARGS__)) #define coro_yield coro_yield__((__COUNTER__ + 1)) #else #define coro_await(...) coro_await__(__LINE__, (__VA_ARGS__)) #define coro_yield coro_yield__(__LINE__) #endif #endif ================================================ FILE: src/shared/km/debug.c ================================================ /** * @file shared/km/debug.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #if DBG ULONG DebugRandom(VOID) { static KSPIN_LOCK SpinLock = 0; static ULONG Seed = 1; KIRQL Irql; ULONG Result; KeAcquireSpinLock(&SpinLock, &Irql); /* see ucrt sources */ Seed = Seed * 214013 + 2531011; Result = (Seed >> 16) & 0x7fff; KeReleaseSpinLock(&SpinLock, Irql); return Result; } BOOLEAN DebugMemory(PVOID Memory, SIZE_T Size, BOOLEAN Test) { BOOLEAN Result = TRUE; if (!Test) { for (SIZE_T I = 0, N = Size / sizeof(UINT32); N > I; I++) { ((PUINT8)Memory)[0] = 0x0B; ((PUINT8)Memory)[1] = 0xAD; ((PUINT8)Memory)[2] = 0xF0; ((PUINT8)Memory)[3] = 0x0D; Memory = (PUINT8)Memory + sizeof(UINT32); } } else { for (SIZE_T I = 0, N = Size / sizeof(UINT32); N > I; I++) { if ( ((PUINT8)Memory)[0] == 0x0B && ((PUINT8)Memory)[1] == 0xAD && ((PUINT8)Memory)[2] == 0xF0 && ((PUINT8)Memory)[3] == 0x0D ) { Result = FALSE; break; } Memory = (PUINT8)Memory + sizeof(UINT32); } } return Result; } int _snprintf(char *buf, size_t siz, const char *fmt, ...); static const char *FuseErrnoSignSym(INT32 Errno) { if (0 < Errno) return "+"; else if (0 > Errno) return "-"; else return ""; } static const char *FuseErrnoSym(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno) { if (0 > Errno) Errno = -Errno; switch (InstanceType) { default: case FuseInstanceWindows: switch (Errno) { #undef FUSE_ERRNO #define FUSE_ERRNO 87 #include "errnosym.i" default: return "errno:UNKNOWN"; } case FuseInstanceCygwin: switch (Errno) { #undef FUSE_ERRNO #define FUSE_ERRNO 67 #include "errnosym.i" default: return "errno:UNKNOWN"; } case FuseInstanceLinux: switch (Errno) { #undef FUSE_ERRNO #define FUSE_ERRNO 76 #include "errnosym.i" default: return "errno:UNKNOWN"; } } } static const char *FuseOpcodeSym(UINT32 Opcode) { #define SYM(x) case FUSE_PROTO_OPCODE_ ## x: return #x; switch (Opcode) { case 0: return "EMPTY"; SYM(LOOKUP) SYM(FORGET) SYM(GETATTR) SYM(SETATTR) SYM(READLINK) SYM(SYMLINK) SYM(MKNOD) SYM(MKDIR) SYM(UNLINK) SYM(RMDIR) SYM(RENAME) SYM(LINK) SYM(OPEN) SYM(READ) SYM(WRITE) SYM(STATFS) SYM(RELEASE) SYM(FSYNC) SYM(SETXATTR) SYM(GETXATTR) SYM(LISTXATTR) SYM(REMOVEXATTR) SYM(FLUSH) SYM(INIT) SYM(OPENDIR) SYM(READDIR) SYM(RELEASEDIR) SYM(FSYNCDIR) SYM(GETLK) SYM(SETLK) SYM(SETLKW) SYM(ACCESS) SYM(CREATE) SYM(INTERRUPT) SYM(BMAP) SYM(DESTROY) SYM(IOCTL) SYM(POLL) SYM(NOTIFY_REPLY) SYM(BATCH_FORGET) SYM(FALLOCATE) SYM(READDIRPLUS) SYM(RENAME2) SYM(LSEEK) SYM(COPY_FILE_RANGE) default: return "INVALID"; } #undef SYM } static const char *FuseDebugLogTimeString(UINT64 time, UINT32 timensec, char *Buf) { UINT64 FileTime; TIME_FIELDS TimeFields; if (0 == time && 0 == timensec) Buf[0] = '0', Buf[1] = '\0'; else { FuseUnixTimeToFileTime(time, timensec, &FileTime); RtlTimeToTimeFields((PLARGE_INTEGER)&FileTime, &TimeFields); _snprintf(Buf, 32, "%04hu-%02hu-%02huT%02hu:%02hu:%02hu.%03huZ", TimeFields.Year, TimeFields.Month, TimeFields.Day, TimeFields.Hour, TimeFields.Minute, TimeFields.Second, TimeFields.Milliseconds); } return Buf; } static const char *FuseDebugLogAttrString(FUSE_PROTO_ATTR *Attr, char *Buf) { char atimebuf[32], mtimebuf[32], ctimebuf[32]; _snprintf(Buf, 512, "{ino=%llu, size=%llu, blocks=%llu, atime=%s, mtime=%s, ctime=%s, " "mode=0%06o, nlink=%u, uid=%u, gid=%u, rdev=0x%x, blksize=%u}", Attr->ino, Attr->size, Attr->blocks, FuseDebugLogTimeString(Attr->atime, Attr->atimensec, atimebuf), FuseDebugLogTimeString(Attr->mtime, Attr->mtimensec, mtimebuf), FuseDebugLogTimeString(Attr->ctime, Attr->ctimensec, ctimebuf), Attr->mode, Attr->nlink, Attr->uid, Attr->gid, Attr->rdev, Attr->blksize); return Buf; } static const char *FuseDebugLogEntryString(FUSE_PROTO_ENTRY *Entry, char *Buf) { int Len0, Len1; Len0 = _snprintf(Buf, 256, "{nodeid=%llu, generation=%llu, entry_valid=%llu, entry_valid_nsec=%u, " "attr_valid=%llu, attr_valid_nsec=%u, attr=", Entry->nodeid, Entry->generation, Entry->entry_valid, Entry->entry_valid_nsec, Entry->attr_valid, Entry->attr_valid_nsec); FuseDebugLogAttrString(&Entry->attr, Buf + Len0); Len1 = Len0 + (int)strlen(Buf + Len0); Buf[Len1] = '}'; Buf[Len1 + 1] = '\0'; return Buf; } VOID FuseDebugLogRequest(FUSE_PROTO_REQ *Request) { #define LOG(fmt, ...) \ DbgPrint("[%d] FUSE: %p[%06x]: <<%s[ino=%llu,uid=%u:%u,pid=%u] " fmt "\n",\ KeGetCurrentIrql(), \ (PVOID)(UINT_PTR)Request->unique,\ Request->len, \ FuseOpcodeSym(Request->opcode), \ Request->nodeid, \ Request->uid, \ Request->gid, \ Request->pid, \ __VA_ARGS__) if (0 == Request->len) { LOG("", 0); return; } FUSE_CONTEXT *Context = (PVOID)(UINT_PTR)Request->unique; 0 != Context ? Context->DebugLogOpcode = Request->opcode : 0; char atimebuf[32], mtimebuf[32], ctimebuf[32]; switch (Request->opcode) { case FUSE_PROTO_OPCODE_LOOKUP: LOG("name=\"%s\"", Request->req.lookup.name); break; case FUSE_PROTO_OPCODE_FORGET: LOG("nlookup=%llu", Request->req.forget.nlookup); break; case FUSE_PROTO_OPCODE_GETATTR: LOG("fh=%llu, flags=%u", Request->req.getattr.fh, Request->req.getattr.getattr_flags); break; case FUSE_PROTO_OPCODE_SETATTR: LOG("fh=%llu, valid=%x, size=%llu, atime=%s, mtime=%s, ctime=%s, mode=0%03o, uid=%u, gid=%u", Request->req.setattr.fh, Request->req.setattr.valid, Request->req.setattr.size, FuseDebugLogTimeString(Request->req.setattr.atime, Request->req.setattr.atimensec, atimebuf), FuseDebugLogTimeString(Request->req.setattr.mtime, Request->req.setattr.mtimensec, mtimebuf), FuseDebugLogTimeString(Request->req.setattr.ctime, Request->req.setattr.ctimensec, ctimebuf), Request->req.setattr.mode, Request->req.setattr.uid, Request->req.setattr.gid); break; case FUSE_PROTO_OPCODE_SYMLINK: LOG("name=\"%s\", target=\"%s\"", Request->req.symlink.name, Request->req.symlink.name + strlen(Request->req.symlink.name) + 1); break; case FUSE_PROTO_OPCODE_MKNOD: LOG("name=\"%s\", mode=0%06o, rdev=0x%x, umask=0%03o", Request->req.mknod.name, Request->req.mknod.mode, Request->req.mknod.rdev, Request->req.mknod.umask); break; case FUSE_PROTO_OPCODE_MKDIR: LOG("name=\"%s\", mode=0%06o, umask=0%03o", Request->req.mkdir.name, Request->req.mkdir.mode, Request->req.mkdir.umask); break; case FUSE_PROTO_OPCODE_UNLINK: LOG("name=\"%s\"", Request->req.unlink.name); break; case FUSE_PROTO_OPCODE_RMDIR: LOG("name=\"%s\"", Request->req.rmdir.name); break; case FUSE_PROTO_OPCODE_RENAME: LOG("oldname=\"%s\", newdir=%llu, newname=\"%s\"", Request->req.rename.name, Request->req.rename.newdir, Request->req.rename.name + strlen(Request->req.rename.name) + 1); break; case FUSE_PROTO_OPCODE_LINK: LOG("oldino=%llu, name=\"%s\"", Request->req.link.oldnodeid, Request->req.link.name); break; case FUSE_PROTO_OPCODE_OPEN: case FUSE_PROTO_OPCODE_OPENDIR: LOG("open_flags=0x%x", Request->req.open.flags); break; case FUSE_PROTO_OPCODE_READ: case FUSE_PROTO_OPCODE_READDIR: case FUSE_PROTO_OPCODE_READDIRPLUS: LOG("fh=%llu, offset=%llu, size=%u, open_flags=0x%x", Request->req.read.fh, Request->req.read.offset, Request->req.read.size, Request->req.read.flags); break; case FUSE_PROTO_OPCODE_WRITE: LOG("fh=%llu, offset=%llu, size=%u, open_flags=0x%x", Request->req.write.fh, Request->req.write.offset, Request->req.write.size, Request->req.write.flags); break; case FUSE_PROTO_OPCODE_RELEASE: case FUSE_PROTO_OPCODE_RELEASEDIR: LOG("fh=%llu, flags=0x%x, open_flags=0x%x", Request->req.release.fh, Request->req.release.release_flags, Request->req.release.flags); break; case FUSE_PROTO_OPCODE_FSYNC: case FUSE_PROTO_OPCODE_FSYNCDIR: LOG("fh=%llu, flags=0x%x", Request->req.fsync.fh, Request->req.fsync.fsync_flags); break; case FUSE_PROTO_OPCODE_SETXATTR: LOG("name=\"%s\", size=%u, flags=0x%x", Request->req.setxattr.name, Request->req.setxattr.size, Request->req.setxattr.flags); break; case FUSE_PROTO_OPCODE_GETXATTR: LOG("name=\"%s\", size=%u", Request->req.getxattr.name, Request->req.getxattr.size); break; case FUSE_PROTO_OPCODE_LISTXATTR: LOG("size=%u", Request->req.listxattr.size); break; case FUSE_PROTO_OPCODE_REMOVEXATTR: LOG("name=\"%s\"", Request->req.removexattr.name); break; case FUSE_PROTO_OPCODE_FLUSH: LOG("fh=%llu", Request->req.flush.fh); break; case FUSE_PROTO_OPCODE_INIT: LOG("major=%u, minor=%u, flags=0x%x, max_readahead=%u", Request->req.init.major, Request->req.init.minor, Request->req.init.flags, Request->req.init.max_readahead); break; case FUSE_PROTO_OPCODE_ACCESS: LOG("mask=0%o", Request->req.access.mask); break; case FUSE_PROTO_OPCODE_CREATE: LOG("name=\"%s\", mode=0%06o, umask=0%03o, open_flags=0x%x", Request->req.create.name, Request->req.create.mode, Request->req.create.umask, Request->req.create.flags); break; case FUSE_PROTO_OPCODE_BATCH_FORGET: LOG("count=%u", Request->req.batch_forget.count); break; default: LOG("", 0); break; } #undef LOG } VOID FuseDebugLogResponse(FUSE_PROTO_RSP *Response) { #define LOG(fmt, ...) \ DbgPrint("[%d] FUSE: %p[%06x]: >>%s[err=%s%s] " fmt "\n",\ KeGetCurrentIrql(), \ (PVOID)(UINT_PTR)Response->unique,\ Response->len, \ FuseOpcodeSym(Opcode), \ FuseErrnoSignSym(Response->error),\ FuseErrnoSym(InstanceType, Response->error),\ __VA_ARGS__) FUSE_CONTEXT *Context = (PVOID)(UINT_PTR)Response->unique; FUSE_INSTANCE_TYPE InstanceType = 0 != Context ? Context->Instance->InstanceType : FuseInstanceWindows; UINT32 Opcode = 0 != Context ? Context->DebugLogOpcode : 0; if (0 != Response->error) { LOG("", 0); return; } char entrybuf[256 + 512]; switch (Opcode) { case FUSE_PROTO_OPCODE_LOOKUP: LOG("entry=%s", FuseDebugLogEntryString(&Response->rsp.lookup.entry, entrybuf)); break; case FUSE_PROTO_OPCODE_GETATTR: LOG("attr_valid=%llu, attr_valid_nsec=%u, attr=%s", Response->rsp.getattr.attr_valid, Response->rsp.getattr.attr_valid_nsec, FuseDebugLogAttrString(&Response->rsp.getattr.attr, entrybuf)); break; case FUSE_PROTO_OPCODE_SETATTR: LOG("attr_valid=%llu, attr_valid_nsec=%u, attr=%s", Response->rsp.setattr.attr_valid, Response->rsp.setattr.attr_valid_nsec, FuseDebugLogAttrString(&Response->rsp.setattr.attr, entrybuf)); break; case FUSE_PROTO_OPCODE_SYMLINK: LOG("entry=%s", FuseDebugLogEntryString(&Response->rsp.symlink.entry, entrybuf)); break; case FUSE_PROTO_OPCODE_MKNOD: LOG("entry=%s", FuseDebugLogEntryString(&Response->rsp.mknod.entry, entrybuf)); break; case FUSE_PROTO_OPCODE_MKDIR: LOG("entry=%s", FuseDebugLogEntryString(&Response->rsp.mkdir.entry, entrybuf)); break; case FUSE_PROTO_OPCODE_LINK: LOG("entry=%s", FuseDebugLogEntryString(&Response->rsp.link.entry, entrybuf)); break; case FUSE_PROTO_OPCODE_OPEN: case FUSE_PROTO_OPCODE_OPENDIR: LOG("fh=%llu, open_flags=0x%x", Response->rsp.open.fh, Response->rsp.open.open_flags); break; case FUSE_PROTO_OPCODE_WRITE: LOG("size=%u", Response->rsp.write.size); break; case FUSE_PROTO_OPCODE_STATFS: LOG("st={blocks=%llu, bfree=%llu, bavail=%llu, files=%llu, ffree=%llu, bsize=%u, frsize=%u, namelen=%u}", Response->rsp.statfs.st.blocks, Response->rsp.statfs.st.bfree, Response->rsp.statfs.st.bavail, Response->rsp.statfs.st.files, Response->rsp.statfs.st.ffree, Response->rsp.statfs.st.bsize, Response->rsp.statfs.st.frsize, Response->rsp.statfs.st.namelen); break; case FUSE_PROTO_OPCODE_GETXATTR: LOG("size=%u", Response->rsp.getxattr.size); break; case FUSE_PROTO_OPCODE_LISTXATTR: LOG("size=%u", Response->rsp.listxattr.size); break; case FUSE_PROTO_OPCODE_INIT: LOG("major=%u, minor=%u, flags=0x%x, max_readahead=%u, max_write=%u", Response->rsp.init.major, Response->rsp.init.minor, Response->rsp.init.flags, Response->rsp.init.max_readahead, Response->rsp.init.max_write); break; case FUSE_PROTO_OPCODE_CREATE: LOG("entry=%s, fh=%llu, open_flags=0x%x", FuseDebugLogEntryString(&Response->rsp.create.entry, entrybuf), Response->rsp.create.fh, Response->rsp.create.open_flags); break; default: LOG("", 0); break; } #undef LOG } #endif ================================================ FILE: src/shared/km/errno.i ================================================ #if FUSE_ERRNO == 87 /* Windows */ case 0: return STATUS_SUCCESS; case 1: return STATUS_ACCESS_DENIED; case 2: return STATUS_OBJECT_NAME_NOT_FOUND; case 3: return STATUS_PROCEDURE_NOT_FOUND; case 4: return STATUS_CANCELLED; case 5: return STATUS_IO_DEVICE_ERROR; case 6: return STATUS_FILE_INVALID; case 7: return STATUS_INSUFFICIENT_RESOURCES; case 8: return STATUS_INVALID_IMAGE_FORMAT; case 9: return STATUS_INVALID_HANDLE; case 12: return STATUS_INSUFFICIENT_RESOURCES; case 13: return STATUS_ACCESS_DENIED; case 14: return STATUS_ACCESS_VIOLATION; case 16: return STATUS_DEVICE_BUSY; case 17: return STATUS_OBJECT_NAME_COLLISION; case 18: return STATUS_NOT_SAME_DEVICE; case 19: return STATUS_NO_SUCH_DEVICE; case 20: return STATUS_NOT_A_DIRECTORY; case 21: return STATUS_FILE_IS_A_DIRECTORY; case 22: return STATUS_INVALID_PARAMETER; case 23: return STATUS_TOO_MANY_OPENED_FILES; case 24: return STATUS_TOO_MANY_OPENED_FILES; case 27: return STATUS_DISK_FULL; case 28: return STATUS_DISK_FULL; case 29: return STATUS_INVALID_PARAMETER; case 30: return STATUS_MEDIA_WRITE_PROTECTED; case 31: return STATUS_TOO_MANY_LINKS; case 32: return STATUS_PIPE_BROKEN; case 33: return STATUS_INVALID_PARAMETER; case 34: return STATUS_INVALID_PARAMETER; case 36: return STATUS_POSSIBLE_DEADLOCK; case 38: return STATUS_NAME_TOO_LONG; case 39: return STATUS_LOCK_NOT_GRANTED; case 40: return STATUS_INVALID_DEVICE_REQUEST; case 41: return STATUS_DIRECTORY_NOT_EMPTY; case 42: return STATUS_INVALID_PARAMETER; case 100: return STATUS_ADDRESS_ALREADY_ASSOCIATED; case 103: return STATUS_CONNECTION_ACTIVE; case 105: return STATUS_CANCELLED; case 106: return STATUS_CONNECTION_ABORTED; case 107: return STATUS_CONNECTION_REFUSED; case 108: return STATUS_CONNECTION_RESET; case 110: return STATUS_HOST_UNREACHABLE; case 113: return STATUS_CONNECTION_ACTIVE; case 114: return STATUS_REPARSE_POINT_NOT_RESOLVED; case 116: return STATUS_HOST_DOWN; case 117: return STATUS_CONNECTION_RESET; case 118: return STATUS_NETWORK_UNREACHABLE; case 119: return STATUS_INSUFFICIENT_RESOURCES; case 120: return STATUS_END_OF_FILE; case 121: return STATUS_CONNECTION_INVALID; case 126: return STATUS_CONNECTION_INVALID; case 128: return STATUS_INVALID_HANDLE; case 138: return STATUS_TRANSACTION_TIMED_OUT; #elif FUSE_ERRNO == 67 /* Cygwin */ case 0: return STATUS_SUCCESS; case 1: return STATUS_ACCESS_DENIED; case 2: return STATUS_OBJECT_NAME_NOT_FOUND; case 3: return STATUS_PROCEDURE_NOT_FOUND; case 4: return STATUS_CANCELLED; case 5: return STATUS_IO_DEVICE_ERROR; case 6: return STATUS_FILE_INVALID; case 7: return STATUS_INSUFFICIENT_RESOURCES; case 8: return STATUS_INVALID_IMAGE_FORMAT; case 9: return STATUS_INVALID_HANDLE; case 12: return STATUS_INSUFFICIENT_RESOURCES; case 13: return STATUS_ACCESS_DENIED; case 14: return STATUS_ACCESS_VIOLATION; case 16: return STATUS_DEVICE_BUSY; case 17: return STATUS_OBJECT_NAME_COLLISION; case 18: return STATUS_NOT_SAME_DEVICE; case 19: return STATUS_NO_SUCH_DEVICE; case 20: return STATUS_NOT_A_DIRECTORY; case 21: return STATUS_FILE_IS_A_DIRECTORY; case 22: return STATUS_INVALID_PARAMETER; case 23: return STATUS_TOO_MANY_OPENED_FILES; case 24: return STATUS_TOO_MANY_OPENED_FILES; case 27: return STATUS_DISK_FULL; case 28: return STATUS_DISK_FULL; case 29: return STATUS_INVALID_PARAMETER; case 30: return STATUS_MEDIA_WRITE_PROTECTED; case 31: return STATUS_TOO_MANY_LINKS; case 32: return STATUS_PIPE_BROKEN; case 33: return STATUS_INVALID_PARAMETER; case 34: return STATUS_INVALID_PARAMETER; case 45: return STATUS_POSSIBLE_DEADLOCK; case 91: return STATUS_NAME_TOO_LONG; case 46: return STATUS_LOCK_NOT_GRANTED; case 88: return STATUS_INVALID_DEVICE_REQUEST; case 90: return STATUS_DIRECTORY_NOT_EMPTY; case 138: return STATUS_INVALID_PARAMETER; case 112: return STATUS_ADDRESS_ALREADY_ASSOCIATED; case 120: return STATUS_CONNECTION_ACTIVE; case 140: return STATUS_CANCELLED; case 113: return STATUS_CONNECTION_ABORTED; case 111: return STATUS_CONNECTION_REFUSED; case 104: return STATUS_CONNECTION_RESET; case 118: return STATUS_HOST_UNREACHABLE; case 127: return STATUS_CONNECTION_ACTIVE; case 92: return STATUS_REPARSE_POINT_NOT_RESOLVED; case 115: return STATUS_HOST_DOWN; case 126: return STATUS_CONNECTION_RESET; case 114: return STATUS_NETWORK_UNREACHABLE; case 105: return STATUS_INSUFFICIENT_RESOURCES; case 61: return STATUS_END_OF_FILE; case 67: return STATUS_CONNECTION_INVALID; case 128: return STATUS_CONNECTION_INVALID; case 108: return STATUS_INVALID_HANDLE; case 116: return STATUS_TRANSACTION_TIMED_OUT; #elif FUSE_ERRNO == 76 /* Linux */ case 0: return STATUS_SUCCESS; case 1: return STATUS_ACCESS_DENIED; case 2: return STATUS_OBJECT_NAME_NOT_FOUND; case 3: return STATUS_PROCEDURE_NOT_FOUND; case 4: return STATUS_CANCELLED; case 5: return STATUS_IO_DEVICE_ERROR; case 6: return STATUS_FILE_INVALID; case 7: return STATUS_INSUFFICIENT_RESOURCES; case 8: return STATUS_INVALID_IMAGE_FORMAT; case 9: return STATUS_INVALID_HANDLE; case 12: return STATUS_INSUFFICIENT_RESOURCES; case 13: return STATUS_ACCESS_DENIED; case 14: return STATUS_ACCESS_VIOLATION; case 16: return STATUS_DEVICE_BUSY; case 17: return STATUS_OBJECT_NAME_COLLISION; case 18: return STATUS_NOT_SAME_DEVICE; case 19: return STATUS_NO_SUCH_DEVICE; case 20: return STATUS_NOT_A_DIRECTORY; case 21: return STATUS_FILE_IS_A_DIRECTORY; case 22: return STATUS_INVALID_PARAMETER; case 23: return STATUS_TOO_MANY_OPENED_FILES; case 24: return STATUS_TOO_MANY_OPENED_FILES; case 27: return STATUS_DISK_FULL; case 28: return STATUS_DISK_FULL; case 29: return STATUS_INVALID_PARAMETER; case 30: return STATUS_MEDIA_WRITE_PROTECTED; case 31: return STATUS_TOO_MANY_LINKS; case 32: return STATUS_PIPE_BROKEN; case 33: return STATUS_INVALID_PARAMETER; case 34: return STATUS_INVALID_PARAMETER; case 35: return STATUS_POSSIBLE_DEADLOCK; case 36: return STATUS_NAME_TOO_LONG; case 37: return STATUS_LOCK_NOT_GRANTED; case 38: return STATUS_INVALID_DEVICE_REQUEST; case 39: return STATUS_DIRECTORY_NOT_EMPTY; case 84: return STATUS_INVALID_PARAMETER; case 98: return STATUS_ADDRESS_ALREADY_ASSOCIATED; case 114: return STATUS_CONNECTION_ACTIVE; case 125: return STATUS_CANCELLED; case 103: return STATUS_CONNECTION_ABORTED; case 111: return STATUS_CONNECTION_REFUSED; case 104: return STATUS_CONNECTION_RESET; case 113: return STATUS_HOST_UNREACHABLE; case 106: return STATUS_CONNECTION_ACTIVE; case 40: return STATUS_REPARSE_POINT_NOT_RESOLVED; case 100: return STATUS_HOST_DOWN; case 102: return STATUS_CONNECTION_RESET; case 101: return STATUS_NETWORK_UNREACHABLE; case 105: return STATUS_INSUFFICIENT_RESOURCES; case 61: return STATUS_END_OF_FILE; case 67: return STATUS_CONNECTION_INVALID; case 107: return STATUS_CONNECTION_INVALID; case 88: return STATUS_INVALID_HANDLE; case 110: return STATUS_TRANSACTION_TIMED_OUT; #endif ================================================ FILE: src/shared/km/errnosym.i ================================================ #if FUSE_ERRNO == 87 /* Windows */ case 0: return "0"; case 1: return "EPERM"; case 2: return "ENOENT"; case 3: return "ESRCH"; case 4: return "EINTR"; case 5: return "EIO"; case 6: return "ENXIO"; case 7: return "E2BIG"; case 8: return "ENOEXEC"; case 9: return "EBADF"; case 12: return "ENOMEM"; case 13: return "EACCES"; case 14: return "EFAULT"; case 16: return "EBUSY"; case 17: return "EEXIST"; case 18: return "EXDEV"; case 19: return "ENODEV"; case 20: return "ENOTDIR"; case 21: return "EISDIR"; case 22: return "EINVAL"; case 23: return "ENFILE"; case 24: return "EMFILE"; case 27: return "EFBIG"; case 28: return "ENOSPC"; case 29: return "ESPIPE"; case 30: return "EROFS"; case 31: return "EMLINK"; case 32: return "EPIPE"; case 33: return "EDOM"; case 34: return "ERANGE"; case 36: return "EDEADLK"; case 38: return "ENAMETOOLONG"; case 39: return "ENOLCK"; case 40: return "ENOSYS"; case 41: return "ENOTEMPTY"; case 42: return "EILSEQ"; case 100: return "EADDRINUSE"; case 103: return "EALREADY"; case 105: return "ECANCELED"; case 106: return "ECONNABORTED"; case 107: return "ECONNREFUSED"; case 108: return "ECONNRESET"; case 110: return "EHOSTUNREACH"; case 113: return "EISCONN"; case 114: return "ELOOP"; case 116: return "ENETDOWN"; case 117: return "ENETRESET"; case 118: return "ENETUNREACH"; case 119: return "ENOBUFS"; case 120: return "ENODATA"; case 121: return "ENOLINK"; case 126: return "ENOTCONN"; case 128: return "ENOTSOCK"; case 138: return "ETIMEDOUT"; #elif FUSE_ERRNO == 67 /* Cygwin */ case 0: return "0"; case 1: return "EPERM"; case 2: return "ENOENT"; case 3: return "ESRCH"; case 4: return "EINTR"; case 5: return "EIO"; case 6: return "ENXIO"; case 7: return "E2BIG"; case 8: return "ENOEXEC"; case 9: return "EBADF"; case 12: return "ENOMEM"; case 13: return "EACCES"; case 14: return "EFAULT"; case 16: return "EBUSY"; case 17: return "EEXIST"; case 18: return "EXDEV"; case 19: return "ENODEV"; case 20: return "ENOTDIR"; case 21: return "EISDIR"; case 22: return "EINVAL"; case 23: return "ENFILE"; case 24: return "EMFILE"; case 27: return "EFBIG"; case 28: return "ENOSPC"; case 29: return "ESPIPE"; case 30: return "EROFS"; case 31: return "EMLINK"; case 32: return "EPIPE"; case 33: return "EDOM"; case 34: return "ERANGE"; case 45: return "EDEADLK"; case 91: return "ENAMETOOLONG"; case 46: return "ENOLCK"; case 88: return "ENOSYS"; case 90: return "ENOTEMPTY"; case 138: return "EILSEQ"; case 112: return "EADDRINUSE"; case 120: return "EALREADY"; case 140: return "ECANCELED"; case 113: return "ECONNABORTED"; case 111: return "ECONNREFUSED"; case 104: return "ECONNRESET"; case 118: return "EHOSTUNREACH"; case 127: return "EISCONN"; case 92: return "ELOOP"; case 115: return "ENETDOWN"; case 126: return "ENETRESET"; case 114: return "ENETUNREACH"; case 105: return "ENOBUFS"; case 61: return "ENODATA"; case 67: return "ENOLINK"; case 128: return "ENOTCONN"; case 108: return "ENOTSOCK"; case 116: return "ETIMEDOUT"; #elif FUSE_ERRNO == 76 /* Linux */ case 0: return "0"; case 1: return "EPERM"; case 2: return "ENOENT"; case 3: return "ESRCH"; case 4: return "EINTR"; case 5: return "EIO"; case 6: return "ENXIO"; case 7: return "E2BIG"; case 8: return "ENOEXEC"; case 9: return "EBADF"; case 12: return "ENOMEM"; case 13: return "EACCES"; case 14: return "EFAULT"; case 16: return "EBUSY"; case 17: return "EEXIST"; case 18: return "EXDEV"; case 19: return "ENODEV"; case 20: return "ENOTDIR"; case 21: return "EISDIR"; case 22: return "EINVAL"; case 23: return "ENFILE"; case 24: return "EMFILE"; case 27: return "EFBIG"; case 28: return "ENOSPC"; case 29: return "ESPIPE"; case 30: return "EROFS"; case 31: return "EMLINK"; case 32: return "EPIPE"; case 33: return "EDOM"; case 34: return "ERANGE"; case 35: return "EDEADLK"; case 36: return "ENAMETOOLONG"; case 37: return "ENOLCK"; case 38: return "ENOSYS"; case 39: return "ENOTEMPTY"; case 84: return "EILSEQ"; case 98: return "EADDRINUSE"; case 114: return "EALREADY"; case 125: return "ECANCELED"; case 103: return "ECONNABORTED"; case 111: return "ECONNREFUSED"; case 104: return "ECONNRESET"; case 113: return "EHOSTUNREACH"; case 106: return "EISCONN"; case 40: return "ELOOP"; case 100: return "ENETDOWN"; case 102: return "ENETRESET"; case 101: return "ENETUNREACH"; case 105: return "ENOBUFS"; case 61: return "ENODATA"; case 67: return "ENOLINK"; case 107: return "ENOTCONN"; case 88: return "ENOTSOCK"; case 110: return "ETIMEDOUT"; #endif ================================================ FILE: src/shared/km/file.c ================================================ /** * @file shared/km/file.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include VOID FuseFileInstanceInit(FUSE_INSTANCE *Instance) { KeInitializeSpinLock(&Instance->FileListLock); InitializeListHead(&Instance->FileList); } VOID FuseFileInstanceFini(FUSE_INSTANCE *Instance) { FUSE_FILE *File; for (PLIST_ENTRY Entry = Instance->FileList.Flink; &Instance->FileList != Entry;) { File = CONTAINING_RECORD(Entry, FUSE_FILE, ListEntry); Entry = Entry->Flink; FuseCacheDereferenceItem(Instance->Cache, File->CacheItem); FuseFree(File); } } NTSTATUS FuseFileCreate(FUSE_INSTANCE *Instance, FUSE_FILE **PFile) { KIRQL Irql; FUSE_FILE *File; *PFile = 0; File = FuseAllocNonPaged(sizeof *File); /* spinlocks must operate on non-paged memory */ if (0 == File) return STATUS_INSUFFICIENT_RESOURCES; RtlZeroMemory(File, sizeof *File); KeAcquireSpinLock(&Instance->FileListLock, &Irql); InsertTailList(&Instance->FileList, &File->ListEntry); KeReleaseSpinLock(&Instance->FileListLock, Irql); *PFile = File; return STATUS_SUCCESS; } VOID FuseFileDelete(FUSE_INSTANCE *Instance, FUSE_FILE *File) { KIRQL Irql; KeAcquireSpinLock(&Instance->FileListLock, &Irql); RemoveEntryList(&File->ListEntry); KeReleaseSpinLock(&Instance->FileListLock, Irql); FuseCacheDereferenceItem(Instance->Cache, File->CacheItem); DEBUGFILL(File, sizeof *File); FuseFree(File); } ================================================ FILE: src/shared/km/fuseop.c ================================================ /** * @file shared/km/fuseop.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include static BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context); static BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context); static BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context); static BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context); static VOID FuseLookup(FUSE_CONTEXT *Context); static NTSTATUS FuseAccessCheck( UINT32 FileUid, UINT32 FileGid, UINT32 FileMode, UINT32 OrigUid, UINT32 OrigGid, UINT32 DesiredAccess, PUINT32 PGrantedAccess); static VOID FusePrepareLookupPath(FUSE_CONTEXT *Context); static VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context); static VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context); static VOID FuseLookupPath(FUSE_CONTEXT *Context); static VOID FuseCreateCheck(FUSE_CONTEXT *Context); static VOID FuseOpenCheck(FUSE_CONTEXT *Context); static VOID FuseOverwriteCheck(FUSE_CONTEXT *Context); static VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context); static VOID FuseRenameCheck(FUSE_CONTEXT *Context); static VOID FuseCreate(FUSE_CONTEXT *Context); static VOID FuseOpen(FUSE_CONTEXT *Context); static VOID FuseOpCreate_FileCreate(FUSE_CONTEXT *Context); static VOID FuseOpCreate_FileOpen(FUSE_CONTEXT *Context); static VOID FuseOpCreate_FileOpenIf(FUSE_CONTEXT *Context); static VOID FuseOpCreate_FileOverwrite(FUSE_CONTEXT *Context); static VOID FuseOpCreate_FileOverwriteIf(FUSE_CONTEXT *Context); static VOID FuseOpCreate_FileOpenTargetDirectory(FUSE_CONTEXT *Context); static BOOLEAN FuseOpCreate(FUSE_CONTEXT *Context); static INT FuseOgCreate(FUSE_CONTEXT *Context, BOOLEAN Acquire); static BOOLEAN FuseOpOverwrite(FUSE_CONTEXT *Context); static BOOLEAN FuseOpCleanup(FUSE_CONTEXT *Context); static INT FuseOgCleanup(FUSE_CONTEXT *Context, BOOLEAN Acquire); static BOOLEAN FuseOpClose(FUSE_CONTEXT *Context); static VOID FuseOpClose_ContextFini(FUSE_CONTEXT *Context); static BOOLEAN FuseOpRead(FUSE_CONTEXT *Context); static BOOLEAN FuseOpWrite(FUSE_CONTEXT *Context); static BOOLEAN FuseOpQueryInformation(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetInformation_SetBasicInfo(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetInformation_SetAllocationSize(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetInformation_SetFileSize(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetInformation_SetDelete(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetInformation_Rename(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetInformation(FUSE_CONTEXT *Context); static INT FuseOgSetInformation(FUSE_CONTEXT *Context, BOOLEAN Acquire); static BOOLEAN FuseOpQueryEa(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetEa(FUSE_CONTEXT *Context); static BOOLEAN FuseOpFlushBuffers(FUSE_CONTEXT *Context); static BOOLEAN FuseOpQueryVolumeInformation(FUSE_CONTEXT *Context); static BOOLEAN FuseAddDirInfo(FUSE_CONTEXT *Context, PSTRING Name, UINT64 NextOffset, FUSE_PROTO_ATTR *Attr, PVOID Buffer, ULONG Length, PULONG PBytesTransferred); static VOID FuseOpQueryDirectory_GetDirInfoByName(FUSE_CONTEXT *Context); static VOID FuseOpQueryDirectory_ReadDirectory(FUSE_CONTEXT *Context); static BOOLEAN FuseOpQueryDirectory(FUSE_CONTEXT *Context); static VOID FuseOpQueryDirectory_ContextFini(FUSE_CONTEXT *Context); static INT FuseOgQueryDirectory(FUSE_CONTEXT *Context, BOOLEAN Acquire); static BOOLEAN FuseOpFileSystemControl(FUSE_CONTEXT *Context); static BOOLEAN FuseOpDeviceControl(FUSE_CONTEXT *Context); static BOOLEAN FuseOpQuerySecurity(FUSE_CONTEXT *Context); static BOOLEAN FuseOpSetSecurity(FUSE_CONTEXT *Context); static VOID FuseSecurity_ContextFini(FUSE_CONTEXT *Context); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseOpReserved_Init) #pragma alloc_text(PAGE, FuseOpReserved_Destroy) #pragma alloc_text(PAGE, FuseOpReserved_Forget) #pragma alloc_text(PAGE, FuseOpReserved) #pragma alloc_text(PAGE, FuseLookup) #pragma alloc_text(PAGE, FuseAccessCheck) #pragma alloc_text(PAGE, FusePrepareLookupPath) #pragma alloc_text(PAGE, FusePrepareLookupPath2) #pragma alloc_text(PAGE, FusePrepareLookupPath_ContextFini) #pragma alloc_text(PAGE, FuseLookupPath) #pragma alloc_text(PAGE, FuseCreateCheck) #pragma alloc_text(PAGE, FuseOpenCheck) #pragma alloc_text(PAGE, FuseOverwriteCheck) #pragma alloc_text(PAGE, FuseOpenTargetDirectoryCheck) #pragma alloc_text(PAGE, FuseRenameCheck) #pragma alloc_text(PAGE, FuseCreate) #pragma alloc_text(PAGE, FuseOpen) #pragma alloc_text(PAGE, FuseOpCreate_FileCreate) #pragma alloc_text(PAGE, FuseOpCreate_FileOpen) #pragma alloc_text(PAGE, FuseOpCreate_FileOpenIf) #pragma alloc_text(PAGE, FuseOpCreate_FileOverwrite) #pragma alloc_text(PAGE, FuseOpCreate_FileOverwriteIf) #pragma alloc_text(PAGE, FuseOpCreate_FileOpenTargetDirectory) #pragma alloc_text(PAGE, FuseOpCreate) #pragma alloc_text(PAGE, FuseOgCreate) #pragma alloc_text(PAGE, FuseOpOverwrite) #pragma alloc_text(PAGE, FuseOpCleanup) #pragma alloc_text(PAGE, FuseOgCleanup) #pragma alloc_text(PAGE, FuseOpClose) #pragma alloc_text(PAGE, FuseOpClose_ContextFini) #pragma alloc_text(PAGE, FuseOpRead) #pragma alloc_text(PAGE, FuseOpWrite) #pragma alloc_text(PAGE, FuseOpQueryInformation) #pragma alloc_text(PAGE, FuseOpSetInformation_SetBasicInfo) #pragma alloc_text(PAGE, FuseOpSetInformation_SetAllocationSize) #pragma alloc_text(PAGE, FuseOpSetInformation_SetFileSize) #pragma alloc_text(PAGE, FuseOpSetInformation_SetDelete) #pragma alloc_text(PAGE, FuseOpSetInformation_Rename) #pragma alloc_text(PAGE, FuseOpSetInformation) #pragma alloc_text(PAGE, FuseOgSetInformation) #pragma alloc_text(PAGE, FuseOpQueryEa) #pragma alloc_text(PAGE, FuseOpSetEa) #pragma alloc_text(PAGE, FuseOpFlushBuffers) #pragma alloc_text(PAGE, FuseOpQueryVolumeInformation) #pragma alloc_text(PAGE, FuseAddDirInfo) #pragma alloc_text(PAGE, FuseOpQueryDirectory_GetDirInfoByName) #pragma alloc_text(PAGE, FuseOpQueryDirectory_ReadDirectory) #pragma alloc_text(PAGE, FuseOpQueryDirectory) #pragma alloc_text(PAGE, FuseOpQueryDirectory_ContextFini) #pragma alloc_text(PAGE, FuseOgQueryDirectory) #pragma alloc_text(PAGE, FuseOpFileSystemControl) #pragma alloc_text(PAGE, FuseOpDeviceControl) #pragma alloc_text(PAGE, FuseOpQuerySecurity) #pragma alloc_text(PAGE, FuseOpSetSecurity) #pragma alloc_text(PAGE, FuseSecurity_ContextFini) #endif static BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseProtoSendInit(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FUSE_INSTANCE *Instance = Context->Instance; if (FUSE_PROTO_VERSION != Context->FuseResponse->rsp.init.major) { Instance->VersionMajor = (UINT32)-1; KeSetEvent(&Instance->InitEvent, 1, FALSE); Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_CONNECTION_REFUSED; coro_break; } Instance->VersionMajor = Context->FuseResponse->rsp.init.major; Instance->VersionMinor = Context->FuseResponse->rsp.init.minor; // !!!: REVISIT KeSetEvent(&Instance->InitEvent, 1, FALSE); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseProtoSendDestroy(Context)); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context) { PAGED_CODE(); FUSE_INSTANCE *Instance = Context->Instance; ASSERT(!IsListEmpty(&Context->Forget.ForgetList)); if (16 > Instance->VersionMinor || &Context->Forget.ForgetList == Context->Forget.ForgetList.Flink->Flink || DEBUGTEST(10)) FuseProtoFillForget(Context); else FuseProtoFillBatchForget(Context); return FALSE; } static BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context) { PAGED_CODE(); switch (Context->InternalResponse->Hint) { case FUSE_PROTO_OPCODE_INIT: return FuseOpReserved_Init(Context); case FUSE_PROTO_OPCODE_DESTROY: return FuseOpReserved_Destroy(Context); case FUSE_PROTO_OPCODE_FORGET: case FUSE_PROTO_OPCODE_BATCH_FORGET: return FuseOpReserved_Forget(Context); default: return FALSE; } } static VOID FuseLookup(FUSE_CONTEXT *Context) { PAGED_CODE(); FUSE_PROTO_ENTRY EntryBuf, *Entry = &EntryBuf; PVOID CacheItem; coro_block (Context->CoroState) { if (!FuseCacheGetEntry(Context->Instance->Cache, Context->Lookup.Ino, &Context->Lookup.Name, Entry, &CacheItem)) { if (FUSE_PROTO_ROOT_INO == Context->Lookup.Ino && 1 == Context->Lookup.Name.Length && '/' == Context->Lookup.Name.Buffer[0]) { coro_await (FuseProtoSendGetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; RtlZeroMemory(Entry, sizeof *Entry); Entry->nodeid = FUSE_PROTO_ROOT_INO; Entry->entry_valid = Entry->attr_valid = Context->FuseResponse->rsp.getattr.attr_valid; Entry->entry_valid_nsec = Entry->attr_valid_nsec = Context->FuseResponse->rsp.getattr.attr_valid_nsec; Entry->attr = Context->FuseResponse->rsp.getattr.attr; } else { coro_await (FuseProtoSendLookup(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Entry = &Context->FuseResponse->rsp.lookup.entry; } FuseCacheSetEntry( Context->Instance->Cache, Context->Lookup.Ino, &Context->Lookup.Name, Entry, &CacheItem); } Context->Lookup.CacheItem = CacheItem; Context->Lookup.Ino = Entry->nodeid; Context->Lookup.Attr = Entry->attr; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } /* code borrowed from winfsp/src/ku/posix.c - see there for comments/explanations */ #define FusePosixDefaultPerm \ (SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_READ_EA) #define FusePosixOwnerDefaultPerm \ (FusePosixDefaultPerm | DELETE | WRITE_DAC | WRITE_OWNER | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA) static inline ACCESS_MASK FusePosixMapPermissionToAccessMask(UINT32 Mode, UINT32 Perm) { ACCESS_MASK DeleteChild = 0040000 == (Mode & 0041000) ? FILE_DELETE_CHILD : 0; return ((Perm & 4) ? FILE_READ_DATA : 0) | ((Perm & 2) ? FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | FILE_APPEND_DATA | DeleteChild : 0) | ((Perm & 1) ? FILE_EXECUTE : 0); } static NTSTATUS FuseAccessCheck( UINT32 FileUid, UINT32 FileGid, UINT32 FileMode, UINT32 OrigUid, UINT32 OrigGid, UINT32 DesiredAccess, PUINT32 PGrantedAccess) { PAGED_CODE(); UINT32 FileAccess, RequiredAccess; if (OrigUid == FileUid) FileAccess = FusePosixOwnerDefaultPerm | FusePosixMapPermissionToAccessMask(FileMode & ~001000, (FileMode & 0700) >> 6); else if (OrigGid == FileGid) FileAccess = FusePosixDefaultPerm | FusePosixMapPermissionToAccessMask(FileMode, (FileMode & 0070) >> 3); else FileAccess = FusePosixDefaultPerm | FusePosixMapPermissionToAccessMask(FileMode, (FileMode & 0007)); RequiredAccess = DesiredAccess & (STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL); if (RequiredAccess == (FileAccess & RequiredAccess)) { if (0 != PGrantedAccess) *PGrantedAccess = FlagOn(DesiredAccess, MAXIMUM_ALLOWED) ? FileAccess : RequiredAccess; return STATUS_SUCCESS; } else { if (0 != PGrantedAccess) *PGrantedAccess = 0; return STATUS_ACCESS_DENIED; } } static VOID FusePrepareLookupPath(FUSE_CONTEXT *Context) { PAGED_CODE(); UINT32 Uid = 0, Gid = 0, Pid = 0; PVOID CacheGen = 0; PSTR PosixPath = 0; PWSTR FileName = 0; UINT64 AccessToken = 0; PACCESS_TOKEN AccessTokenObject = 0; UINT32 IsUserMode = 1; UINT32 HasTraversePrivilege = 0; switch (Context->InternalRequest->Kind) { case FspFsctlTransactCreateKind: FileName = (PWSTR)Context->InternalRequest->Buffer; AccessToken = Context->InternalRequest->Req.Create.AccessToken; IsUserMode = Context->InternalRequest->Req.Create.UserMode; HasTraversePrivilege = Context->InternalRequest->Req.Create.HasTraversePrivilege; break; case FspFsctlTransactCleanupKind: ASSERT(Context->InternalRequest->Req.Cleanup.Delete); FileName = (PWSTR)Context->InternalRequest->Buffer; IsUserMode = 0; HasTraversePrivilege = 1; break; case FspFsctlTransactSetInformationKind: ASSERT(FileRenameInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass); FileName = (PWSTR)(Context->InternalRequest->Buffer + Context->InternalRequest->Req.SetInformation.Info.Rename.NewFileName.Offset); AccessToken = Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken; IsUserMode = 1; HasTraversePrivilege = 1; break; default: ASSERT(FALSE); Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER; goto exit; } if (0 != FileName) { Context->InternalResponse->IoStatus.Status = FuseCacheReferenceGen( Context->Instance->Cache, &CacheGen); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto exit; Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx( FileName, &PosixPath, TRUE); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto exit; } if (0 != AccessToken) { Context->InternalResponse->IoStatus.Status = ObReferenceObjectByHandle( FSP_FSCTL_TRANSACT_REQ_TOKEN_HANDLE(AccessToken), TOKEN_QUERY, *SeTokenObjectType, UserMode, &AccessTokenObject, 0/*HandleInformation*/); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto exit; Context->InternalResponse->IoStatus.Status = FuseGetTokenUid( AccessTokenObject, TokenUser, &Uid); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto exit; Context->InternalResponse->IoStatus.Status = FuseGetTokenUid( AccessTokenObject, TokenPrimaryGroup, &Gid); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto exit; ObDereferenceObject(AccessTokenObject); Pid = FSP_FSCTL_TRANSACT_REQ_TOKEN_PID(AccessToken); } Context->OrigUid = Uid; Context->OrigGid = Gid; Context->OrigPid = Pid; ASSERT(0 == Context->LookupPath.OrigPath.Buffer); RtlInitString(&Context->LookupPath.OrigPath, PosixPath); Context->LookupPath.CacheGen = CacheGen; Context->LookupPath.UserMode = IsUserMode; Context->LookupPath.HasTraversePrivilege = HasTraversePrivilege; Context->Fini = FusePrepareLookupPath_ContextFini; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; exit: if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) { FspPosixDeletePath(PosixPath); /* handles NULL paths */ FuseCacheDereferenceGen(Context->Instance->Cache, CacheGen); /* handles NULL gens */ } } static VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context) { PAGED_CODE(); PSTR PosixPath = 0; PWSTR FileName = 0; switch (Context->InternalRequest->Kind) { case FspFsctlTransactSetInformationKind: ASSERT(FileRenameInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass); FileName = (PWSTR)Context->InternalRequest->Buffer; break; default: ASSERT(FALSE); Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER; goto exit; } if (0 != FileName) { Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx( FileName, &PosixPath, TRUE); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto exit; } ASSERT(0 == Context->LookupPath.OrigPath.Buffer); ASSERT(0 != Context->LookupPath.OrigPath2.Buffer); RtlInitString(&Context->LookupPath.OrigPath, PosixPath); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; exit: if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) { FspPosixDeletePath(PosixPath); /* handles NULL paths */ } } static VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context) { PAGED_CODE(); if (FspFsctlTransactCreateKind == Context->InternalRequest->Kind && 0 != Context->File) FuseFileDelete(Context->Instance, Context->File); FspPosixDeletePath(Context->LookupPath.OrigPath2.Buffer); /* handles NULL paths */ FspPosixDeletePath(Context->LookupPath.OrigPath.Buffer); /* handles NULL paths */ FuseCacheDereferenceGen(Context->Instance->Cache, Context->LookupPath.CacheGen); /* handles NULL gens */ } static VOID FuseLookupPath(FUSE_CONTEXT *Context) { #define RootName (1 == Context->LookupPath.Name.Length && '/' == Context->LookupPath.Name.Buffer[0]) #define LastName (0 == Context->LookupPath.Remain.Length) #define UserMode (Context->LookupPath.UserMode) #define TravPriv (Context->LookupPath.HasTraversePrivilege) PAGED_CODE(); coro_block (Context->CoroState) { Context->LookupPath.Ino = FUSE_PROTO_ROOT_INO; DEBUGFILL(&Context->Lookup.Attr, sizeof Context->Lookup.Attr); while (1) /* for (;;) produces "warning C4702: unreachable code" */ { FusePosixPathPrefix(&Context->LookupPath.Remain, &Context->LookupPath.Name, &Context->LookupPath.Remain); /* * - RootName: * - UserMode: * - !LastName && !TravPriv: * - Lookup * - TraverseCheck * - LastName: * - Lookup * - AccessCheck * - !UserMode: * - LastName: * - Lookup * - !RootName: * - Lookup * - UserMode: * - !LastName && !TravPriv: * - TraverseCheck * - LastName: * - AccessCheck */ if (!RootName || LastName || (UserMode && !TravPriv)) { coro_await (FuseLookup(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; if (UserMode) { if (!LastName && !TravPriv) { Context->InternalResponse->IoStatus.Status = FuseAccessCheck( Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid, Context->LookupPath.Attr.mode, Context->OrigUid, Context->OrigGid, FILE_TRAVERSE, 0); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } else if (LastName) { Context->InternalResponse->IoStatus.Status = FuseAccessCheck( Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid, Context->LookupPath.Attr.mode, Context->OrigUid, Context->OrigGid, Context->LookupPath.DesiredAccess, &Context->LookupPath.GrantedAccess); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } } } if (LastName) { ASSERT(DEBUGGOOD(&Context->Lookup.Attr, sizeof Context->Lookup.Attr)); break; } } Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } #undef TravPriv #undef UserMode #undef LastName #undef RootName } static VOID FuseCreateCheck(FUSE_CONTEXT *Context) { PAGED_CODE(); /* * CreateCheck for a new file consists of checking the parent directory * for the FILE_ADD_SUBDIRECTORY or FILE_ADD_FILE rights (depending on * whether we are creating a file or directory). * * If the access check succeeds and MAXIMUM_ALLOWED has been requested * then we go ahead and grant all access to the creator. */ coro_block (Context->CoroState) { if (Context->InternalRequest->Req.Create.HasTrailingBackslash && !FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE)) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_INVALID; coro_break; } if (Context->InternalRequest->Req.Create.HasRestorePrivilege) Context->LookupPath.DesiredAccess = 0; else if (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE)) Context->LookupPath.DesiredAccess = FILE_ADD_SUBDIRECTORY; else Context->LookupPath.DesiredAccess = FILE_ADD_FILE; FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0); coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED) ? IoGetFileObjectGenericMapping()->GenericAll : Context->InternalRequest->Req.Create.DesiredAccess; Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |= Context->InternalRequest->Req.Create.GrantedAccess; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } static VOID FuseOpenCheck(FUSE_CONTEXT *Context) { PAGED_CODE(); /* * OpenCheck consists of checking the file for the desired access, * unless FILE_DELETE_ON_CLOSE is requested in which case we also * check for DELETE access. * * If the access check succeeds and MAXIMUM_ALLOWED was not requested * then we reset the DELETE access based on whether it was actually * requested in DesiredAccess. */ coro_block (Context->CoroState) { Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess | (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DELETE_ON_CLOSE) ? DELETE : 0); Context->LookupPath.Remain = Context->LookupPath.OrigPath; coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess; if (!FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED)) Context->InternalResponse->Rsp.Create.Opened.GrantedAccess &= ~DELETE | (Context->InternalRequest->Req.Create.DesiredAccess & DELETE); Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |= Context->InternalRequest->Req.Create.GrantedAccess; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } static VOID FuseOverwriteCheck(FUSE_CONTEXT *Context) { PAGED_CODE(); /* * OverwriteCheck consists of checking the file for the desired access, * unless FILE_DELETE_ON_CLOSE is requested in which case we also * check for DELETE access. Furthermore we grant DELETE or FILE_WRITE_DATA * access based on whether this is a Supersede or Overwrite operation. * * If the access check succeeds and MAXIMUM_ALLOWED was not requested * then we reset the DELETE and FILE_WRITE_DATA accesses based on whether * they were actually requested in DesiredAccess. */ coro_block (Context->CoroState) { Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess | (FILE_SUPERSEDE == ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff) ? DELETE : FILE_WRITE_DATA) | (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DELETE_ON_CLOSE) ? DELETE : 0); Context->LookupPath.Remain = Context->LookupPath.OrigPath; coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess; if (!FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED)) Context->InternalResponse->Rsp.Create.Opened.GrantedAccess &= ~(DELETE | FILE_WRITE_DATA) | (Context->InternalRequest->Req.Create.DesiredAccess & (DELETE | FILE_WRITE_DATA)); Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |= Context->InternalRequest->Req.Create.GrantedAccess; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } static VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context) { PAGED_CODE(); /* * OpenTargetDirectoryCheck consists of checking the parent directory * for the desired access. */ coro_block (Context->CoroState) { Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess; FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0); coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess; Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |= Context->InternalRequest->Req.Create.GrantedAccess; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } static VOID FuseRenameCheck(FUSE_CONTEXT *Context) { PAGED_CODE(); /* * RenameCheck consists of checking the new file name for DELETE access. * * The following assumptions are being made here for a file that is going * to be replaced: * - The new file is in the same directory as the old one. In that case * there is no need for traverse access checks as they have been already * performed (if necessary) when opening the file under the existing file * name. * - The new file is in a different directory than the old one. In that case * NTOS called us with SL_OPEN_TARGET_DIRECTORY and we performed any * necessary traverse access checks at that time. */ coro_block (Context->CoroState) { Context->LookupPath.DesiredAccess = 0; FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0); coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->LookupPath.Ino2 = Context->LookupPath.Ino; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); coro_await (FuseLookup(Context)); if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) { if (0 != Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken) { Context->InternalResponse->IoStatus.Status = FuseAccessCheck( Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid, Context->LookupPath.Attr.mode, Context->OrigUid, Context->OrigGid, DELETE, &Context->LookupPath.GrantedAccess); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } Context->LookupPath.OrigPath2 = Context->LookupPath.OrigPath; Context->LookupPath.Name2 = Context->LookupPath.Name; Context->LookupPath.Ino = 0; Context->LookupPath.OrigPath.Length = Context->LookupPath.OrigPath.MaximumLength = 0; Context->LookupPath.OrigPath.Buffer = 0; Context->LookupPath.Name.Length = Context->LookupPath.Name.MaximumLength = 0; Context->LookupPath.Name.Buffer = 0; } } static VOID FuseCreate(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->InternalResponse->IoStatus.Status = FuseFileCreate(Context->Instance, &Context->File); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->File->OpenFlags = 0x0100 | 0x0400 | 2 /*O_CREAT|O_EXCL|O_RDWR*/; Context->LookupPath.Attr.rdev = 0; Context->LookupPath.Attr.mode = 0777; if (0 != Context->InternalRequest->Req.Create.SecurityDescriptor.Offset) { UINT32 Uid, Gid, Mode; Uid = Context->OrigUid; Gid = Context->OrigGid; Context->InternalResponse->IoStatus.Status = FspPosixMapSecurityDescriptorToPermissions( (PSECURITY_DESCRIPTOR)(Context->InternalRequest->Buffer + Context->InternalRequest->Req.Create.SecurityDescriptor.Offset), (PVOID)((UINT_PTR)&Uid | 1), (PVOID)((UINT_PTR)&Gid | 1), &Mode); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->LookupPath.Attr.mode = Mode; Context->LookupPath.Chown = Uid != Context->OrigUid || Gid != Context->OrigGid; } if (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE)) { coro_await (FuseProtoSendMkdir(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheSetEntry( Context->Instance->Cache, Context->LookupPath.Ino, &Context->LookupPath.Name, &Context->FuseResponse->rsp.mkdir.entry, &Context->LookupPath.CacheItem); Context->LookupPath.Ino = Context->FuseResponse->rsp.mkdir.entry.nodeid; Context->LookupPath.Attr = Context->FuseResponse->rsp.mkdir.entry.attr; coro_await (FuseProtoSendOpendir(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->LookupPath.DisableCache = BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO); Context->File->Ino = Context->LookupPath.Ino; Context->File->Fh = Context->FuseResponse->rsp.open.fh; Context->File->IsDirectory = TRUE; Context->File->CacheItem = Context->LookupPath.CacheItem; FuseCacheReferenceItem(Context->Instance->Cache, Context->File->CacheItem); } else { coro_await (FuseProtoSendCreate(Context)); if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) { FuseCacheSetEntry( Context->Instance->Cache, Context->LookupPath.Ino, &Context->LookupPath.Name, &Context->FuseResponse->rsp.create.entry, &Context->LookupPath.CacheItem); Context->LookupPath.Ino = Context->FuseResponse->rsp.create.entry.nodeid; Context->LookupPath.Attr = Context->FuseResponse->rsp.create.entry.attr; Context->LookupPath.DisableCache = BooleanFlagOn(Context->FuseResponse->rsp.create.open_flags, FUSE_PROTO_OPEN_DIRECT_IO); Context->File->Ino = Context->LookupPath.Ino; Context->File->Fh = Context->FuseResponse->rsp.create.fh; Context->File->CacheItem = Context->LookupPath.CacheItem; FuseCacheReferenceItem(Context->Instance->Cache, Context->File->CacheItem); } else { if (STATUS_INVALID_DEVICE_REQUEST != Context->InternalResponse->IoStatus.Status) coro_break; coro_await (FuseProtoSendMknod(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheSetEntry( Context->Instance->Cache, Context->LookupPath.Ino, &Context->LookupPath.Name, &Context->FuseResponse->rsp.mknod.entry, &Context->LookupPath.CacheItem); Context->LookupPath.Ino = Context->FuseResponse->rsp.mknod.entry.nodeid; Context->LookupPath.Attr = Context->FuseResponse->rsp.mknod.entry.attr; coro_await (FuseProtoSendOpen(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->LookupPath.DisableCache = BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO); Context->File->Ino = Context->LookupPath.Ino; Context->File->Fh = Context->FuseResponse->rsp.open.fh; Context->File->CacheItem = Context->LookupPath.CacheItem; FuseCacheReferenceItem(Context->Instance->Cache, Context->File->CacheItem); } } Context->InternalResponse->Rsp.Create.Opened.UserContext2 = (UINT64)(UINT_PTR)Context->File; FuseAttrToFileInfo(Context->Instance, &Context->LookupPath.Attr, &Context->InternalResponse->Rsp.Create.Opened.FileInfo); Context->InternalResponse->Rsp.Create.Opened.DisableCache = Context->LookupPath.DisableCache; if (Context->LookupPath.Chown) { UINT32 Uid, Gid, Mode; Uid = Context->OrigUid; Gid = Context->OrigGid; Context->InternalResponse->IoStatus.Status = FspPosixMapSecurityDescriptorToPermissions( (PSECURITY_DESCRIPTOR)(Context->InternalRequest->Buffer + Context->InternalRequest->Req.Create.SecurityDescriptor.Offset), (PVOID)((UINT_PTR)&Uid | 1), (PVOID)((UINT_PTR)&Gid | 1), &Mode); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) goto cleanup; Context->LookupPath.Attr.uid = Uid; Context->LookupPath.Attr.gid = Gid; coro_await (FuseProtoSendLookupChown(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status) && STATUS_INVALID_DEVICE_REQUEST != Context->InternalResponse->IoStatus.Status) goto cleanup; FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.setattr.attr, &Context->InternalResponse->Rsp.Create.Opened.FileInfo); } Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = FILE_CREATED; /* ensure that ContextFini will not free the newly opened file */ Context->File = 0; coro_break; cleanup: if (Context->File->IsDirectory) coro_await (FuseProtoSendReleasedir(Context)); else coro_await (FuseProtoSendRelease(Context)); } } static VOID FuseOpen(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->InternalResponse->IoStatus.Status = FuseFileCreate(Context->Instance, &Context->File); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; UINT32 GrantedAccess = Context->InternalResponse->Rsp.Create.Opened.GrantedAccess; switch (GrantedAccess & (FILE_READ_DATA | FILE_WRITE_DATA)) { default: case FILE_READ_DATA: Context->File->OpenFlags = 0/*O_RDONLY*/; break; case FILE_WRITE_DATA: Context->File->OpenFlags = 1/*O_WRONLY*/; break; case FILE_READ_DATA | FILE_WRITE_DATA: Context->File->OpenFlags = 2/*O_RDWR*/; break; } UINT32 Type = Context->LookupPath.Attr.mode & 0170000; if (0120000/* S_IFLNK */ == Type || 0010000/* S_IFIFO */ == Type || 0020000/* S_IFCHR */ == Type || 0060000/* S_IFBLK */ == Type || 0140000/* S_IFSOCK */ == Type) { Context->LookupPath.DisableCache = TRUE; Context->File->Ino = Context->LookupPath.Ino; Context->File->IsReparsePoint = TRUE; } else if (0040000/* S_IFDIR */ == Type) { coro_await (FuseProtoSendOpendir(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->LookupPath.DisableCache = BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO); Context->File->Ino = Context->LookupPath.Ino; Context->File->Fh = Context->FuseResponse->rsp.open.fh; Context->File->IsDirectory = TRUE; } else { /* * Some Windows applications specify FILE_APPEND_DATA without * FILE_WRITE_DATA when opening files for appending. * * NOTE: GrantedAccess has been initialized above and there is no coro_yield or * coro_await between that initialization and this use. */ if (GrantedAccess & FILE_APPEND_DATA) { if (Context->File->OpenFlags == 0) Context->File->OpenFlags = 1/* O_WRONLY */; Context->File->OpenFlags |= 8/*O_APPEND*/; } coro_await (FuseProtoSendOpen(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->LookupPath.DisableCache = BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO); Context->File->Ino = Context->LookupPath.Ino; Context->File->Fh = Context->FuseResponse->rsp.open.fh; } Context->File->CacheItem = Context->LookupPath.CacheItem; FuseCacheReferenceItem(Context->Instance->Cache, Context->File->CacheItem); Context->InternalResponse->Rsp.Create.Opened.UserContext2 = (UINT64)(UINT_PTR)Context->File; FuseAttrToFileInfo(Context->Instance, &Context->LookupPath.Attr, &Context->InternalResponse->Rsp.Create.Opened.FileInfo); Context->InternalResponse->Rsp.Create.Opened.DisableCache = Context->LookupPath.DisableCache; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = FILE_OPENED; /* ensure that ContextFini will not free the newly opened file */ Context->File = 0; } } static VOID FuseOpCreate_FileCreate(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseCreateCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); coro_await (FuseCreate(Context)); } } static VOID FuseOpCreate_FileOpen(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseOpenCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseOpen(Context)); } } static VOID FuseOpCreate_FileOpenIf(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseOpenCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) { if (STATUS_OBJECT_NAME_NOT_FOUND != Context->InternalResponse->IoStatus.Status) coro_break; coro_await (FuseCreateCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); coro_await (FuseCreate(Context)); } else coro_await (FuseOpen(Context)); } } static VOID FuseOpCreate_FileOverwrite(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseOverwriteCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseOpen(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->IoStatus.Information = FILE_OVERWRITTEN; } } static VOID FuseOpCreate_FileOverwriteIf(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseOverwriteCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) { if (STATUS_OBJECT_NAME_NOT_FOUND != Context->InternalResponse->IoStatus.Status) coro_break; coro_await (FuseCreateCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); coro_await (FuseCreate(Context)); } else { coro_await (FuseOpen(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->IoStatus.Information = FILE_OVERWRITTEN; } } } static VOID FuseOpCreate_FileOpenTargetDirectory(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseOpenTargetDirectoryCheck(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseOpen(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); coro_await (FuseLookup(Context)); Context->InternalResponse->IoStatus.Information = NT_SUCCESS(Context->InternalResponse->IoStatus.Status) ? FILE_EXISTS : FILE_DOES_NOT_EXIST; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } static BOOLEAN FuseOpCreate(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { if (Context->InternalRequest->Req.Create.NamedStream) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_INVALID; coro_break; } FusePrepareLookupPath(Context); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; UINT32 Disposition = (Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff; if (Context->InternalRequest->Req.Create.OpenTargetDirectory) coro_await (FuseOpCreate_FileOpenTargetDirectory(Context)); else if (FILE_CREATE == Disposition) coro_await (FuseOpCreate_FileCreate(Context)); else if (FILE_OPEN == Disposition) coro_await (FuseOpCreate_FileOpen(Context)); else if (FILE_OPEN_IF == Disposition) coro_await (FuseOpCreate_FileOpenIf(Context)); else if (FILE_OVERWRITE == Disposition) coro_await (FuseOpCreate_FileOverwrite(Context)); else if (FILE_OVERWRITE_IF == Disposition || FILE_SUPERSEDE == Disposition) coro_await (FuseOpCreate_FileOverwriteIf(Context)); else Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER; } return coro_active(); } static INT FuseOgCreate(FUSE_CONTEXT *Context, BOOLEAN Acquire) { PAGED_CODE(); if (Acquire) { INT Result; if (FILE_OPEN != ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff)) Result = FuseOpGuardAcquireExclusive(Context); else Result = FuseOpGuardAcquireShared(Context); #if DBG /* * In debug builds we add an artificial delay to our opens to test alertable locks. */ if (Result) { UNICODE_STRING LockDly, FileName; RtlInitUnicodeString(&LockDly, L"\\$LOCKDLY"); FileName.Length = FileName.MaximumLength = Context->InternalRequest->FileName.Size - sizeof(WCHAR); FileName.Buffer = (PVOID)( Context->InternalRequest->Buffer + Context->InternalRequest->FileName.Offset); if (RtlEqualUnicodeString(&LockDly, &FileName, FALSE)) { LARGE_INTEGER Delay; Delay.QuadPart = 5000/*ms*/ * -10000LL; KeDelayExecutionThread(KernelMode, FALSE, &Delay); } } #endif return Result; } else { if (FILE_OPEN != ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff)) return FuseOpGuardReleaseExclusive(Context); else return FuseOpGuardReleaseShared(Context); } } static BOOLEAN FuseOpOverwrite(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Overwrite.UserContext2; //Context->Setattr.Attr.size = 0; coro_await (FuseProtoSendFtruncate(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheQuickExpireItem(Context->Instance->Cache, Context->File->CacheItem); FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr, &Context->InternalResponse->Rsp.Overwrite.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpCleanup(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { if (Context->InternalRequest->Req.Cleanup.Delete) { /* NOTE: CLEANUP cannot report failure! */ Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Cleanup.UserContext2; FusePrepareLookupPath(Context); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0); coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); if (Context->File->IsDirectory) coro_await (FuseProtoSendRmdir(Context)); else coro_await (FuseProtoSendUnlink(Context)); FuseCacheRemoveEntry( Context->Instance->Cache, Context->Lookup.Ino, &Context->Lookup.Name); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } } return coro_active(); } static INT FuseOgCleanup(FUSE_CONTEXT *Context, BOOLEAN Acquire) { PAGED_CODE(); if (Acquire) { if (Context->InternalRequest->Req.Cleanup.Delete) return FuseOpGuardAcquireExclusive(Context); else return FuseOpGuardFalse; } else { if (Context->InternalRequest->Req.Cleanup.Delete) return FuseOpGuardReleaseExclusive(Context); else return FuseOpGuardFalse; } } static BOOLEAN FuseOpClose(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { /* NOTE: CLOSE cannot report failure! */ Context->Fini = FuseOpClose_ContextFini; Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Close.UserContext2; if (Context->File->IsReparsePoint) /* reparse points are not opened; ignore */; else if (Context->File->IsDirectory) coro_await (FuseProtoSendReleasedir(Context)); else coro_await (FuseProtoSendRelease(Context)); } return coro_active(); } static VOID FuseOpClose_ContextFini(FUSE_CONTEXT *Context) { PAGED_CODE(); if (0 != Context->File) FuseFileDelete(Context->Instance, Context->File); } static BOOLEAN FuseOpRead(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Read.UserContext2; Context->Read.StartOffset = Context->InternalRequest->Req.Read.Offset; Context->Read.Remain = Context->InternalRequest->Req.Read.Length; Context->Read.Offset = 0; while (0 != Context->Read.Remain) { Context->Read.Length = Context->Read.Remain; #if DBG if (DEBUGTEST(10) && Context->Read.Length > 512) Context->Read.Length = 512; #endif #if 0 FUSE_DEVICE_EXTENSION *Instance = FuseDeviceExtension(Context->DeviceObject); if (Context->Read.Length > Instance->VolumeParams.MaxRead) Context->Read.Length = Instance->VolumeParams.MaxRead; #endif coro_await (FuseProtoSendRead(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; UINT32 BytesTransferred = Context->FuseResponse->len - FUSE_PROTO_RSP_HEADER_SIZE; if (Context->Read.Length < BytesTransferred) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR; coro_break; } Context->InternalResponse->IoStatus.Status = FuseSafeCopyMemory( (PUINT8)(UINT_PTR)Context->InternalRequest->Req.Read.Address + Context->Write.Offset, (PUINT8)Context->FuseResponse + FUSE_PROTO_RSP_HEADER_SIZE, BytesTransferred); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->Read.Remain -= BytesTransferred; Context->Read.Offset += BytesTransferred; if (Context->Read.Length > BytesTransferred) break; } Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = Context->Read.Offset; if (0 == Context->InternalResponse->IoStatus.Information) Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_END_OF_FILE; } return coro_active(); } static BOOLEAN FuseOpWrite(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Write.UserContext2; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->Write.Attr = Context->FuseResponse->rsp.getattr.attr; UINT64 EndOffset; Context->Write.StartOffset = Context->InternalRequest->Req.Write.Offset; if (Context->InternalRequest->Req.Write.ConstrainedIo) { if (Context->Write.StartOffset >= Context->Write.Attr.size) { FuseAttrToFileInfo(Context->Instance, &Context->Write.Attr, &Context->InternalResponse->Rsp.Write.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = 0; coro_break; } EndOffset = Context->Write.StartOffset + Context->InternalRequest->Req.Write.Length; if (EndOffset > Context->Write.Attr.size) EndOffset = Context->Write.Attr.size; } else { if ((UINT64)-1LL == Context->Write.StartOffset) Context->Write.StartOffset = Context->Write.Attr.size; EndOffset = Context->Write.StartOffset + Context->InternalRequest->Req.Write.Length; } Context->Write.Remain = (UINT32)(EndOffset - Context->Write.StartOffset); Context->Write.Offset = 0; while (0 != Context->Write.Remain) { FuseContextWaitRequest(Context); Context->Write.Length = Context->Write.Remain; #if DBG if (DEBUGTEST(10) && Context->Write.Length > 512) Context->Write.Length = 512; #endif if (Context->Write.Length > Context->FuseRequestLength - FUSE_PROTO_REQ_SIZE(write)) Context->Write.Length = Context->FuseRequestLength - FUSE_PROTO_REQ_SIZE(write); Context->InternalResponse->IoStatus.Status = FuseSafeCopyMemory( (PUINT8)Context->FuseRequest + FUSE_PROTO_REQ_SIZE(write), (PUINT8)(UINT_PTR)Context->InternalRequest->Req.Write.Address + Context->Write.Offset, Context->Write.Length); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseProtoSendWrite(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; UINT32 BytesTransferred = Context->FuseResponse->rsp.write.size; if (Context->Write.Length < BytesTransferred) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR; coro_break; } Context->Write.Remain -= BytesTransferred; Context->Write.Offset += BytesTransferred; if (Context->Write.Length > BytesTransferred) break; } if (Context->Write.Attr.size < Context->Write.StartOffset + Context->Write.Offset) Context->Write.Attr.size = Context->Write.StartOffset + Context->Write.Offset; FuseCacheQuickExpireItem(Context->Instance->Cache, Context->File->CacheItem); FuseAttrToFileInfo(Context->Instance, &Context->Write.Attr, &Context->InternalResponse->Rsp.Write.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = Context->Write.Offset; } return coro_active(); } static BOOLEAN FuseOpQueryInformation(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryInformation.UserContext2; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr, &Context->InternalResponse->Rsp.QueryInformation.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetInformation_SetBasicInfo(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2; if (0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastAccessTime || 0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastWriteTime) { if (0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastAccessTime) FuseFileTimeToUnixTime(Context->InternalRequest->Req.SetInformation.Info.Basic.LastAccessTime, &Context->Setattr.Attr.atime, &Context->Setattr.Attr.atimensec); else Context->Setattr.Attr.atimensec = FUSE_PROTO_UTIME_OMIT; if (0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastWriteTime) FuseFileTimeToUnixTime(Context->InternalRequest->Req.SetInformation.Info.Basic.LastWriteTime, &Context->Setattr.Attr.mtime, &Context->Setattr.Attr.mtimensec); else Context->Setattr.Attr.mtimensec = FUSE_PROTO_UTIME_OMIT; coro_await (FuseProtoSendFutimens(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheQuickExpireItem(Context->Instance->Cache, Context->File->CacheItem); FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr, &Context->InternalResponse->Rsp.SetInformation.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetInformation_SetAllocationSize(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; if (Context->FuseResponse->rsp.getattr.attr.size > Context->InternalRequest->Req.SetInformation.Info.Allocation.AllocationSize) { Context->Setattr.Attr.size = Context->InternalRequest->Req.SetInformation.Info.Allocation.AllocationSize; coro_await (FuseProtoSendFtruncate(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } FuseCacheQuickExpireItem(Context->Instance->Cache, Context->File->CacheItem); FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr, &Context->InternalResponse->Rsp.SetInformation.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetInformation_SetFileSize(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2; Context->Setattr.Attr.size = Context->InternalRequest->Req.SetInformation.Info.EndOfFile.FileSize; coro_await (FuseProtoSendFtruncate(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheQuickExpireItem(Context->Instance->Cache, Context->File->CacheItem); FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr, &Context->InternalResponse->Rsp.SetInformation.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetInformation_SetDelete(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2; if (Context->InternalRequest->Req.SetInformation.Info.Disposition.Delete && Context->File->IsDirectory && !Context->File->IsReparsePoint) { Context->QueryDirectory.NextOffset = 0; Context->QueryDirectory.Length = FSP_FSCTL_ALIGN_UP(sizeof(FUSE_PROTO_DIRENT) + 1, 8) + FSP_FSCTL_ALIGN_UP(sizeof(FUSE_PROTO_DIRENT) + 2, 8) + FSP_FSCTL_ALIGN_UP(sizeof(FUSE_PROTO_DIRENT) + 255, 8); /* enough for ".", ".." and an entry with a name up to 255 chars long */ coro_await (FuseProtoSendReaddir(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; if (FUSE_PROTO_RSP_HEADER_SIZE + Context->QueryDirectory.Length < Context->FuseResponse->len) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR; coro_break; } PUINT8 BufferEndP = (PUINT8)Context->FuseResponse + Context->FuseResponse->len; PUINT8 BufferP = (PUINT8)Context->FuseResponse + FUSE_PROTO_RSP_HEADER_SIZE; for (;;) { if (BufferEndP < BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) || BufferEndP < BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) + ((FUSE_PROTO_DIRENT *)BufferP)->namelen) break; FUSE_PROTO_DIRENT *Dirent = (FUSE_PROTO_DIRENT *)BufferP; if ((1 == Dirent->namelen && '.' == Dirent->name[0]) || (2 == Dirent->namelen && '.' == Dirent->name[0] && '.' == Dirent->name[1])) /*ignore*/; else { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_DIRECTORY_NOT_EMPTY; coro_break; } BufferP += FSP_FSCTL_ALIGN_UP( FIELD_OFFSET(FUSE_PROTO_DIRENT, name) + ((FUSE_PROTO_DIRENT *)BufferP)->namelen, 8); } } Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetInformation_Rename(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2; FusePrepareLookupPath(Context); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; coro_await (FuseRenameCheck(Context)); if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) Context->LookupPath.RenameIsDirectory = 0040000 == (Context->LookupPath.Attr.mode & 0170000); else if (STATUS_OBJECT_PATH_NOT_FOUND == Context->InternalResponse->IoStatus.Status || STATUS_OBJECT_NAME_NOT_FOUND == Context->InternalResponse->IoStatus.Status) Context->LookupPath.RenameIsNonExistent = 1; else coro_break; FusePrepareLookupPath2(Context); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0); coro_await (FuseLookupPath(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name); if (!Context->LookupPath.RenameIsNonExistent && (Context->Instance->VolumeParams->CaseSensitiveSearch || Context->LookupPath.Ino != Context->LookupPath.Ino2 || !RtlEqualString(&Context->LookupPath.Name, &Context->LookupPath.Name2, TRUE))) { if (0 == Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_COLLISION; coro_break; } if (Context->LookupPath.RenameIsDirectory) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_ACCESS_DENIED; coro_break; } } coro_await (FuseProtoSendRename(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheRemoveEntry( Context->Instance->Cache, Context->LookupPath.Ino, &Context->LookupPath.Name); FuseCacheRemoveEntry( Context->Instance->Cache, Context->LookupPath.Ino2, &Context->LookupPath.Name2); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetInformation(FUSE_CONTEXT *Context) { PAGED_CODE(); switch (Context->InternalRequest->Req.SetInformation.FileInformationClass) { case FileBasicInformation: return FuseOpSetInformation_SetBasicInfo(Context); case FileAllocationInformation: return FuseOpSetInformation_SetAllocationSize(Context); case FileEndOfFileInformation: return FuseOpSetInformation_SetFileSize(Context); case FileDispositionInformation: return FuseOpSetInformation_SetDelete(Context); case FileRenameInformation: return FuseOpSetInformation_Rename(Context); default: Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_DEVICE_REQUEST; return FALSE; } } static INT FuseOgSetInformation(FUSE_CONTEXT *Context, BOOLEAN Acquire) { PAGED_CODE(); if (Acquire) { if (FileRenameInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass) return FuseOpGuardAcquireExclusive(Context); else if (FileDispositionInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass) return FuseOpGuardAcquireShared(Context); else return FuseOpGuardFalse; } else { if (FileRenameInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass) return FuseOpGuardReleaseExclusive(Context); else if (FileDispositionInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass) return FuseOpGuardReleaseShared(Context); else return FuseOpGuardFalse; } } static BOOLEAN FuseOpQueryEa(FUSE_CONTEXT *Context) { PAGED_CODE(); return FALSE; } static BOOLEAN FuseOpSetEa(FUSE_CONTEXT *Context) { PAGED_CODE(); return FALSE; } static BOOLEAN FuseOpFlushBuffers(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.FlushBuffers.UserContext2; if (0 == Context->File) { /* FUSE cannot flush volumes */ Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; coro_break; } if (Context->File->IsDirectory) coro_await (FuseProtoSendFsyncdir(Context)); else coro_await (FuseProtoSendFsync(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status) && STATUS_INVALID_DEVICE_REQUEST != Context->InternalResponse->IoStatus.Status) coro_break; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseCacheQuickExpireItem(Context->Instance->Cache, Context->File->CacheItem); FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr, &Context->InternalResponse->Rsp.FlushBuffers.FileInfo); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpQueryVolumeInformation(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { coro_await (FuseProtoSendStatfs(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->Rsp.QueryVolumeInformation.VolumeInfo.TotalSize = (UINT64)Context->FuseResponse->rsp.statfs.st.blocks * (UINT64)Context->FuseResponse->rsp.statfs.st.frsize; Context->InternalResponse->Rsp.QueryVolumeInformation.VolumeInfo.FreeSize = (UINT64)Context->FuseResponse->rsp.statfs.st.bfree * (UINT64)Context->FuseResponse->rsp.statfs.st.frsize; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseAddDirInfo(FUSE_CONTEXT *Context, PSTRING Name, UINT64 NextOffset, FUSE_PROTO_ATTR *Attr, PVOID Buffer, ULONG Length, PULONG PBytesTransferred) { PAGED_CODE(); try { NTSTATUS Result; PVOID BufferEnd = (PUINT8)Buffer + Length; FSP_FSCTL_DIR_INFO *DirInfo; ULONG WideNameLength, DirInfoSize, AlignedSize; WCHAR WideName[255]; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; if (0 != Name) { Result = RtlUTF8ToUnicodeN( WideName, sizeof WideName, &WideNameLength, Name->Buffer, Name->Length); if (STATUS_SOME_NOT_MAPPED == Result) Result = STATUS_SUCCESS; else if (!NT_SUCCESS(Result)) return TRUE; /* return SUCCESS but IGNORE */ FspPosixDecodeWindowsPath(WideName, WideNameLength / sizeof(WCHAR)); DirInfoSize = sizeof(FSP_FSCTL_DIR_INFO) + WideNameLength; AlignedSize = FSP_FSCTL_DEFAULT_ALIGN_UP(DirInfoSize); Buffer = (PVOID)((PUINT8)Buffer + *PBytesTransferred); if ((PUINT8)Buffer + AlignedSize > (PUINT8)BufferEnd) return FALSE; DirInfo = Buffer; DirInfo->Size = (UINT16)DirInfoSize; FuseAttrToFileInfo(Context->Instance, Attr, &DirInfo->FileInfo); DirInfo->NextOffset = NextOffset; RtlCopyMemory(DirInfo->FileNameBuf, WideName, WideNameLength); } else { DirInfoSize = sizeof(UINT16); AlignedSize = DirInfoSize; Buffer = (PVOID)((PUINT8)Buffer + *PBytesTransferred); if ((PUINT8)Buffer + AlignedSize > (PUINT8)BufferEnd) return FALSE; *(PUINT16)Buffer = 0; } *PBytesTransferred += AlignedSize; return TRUE; } except (EXCEPTION_EXECUTE_HANDLER) { Context->InternalResponse->IoStatus.Status = GetExceptionCode(); if (FsRtlIsNtstatusExpected(Context->InternalResponse->IoStatus.Status)) Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_USER_BUFFER; return FALSE; } } static VOID FuseOpQueryDirectory_GetDirInfoByName(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { { PWSTR FileName = (PWSTR)(Context->InternalRequest->Buffer + Context->InternalRequest->Req.QueryDirectory.Pattern.Offset); PSTR PosixName; Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx( FileName, &PosixName, TRUE); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; RtlInitString(&Context->QueryDirectory.OrigName, PosixName); } Context->QueryDirectory.Ino = Context->File->Ino; Context->QueryDirectory.Name = Context->QueryDirectory.OrigName; coro_await (FuseLookup(Context)); BOOLEAN AddDirInfoEnd = FALSE; if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) AddDirInfoEnd = FuseAddDirInfo( Context, &Context->QueryDirectory.Name, 0, &Context->QueryDirectory.Attr, (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address, Context->InternalRequest->Req.QueryDirectory.Length, &Context->QueryDirectory.BytesTransferred); else if (STATUS_OBJECT_NAME_NOT_FOUND == Context->InternalResponse->IoStatus.Status) AddDirInfoEnd = TRUE; if (AddDirInfoEnd) FuseAddDirInfo( Context, 0, 0, 0, (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address, Context->InternalRequest->Req.QueryDirectory.Length, &Context->QueryDirectory.BytesTransferred); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = Context->QueryDirectory.BytesTransferred; } } static VOID FuseOpQueryDirectory_ReadDirectory(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->QueryDirectory.NextOffset = sizeof(UINT64) + sizeof(WCHAR) == Context->InternalRequest->Req.QueryDirectory.Marker.Size ? *(PUINT64)(Context->InternalRequest->Buffer + Context->InternalRequest->Req.QueryDirectory.Marker.Offset) : 0; /* * The FSD has sent us a buffer of QueryDirectory.Length size that holds FSP_FSCTL_DIR_INFO * entries. Assuming that the average file name length is 24 we approximate how many entries * (N) we can fit in that buffer: * * N = QueryDirectory.Length / (sizeof(FSP_FSCTL_DIR_INFO) + (24 * sizeof(WCHAR))) * * We now approximate the FUSE READDIR buffer size required to fit N entries: * * read.size = FUSE_PROTO_RSP_HEADER_SIZE + N * (sizeof(FUSE_PROTO_DIRENT) + 24) */ UINT32 N = Context->InternalRequest->Req.QueryDirectory.Length / (sizeof(FSP_FSCTL_DIR_INFO) + (24 * sizeof(WCHAR))); Context->QueryDirectory.Length = N * (sizeof(FUSE_PROTO_DIRENT) + 24); coro_await (FuseProtoSendReaddir(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; if (FUSE_PROTO_RSP_HEADER_SIZE + Context->QueryDirectory.Length < Context->FuseResponse->len) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR; coro_break; } if (FUSE_PROTO_RSP_HEADER_SIZE < Context->FuseResponse->len) { Context->QueryDirectory.Buffer = FuseAlloc(Context->FuseResponse->len); if (0 == Context->QueryDirectory.Buffer) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INSUFFICIENT_RESOURCES; coro_break; } RtlCopyMemory(Context->QueryDirectory.Buffer, Context->FuseResponse, Context->FuseResponse->len); } Context->QueryDirectory.BufferEndP = Context->QueryDirectory.Buffer + Context->FuseResponse->len; Context->QueryDirectory.BufferP = Context->QueryDirectory.Buffer + FUSE_PROTO_RSP_HEADER_SIZE; for (;;) { if (Context->QueryDirectory.BufferEndP < Context->QueryDirectory.BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) || Context->QueryDirectory.BufferEndP < Context->QueryDirectory.BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) + ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->namelen) break; Context->QueryDirectory.Name.Length = Context->QueryDirectory.Name.MaximumLength = (USHORT) ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->namelen; Context->QueryDirectory.Name.Buffer = ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->name; if ((1 == Context->QueryDirectory.Name.Length && '.' == Context->QueryDirectory.Name.Buffer[0]) || (2 == Context->QueryDirectory.Name.Length && '.' == Context->QueryDirectory.Name.Buffer[0] && '.' == Context->QueryDirectory.Name.Buffer[1])) { /* * If the file system gave us a real inode number try getattr on it. * Otherwise try with the inode number from the file descriptor (this * is obviously incorrect for the parent "..", but we are doing the * best we can). */ Context->QueryDirectory.Ino = FUSE_PROTO_UNKNOWN_INO != ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->ino ? ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->ino : Context->File->Ino; coro_await (FuseProtoSendGetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->Lookup.Attr = Context->FuseResponse->rsp.getattr.attr; } else { Context->QueryDirectory.Ino = Context->File->Ino; coro_await (FuseLookup(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } BOOLEAN Added = FuseAddDirInfo( Context, &Context->QueryDirectory.Name, ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->off, &Context->QueryDirectory.Attr, (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address, Context->InternalRequest->Req.QueryDirectory.Length, &Context->QueryDirectory.BytesTransferred); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; if (!Added) break; Context->QueryDirectory.BufferP += FSP_FSCTL_ALIGN_UP( FIELD_OFFSET(FUSE_PROTO_DIRENT, name) + ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->namelen, 8); } /* empty readdir response signifies end of dir; add WinFsp end-of-dir marker */ if (Context->QueryDirectory.BufferP == Context->QueryDirectory.Buffer + FUSE_PROTO_RSP_HEADER_SIZE) FuseAddDirInfo(Context, 0, 0, 0, (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address, Context->InternalRequest->Req.QueryDirectory.Length, &Context->QueryDirectory.BytesTransferred); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; Context->InternalResponse->IoStatus.Information = Context->QueryDirectory.BytesTransferred; } } static BOOLEAN FuseOpQueryDirectory(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->Fini = FuseOpQueryDirectory_ContextFini; Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.UserContext2; Context->InternalResponse->IoStatus.Status = FuseCacheReferenceGen( Context->Instance->Cache, &Context->QueryDirectory.CacheGen); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; if (0 != Context->InternalRequest->Req.QueryDirectory.Pattern.Size && Context->InternalRequest->Req.QueryDirectory.PatternIsFileName) coro_await (FuseOpQueryDirectory_GetDirInfoByName(Context)); else coro_await (FuseOpQueryDirectory_ReadDirectory(Context)); } return coro_active(); } static VOID FuseOpQueryDirectory_ContextFini(FUSE_CONTEXT *Context) { PAGED_CODE(); if (0 != Context->QueryDirectory.Buffer) FuseFree(Context->QueryDirectory.Buffer); FspPosixDeletePath(Context->QueryDirectory.OrigName.Buffer); /* handles NULL paths */ FuseCacheDereferenceGen(Context->Instance->Cache, Context->QueryDirectory.CacheGen); /* handles NULL gens */ } static INT FuseOgQueryDirectory(FUSE_CONTEXT *Context, BOOLEAN Acquire) { PAGED_CODE(); if (Acquire) return FuseOpGuardAcquireShared(Context); else return FuseOpGuardReleaseShared(Context); } static BOOLEAN FuseOpFileSystemControl(FUSE_CONTEXT *Context) { PAGED_CODE(); return FALSE; } static BOOLEAN FuseOpDeviceControl(FUSE_CONTEXT *Context) { PAGED_CODE(); return FALSE; } static BOOLEAN FuseOpQuerySecurity(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->Fini = FuseSecurity_ContextFini; Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.QuerySecurity.UserContext2; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->IoStatus.Status = FspPosixMapPermissionsToSecurityDescriptor( Context->FuseResponse->rsp.getattr.attr.uid, Context->FuseResponse->rsp.getattr.attr.gid, Context->FuseResponse->rsp.getattr.attr.mode, &Context->Security.SecurityDescriptor); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; ULONG Length = RtlLengthSecurityDescriptor(Context->Security.SecurityDescriptor); if (FSP_FSCTL_TRANSACT_RSP_BUFFER_SIZEMAX < Length) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_SECURITY_DESCR; coro_break; } PVOID InternalResponse = FuseAlloc(sizeof *Context->InternalResponse + Length); if (0 == InternalResponse) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INSUFFICIENT_RESOURCES; coro_break; } RtlZeroMemory(InternalResponse, sizeof *Context->InternalResponse); Context->InternalResponse = InternalResponse; Context->InternalResponse->Size = (UINT16)(sizeof *Context->InternalResponse + Length); Context->InternalResponse->Kind = Context->InternalRequest->Kind; Context->InternalResponse->Hint = Context->InternalRequest->Hint; Context->InternalResponse->Rsp.QuerySecurity.SecurityDescriptor.Offset = 0; Context->InternalResponse->Rsp.QuerySecurity.SecurityDescriptor.Size = (UINT16)Length; /* RtlCopyMemory is safe here, because all buffers are in-kernel */ RtlCopyMemory( Context->InternalResponse->Buffer, Context->Security.SecurityDescriptor, Length); Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static BOOLEAN FuseOpSetSecurity(FUSE_CONTEXT *Context) { PAGED_CODE(); coro_block (Context->CoroState) { Context->Fini = FuseSecurity_ContextFini; Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetSecurity.UserContext2; coro_await (FuseProtoSendFgetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->InternalResponse->IoStatus.Status = FspPosixMapPermissionsToSecurityDescriptor( Context->FuseResponse->rsp.getattr.attr.uid, Context->FuseResponse->rsp.getattr.attr.gid, Context->FuseResponse->rsp.getattr.attr.mode, &Context->Security.SecurityDescriptor); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; /* * BEGIN: * No coro_yield or coro_await allowed, because Context->FuseResponse->rsp.getattr.attr * must remain valid. */ PSECURITY_DESCRIPTOR NewSecurityDescriptor = Context->Security.SecurityDescriptor; Context->InternalResponse->IoStatus.Status = SeSetSecurityDescriptorInfo( 0, (PSECURITY_INFORMATION)&Context->InternalRequest->Req.SetSecurity.SecurityInformation, (PSECURITY_DESCRIPTOR)Context->InternalRequest->Buffer, &NewSecurityDescriptor, PagedPool, IoGetFileObjectGenericMapping()); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; FuseFreeExternal(Context->Security.SecurityDescriptor); Context->Security.SecurityDescriptor = NewSecurityDescriptor; Context->InternalResponse->IoStatus.Status = FspPosixMapSecurityDescriptorToPermissions( Context->Security.SecurityDescriptor, &Context->Security.Attr.uid, &Context->Security.Attr.gid, &Context->Security.Attr.mode); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; Context->Security.Attr.mode &= 07777; Context->Security.Attr.mode |= (Context->FuseResponse->rsp.getattr.attr.mode & 0170000); Context->Security.AttrValid = 0; Context->Security.AttrValid |= Context->Security.Attr.uid != Context->FuseResponse->rsp.getattr.attr.uid ? FUSE_PROTO_SETATTR_UID : 0; Context->Security.AttrValid |= Context->Security.Attr.gid != Context->FuseResponse->rsp.getattr.attr.gid ? FUSE_PROTO_SETATTR_GID : 0; Context->Security.AttrValid |= Context->Security.Attr.mode != Context->FuseResponse->rsp.getattr.attr.mode ? FUSE_PROTO_SETATTR_MODE : 0; /* * END: * No coro_yield or coro_await allowed, because Context->FuseResponse->rsp.getattr.attr * must remain valid. */ if (0 != Context->Security.AttrValid) { coro_await (FuseProtoSendSetattr(Context)); if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status)) coro_break; } Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS; } return coro_active(); } static VOID FuseSecurity_ContextFini(FUSE_CONTEXT *Context) { PAGED_CODE(); if (0 != Context->Security.SecurityDescriptor) FuseFreeExternal(Context->Security.SecurityDescriptor); } FUSE_OPERATION FuseOperations[FspFsctlTransactKindCount] = { /* FspFsctlTransactReservedKind */ { FuseOpReserved }, /* FspFsctlTransactCreateKind */ { FuseOpCreate, FuseOgCreate }, /* FspFsctlTransactOverwriteKind */ { FuseOpOverwrite }, /* FspFsctlTransactCleanupKind */ { FuseOpCleanup, FuseOgCleanup }, /* FspFsctlTransactCloseKind */ { FuseOpClose }, /* FspFsctlTransactReadKind */ { FuseOpRead }, /* FspFsctlTransactWriteKind */ { FuseOpWrite }, /* FspFsctlTransactQueryInformationKind */ { FuseOpQueryInformation }, /* FspFsctlTransactSetInformationKind */ { FuseOpSetInformation, FuseOgSetInformation }, /* FspFsctlTransactQueryEaKind */ { 0 }, /* FspFsctlTransactSetEaKind */ { 0 }, /* FspFsctlTransactFlushBuffersKind */ { FuseOpFlushBuffers }, /* FspFsctlTransactQueryVolumeInformationKind */ { FuseOpQueryVolumeInformation }, /* FspFsctlTransactSetVolumeInformationKind */ { 0 }, /* FspFsctlTransactQueryDirectoryKind */ { FuseOpQueryDirectory, FuseOgQueryDirectory }, /* FspFsctlTransactFileSystemControlKind */ { 0 }, /* FspFsctlTransactDeviceControlKind */ { 0 }, /* FspFsctlTransactShutdownKind */ { 0 }, /* FspFsctlTransactLockControlKind */ { 0 }, /* FspFsctlTransactQuerySecurityKind */ { FuseOpQuerySecurity }, /* FspFsctlTransactSetSecurityKind */ { FuseOpSetSecurity }, /* FspFsctlTransactQueryStreamInformationKind */ { 0 }, }; ================================================ FILE: src/shared/km/instance.c ================================================ /** * @file shared/km/instance.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include NTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance, FSP_FSCTL_VOLUME_PARAMS *VolumeParams, FUSE_INSTANCE_TYPE InstanceType); VOID FuseInstanceFini(FUSE_INSTANCE *Instance); VOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 ExpirationTime); NTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance, FUSE_PROTO_RSP *FuseResponse, ULONG InputBufferLength, FUSE_PROTO_REQ *FuseRequest, PULONG POutputBufferLength, PDEVICE_OBJECT DeviceObject, PFILE_OBJECT FileObject, PIRP CancellableIrp); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseInstanceInit) #pragma alloc_text(PAGE, FuseInstanceFini) #pragma alloc_text(PAGE, FuseInstanceExpirationRoutine) #pragma alloc_text(PAGE, FuseInstanceTransact) #endif NTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance, FSP_FSCTL_VOLUME_PARAMS *VolumeParams, FUSE_INSTANCE_TYPE InstanceType) { PAGED_CODE(); NTSTATUS Result; RtlZeroMemory(Instance, sizeof *Instance); Instance->VolumeParams = VolumeParams; Instance->InstanceType = InstanceType; FuseRwlockInitialize(&Instance->OpGuardLock); Result = FuseIoqCreate(&Instance->Ioq); if (!NT_SUCCESS(Result)) goto exit; Result = FuseCacheCreate(0, 0/*!VolumeParams->CaseSensitiveSearch*/, &Instance->Cache); if (!NT_SUCCESS(Result)) goto exit; FuseFileInstanceInit(Instance); KeInitializeEvent(&Instance->InitEvent, NotificationEvent, FALSE); Result = FuseProtoPostInit(Instance); if (!NT_SUCCESS(Result)) goto exit; /* ensure that VolumeParams can be used for FUSE operations */ VolumeParams->CaseSensitiveSearch = 1; /* revisit FuseCacheCreate above if this changes */ VolumeParams->CasePreservedNames = 1; VolumeParams->PersistentAcls = 1; VolumeParams->ReparsePoints = 1; VolumeParams->ReparsePointsAccessCheck = 0; VolumeParams->NamedStreams = 0; VolumeParams->ReadOnlyVolume = 0; VolumeParams->PostCleanupWhenModifiedOnly = 1; VolumeParams->PassQueryDirectoryFileName = 1; VolumeParams->DeviceControl = 1; VolumeParams->DirectoryMarkerAsNextOffset = 1; Result = STATUS_SUCCESS; exit: if (!NT_SUCCESS(Result)) { if (0 != Instance->Cache) FuseCacheDelete(Instance->Cache); if (0 != Instance->Ioq) FuseIoqDelete(Instance->Ioq); FuseRwlockFinalize(&Instance->OpGuardLock); RtlZeroMemory(Instance, sizeof *Instance); } return Result; } VOID FuseInstanceFini(FUSE_INSTANCE *Instance) { PAGED_CODE(); /* * The order of finalization is IMPORTANT: * * FuseIoqDelete must precede FuseFileInstanceFini, because the Ioq may contain Contexts * that hold File's. * * FuseIoqDelete must precede FuseCacheDelete, because the Ioq may contain Contexts * that hold CacheGen references. * * FuseFileInstanceFini must precede FuseCacheDelete, because some Files may hold * CacheItem references. */ FuseIoqDelete(Instance->Ioq); FuseFileInstanceFini(Instance); FuseCacheDelete(Instance->Cache); FuseRwlockFinalize(&Instance->OpGuardLock); } VOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 ExpirationTime) { PAGED_CODE(); FuseCacheExpirationRoutine(Instance->Cache, Instance, ExpirationTime); } NTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance, FUSE_PROTO_RSP *FuseResponse, ULONG InputBufferLength, FUSE_PROTO_REQ *FuseRequest, PULONG POutputBufferLength, PDEVICE_OBJECT DeviceObject, PFILE_OBJECT FileObject, PIRP CancellableIrp) { PAGED_CODE(); ULONG OutputBufferLength = *POutputBufferLength; FSP_FSCTL_TRANSACT_REQ *InternalRequest = 0; FSP_FSCTL_TRANSACT_RSP InternalResponse; FUSE_CONTEXT *Context; BOOLEAN Continue; NTSTATUS Result; *POutputBufferLength = 0; /* check parameters */ if (0 != FuseResponse) { if (FUSE_PROTO_RSP_HEADER_SIZE > InputBufferLength || FUSE_PROTO_RSP_HEADER_SIZE > FuseResponse->len || FuseResponse->len > InputBufferLength) return STATUS_INVALID_PARAMETER; } if (0 != FuseRequest) { if (FUSE_PROTO_REQ_SIZEMIN > OutputBufferLength) return STATUS_BUFFER_TOO_SMALL; } if (0 != FuseResponse) { Context = FuseIoqEndProcessing(Instance->Ioq, FuseResponse->unique); if (0 == Context) goto request; #if DBG if (fuse_debug & fuse_debug_dp) FuseDebugLogResponse(FuseResponse); #endif Continue = FuseContextProcess(Context, FuseResponse, 0, 0); if (Continue) FuseIoqPostPending(Instance->Ioq, Context); else if (0 == Context->InternalRequest) FuseContextDelete(Context); else { ASSERT(FspFsctlTransactReservedKind != Context->InternalResponse->Kind); Result = FspFsextProviderTransact( DeviceObject, FileObject, Context->InternalResponse, 0); FuseContextDelete(Context); if (!NT_SUCCESS(Result)) goto exit; } } request: if (0 != FuseRequest) { RtlZeroMemory(FuseRequest, sizeof(FUSE_PROTO_REQ)); Context = FuseIoqNextPending(Instance->Ioq); if (0 == Context) { UINT32 VersionMajor = Instance->VersionMajor; _ReadWriteBarrier(); /* * Compiler barrier only. * * A full memory barrier is not needed here, because: * * - WaitForSingleObject acts on a NotificationEvent that stays signaled. * - WaitForSingleObject is a memory barrier. */ if (0 == VersionMajor) { Result = FsRtlCancellableWaitForSingleObject(&Instance->InitEvent, 0, CancellableIrp); if (STATUS_TIMEOUT == Result || STATUS_THREAD_IS_TERMINATING == Result) Result = STATUS_CANCELLED; if (!NT_SUCCESS(Result)) goto exit; ASSERT(STATUS_SUCCESS == Result); VersionMajor = Instance->VersionMajor; } if ((UINT32)-1 == VersionMajor) { Result = STATUS_ACCESS_DENIED; goto exit; } Result = FspFsextProviderTransact( DeviceObject, FileObject, 0, &InternalRequest); if (!NT_SUCCESS(Result)) goto exit; if (0 == InternalRequest) { Result = STATUS_SUCCESS; goto exit; } ASSERT(FspFsctlTransactReservedKind != InternalRequest->Kind); FuseContextCreate(&Context, Instance, InternalRequest); ASSERT(0 != Context); Continue = FALSE; if (!FuseContextIsStatus(Context)) { InternalRequest = 0; Continue = FuseContextProcess(Context, 0, FuseRequest, OutputBufferLength); } } else { ASSERT(!FuseContextIsStatus(Context)); Continue = FuseContextProcess(Context, 0, FuseRequest, OutputBufferLength); } if (Continue) { ASSERT(!FuseContextIsStatus(Context)); FuseIoqStartProcessing(Instance->Ioq, Context); } else if (FuseContextIsStatus(Context)) { ASSERT(0 != InternalRequest); RtlZeroMemory(&InternalResponse, sizeof InternalResponse); InternalResponse.Size = sizeof InternalResponse; InternalResponse.Kind = InternalRequest->Kind; InternalResponse.Hint = InternalRequest->Hint; InternalResponse.IoStatus.Status = FuseContextToStatus(Context); Result = FspFsextProviderTransact( DeviceObject, FileObject, &InternalResponse, 0); if (!NT_SUCCESS(Result)) goto exit; } else if (0 == Context->InternalRequest) { switch (Context->InternalResponse->Hint) { case FUSE_PROTO_OPCODE_FORGET: case FUSE_PROTO_OPCODE_BATCH_FORGET: if (!IsListEmpty(&Context->Forget.ForgetList)) FuseIoqPostPending(Instance->Ioq, Context); else FuseContextDelete(Context); break; } } else { Result = FspFsextProviderTransact( DeviceObject, FileObject, Context->InternalResponse, 0); FuseContextDelete(Context); if (!NT_SUCCESS(Result)) goto exit; } *POutputBufferLength = FuseRequest->len; #if DBG if (fuse_debug & fuse_debug_dp) FuseDebugLogRequest(FuseRequest); #endif } Result = STATUS_SUCCESS; exit: if (0 != InternalRequest) FuseFreeExternal(InternalRequest); return Result; } ================================================ FILE: src/shared/km/ioq.c ================================================ /** * @file shared/km/ioq.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include NTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq); VOID FuseIoqDelete(FUSE_IOQ *Ioq); VOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context); FUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique); VOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context); VOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context); FUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseIoqCreate) #pragma alloc_text(PAGE, FuseIoqDelete) #pragma alloc_text(PAGE, FuseIoqStartProcessing) #pragma alloc_text(PAGE, FuseIoqEndProcessing) #pragma alloc_text(PAGE, FuseIoqPostPending) #pragma alloc_text(PAGE, FuseIoqPostPendingAndStop) #pragma alloc_text(PAGE, FuseIoqNextPending) #endif #define FUSE_IOQ_SIZE 1024 struct _FUSE_IOQ { FAST_MUTEX Mutex; LIST_ENTRY PendingList, ProcessList; FUSE_CONTEXT *LastContext; ULONG ProcessBucketCount; FUSE_CONTEXT *ProcessBuckets[]; }; NTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq) { PAGED_CODE(); *PIoq = 0; FUSE_IOQ *Ioq; ULONG BucketCount = (FUSE_IOQ_SIZE - sizeof *Ioq) / sizeof Ioq->ProcessBuckets[0]; Ioq = FuseAllocNonPaged(FUSE_IOQ_SIZE); if (0 == Ioq) return STATUS_INSUFFICIENT_RESOURCES; RtlZeroMemory(Ioq, FUSE_IOQ_SIZE); ExInitializeFastMutex(&Ioq->Mutex); InitializeListHead(&Ioq->PendingList); InitializeListHead(&Ioq->ProcessList); Ioq->ProcessBucketCount = BucketCount; *PIoq = Ioq; return STATUS_SUCCESS; } VOID FuseIoqDelete(FUSE_IOQ *Ioq) { PAGED_CODE(); for (PLIST_ENTRY Entry = Ioq->PendingList.Flink; &Ioq->PendingList != Entry;) { FUSE_CONTEXT *Context = CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry); Entry = Entry->Flink; FuseContextDelete(Context); } for (PLIST_ENTRY Entry = Ioq->ProcessList.Flink; &Ioq->ProcessList != Entry;) { FUSE_CONTEXT *Context = CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry); Entry = Entry->Flink; FuseContextDelete(Context); } FuseFree(Ioq); } VOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context) { PAGED_CODE(); ExAcquireFastMutex(&Ioq->Mutex); if (0 != Ioq->LastContext) { if (Context != Ioq->LastContext) { ExReleaseFastMutex(&Ioq->Mutex); ASSERT(0 != Context->FuseRequest); if (0 != Context->FuseRequest) Context->FuseRequest->len = 0; FuseContextDelete(Context); return; } else Ioq->LastContext = (PVOID)(UINT_PTR)1; } InsertTailList(&Ioq->ProcessList, &Context->ListEntry); ULONG Index = FuseHashMixPointer(Context) % Ioq->ProcessBucketCount; #if DBG for (FUSE_CONTEXT *ContextX = Ioq->ProcessBuckets[Index]; ContextX; ContextX = ContextX->DictNext) ASSERT(ContextX != Context); #endif ASSERT(0 == Context->DictNext); Context->DictNext = Ioq->ProcessBuckets[Index]; Ioq->ProcessBuckets[Index] = Context; ExReleaseFastMutex(&Ioq->Mutex); } FUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique) { PAGED_CODE(); FUSE_CONTEXT *ContextHint = (PVOID)(UINT_PTR)Unique; FUSE_CONTEXT *Context = 0; ExAcquireFastMutex(&Ioq->Mutex); ULONG Index = FuseHashMixPointer(ContextHint) % Ioq->ProcessBucketCount; for (FUSE_CONTEXT **PContext = &Ioq->ProcessBuckets[Index]; *PContext; PContext = &(*PContext)->DictNext) { if (*PContext == ContextHint) { *PContext = ContextHint->DictNext; ContextHint->DictNext = 0; Context = ContextHint; RemoveEntryList(&Context->ListEntry); break; } } ExReleaseFastMutex(&Ioq->Mutex); return Context; } VOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context) { PAGED_CODE(); ExAcquireFastMutex(&Ioq->Mutex); if (0 != Ioq->LastContext) { ExReleaseFastMutex(&Ioq->Mutex); FuseContextDelete(Context); return; } InsertTailList(&Ioq->PendingList, &Context->ListEntry); ExReleaseFastMutex(&Ioq->Mutex); } VOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context) /* * This function is used to post the last Context for processing (usually DESTROY). * It clears the Pending list, but does not touch the Process list. The reason is * that the last Context must be retrieved only after all in-flight Context's are * done and FuseIoqNextPending checks for this condition when the last Context has * been posted. */ { PAGED_CODE(); ExAcquireFastMutex(&Ioq->Mutex); if (0 != Ioq->LastContext) { ExReleaseFastMutex(&Ioq->Mutex); FuseContextDelete(Context); return; } for (PLIST_ENTRY Entry = Ioq->PendingList.Flink; &Ioq->PendingList != Entry;) { FUSE_CONTEXT *Temp = CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry); Entry = Entry->Flink; FuseContextDelete(Temp); } InitializeListHead(&Ioq->PendingList); InsertTailList(&Ioq->PendingList, &Context->ListEntry); Ioq->LastContext = Context; ExReleaseFastMutex(&Ioq->Mutex); } FUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq) { PAGED_CODE(); ExAcquireFastMutex(&Ioq->Mutex); if (0 != Ioq->LastContext && !IsListEmpty(&Ioq->ProcessList)) { ExReleaseFastMutex(&Ioq->Mutex); return 0; } PLIST_ENTRY Entry = Ioq->PendingList.Flink; FUSE_CONTEXT *Context = &Ioq->PendingList != Entry ? CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry) : 0; if (0 != Context) RemoveEntryList(&Context->ListEntry); ExReleaseFastMutex(&Ioq->Mutex); return Context; } ================================================ FILE: src/shared/km/path.c ================================================ /** * @file shared/km/path.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include VOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain); VOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FusePosixPathPrefix) #pragma alloc_text(PAGE, FusePosixPathSuffix) #endif VOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain) { PAGED_CODE(); STRING PathBuf, PrefixBuf, RemainBuf; PathBuf = *Path; if (0 == Prefix) Prefix = &PrefixBuf; if (0 == Remain) Remain = &RemainBuf; PSTR P = PathBuf.Buffer, EndP = P + PathBuf.Length / sizeof(*P); if (EndP > P && '/' == *P) { Prefix->Length = 1; Prefix->Buffer = PathBuf.Buffer; } else { while (EndP > P && '/' != *P) P++; Prefix->Length = (USHORT)((P - PathBuf.Buffer) * sizeof *P); Prefix->Buffer = PathBuf.Buffer; } while (EndP > P && '/' == *P) P++; Remain->Length = (USHORT)((EndP - P) * sizeof *P); Remain->Buffer = P; Prefix->MaximumLength = Prefix->Length; Remain->MaximumLength = Remain->Length; } VOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix) { PAGED_CODE(); STRING PathBuf, RemainBuf, SuffixBuf; PathBuf = *Path; if (0 == Remain) Remain = &RemainBuf; if (0 == Suffix) Suffix = &SuffixBuf; PSTR P = PathBuf.Buffer, EndP = P + PathBuf.Length / sizeof(*P); Remain->Length = PathBuf.Length; Remain->Buffer = PathBuf.Buffer; Suffix->Length = 0; Suffix->Buffer = PathBuf.Buffer; while (EndP > P) if ('/' == *P) { Remain->Length = (USHORT)((P - PathBuf.Buffer) * sizeof *P); if (0 == Remain->Length) Remain->Length = 1; while (EndP > P && '/' == *P) P++; Suffix->Length = (USHORT)((EndP - P) * sizeof *P); Suffix->Buffer = P; } else P++; Remain->MaximumLength = Remain->Length; Suffix->MaximumLength = Suffix->Length; } ================================================ FILE: src/shared/km/proto.c ================================================ /** * @file shared/km/proto.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include NTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance); VOID FuseProtoSendInit(FUSE_CONTEXT *Context); NTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance); VOID FuseProtoSendDestroy(FUSE_CONTEXT *Context); VOID FuseProtoSendLookup(FUSE_CONTEXT *Context); NTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY ForgetList); static VOID FuseProtoPostForget_ContextFini(FUSE_CONTEXT *Context); VOID FuseProtoFillForget(FUSE_CONTEXT *Context); VOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context); VOID FuseProtoSendStatfs(FUSE_CONTEXT *Context); VOID FuseProtoSendGetattr(FUSE_CONTEXT *Context); VOID FuseProtoSendFgetattr(FUSE_CONTEXT *Context); VOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context); VOID FuseProtoSendFutimens(FUSE_CONTEXT *Context); VOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context); VOID FuseProtoSendSetattr(FUSE_CONTEXT *Context); VOID FuseProtoSendMkdir(FUSE_CONTEXT *Context); VOID FuseProtoSendMknod(FUSE_CONTEXT *Context); VOID FuseProtoSendRmdir(FUSE_CONTEXT *Context); VOID FuseProtoSendUnlink(FUSE_CONTEXT *Context); VOID FuseProtoSendRename(FUSE_CONTEXT *Context); VOID FuseProtoSendCreate(FUSE_CONTEXT *Context); VOID FuseProtoSendOpendir(FUSE_CONTEXT *Context); VOID FuseProtoSendOpen(FUSE_CONTEXT *Context); VOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context); VOID FuseProtoSendRelease(FUSE_CONTEXT *Context); VOID FuseProtoSendReaddir(FUSE_CONTEXT *Context); VOID FuseProtoSendRead(FUSE_CONTEXT *Context); VOID FuseProtoSendWrite(FUSE_CONTEXT *Context); VOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context); VOID FuseProtoSendFsync(FUSE_CONTEXT *Context); VOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance, FUSE_PROTO_ATTR *Attr, FSP_FSCTL_FILE_INFO *FileInfo); NTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseProtoPostInit) #pragma alloc_text(PAGE, FuseProtoSendInit) #pragma alloc_text(PAGE, FuseProtoPostDestroy) #pragma alloc_text(PAGE, FuseProtoSendDestroy) #pragma alloc_text(PAGE, FuseProtoSendLookup) #pragma alloc_text(PAGE, FuseProtoPostForget) #pragma alloc_text(PAGE, FuseProtoPostForget_ContextFini) #pragma alloc_text(PAGE, FuseProtoFillForget) #pragma alloc_text(PAGE, FuseProtoFillBatchForget) #pragma alloc_text(PAGE, FuseProtoSendStatfs) #pragma alloc_text(PAGE, FuseProtoSendGetattr) #pragma alloc_text(PAGE, FuseProtoSendFgetattr) #pragma alloc_text(PAGE, FuseProtoSendFtruncate) #pragma alloc_text(PAGE, FuseProtoSendFutimens) #pragma alloc_text(PAGE, FuseProtoSendLookupChown) #pragma alloc_text(PAGE, FuseProtoSendSetattr) #pragma alloc_text(PAGE, FuseProtoSendMkdir) #pragma alloc_text(PAGE, FuseProtoSendMknod) #pragma alloc_text(PAGE, FuseProtoSendRmdir) #pragma alloc_text(PAGE, FuseProtoSendUnlink) #pragma alloc_text(PAGE, FuseProtoSendRename) #pragma alloc_text(PAGE, FuseProtoSendCreate) #pragma alloc_text(PAGE, FuseProtoSendOpendir) #pragma alloc_text(PAGE, FuseProtoSendOpen) #pragma alloc_text(PAGE, FuseProtoSendReleasedir) #pragma alloc_text(PAGE, FuseProtoSendRelease) #pragma alloc_text(PAGE, FuseProtoSendReaddir) #pragma alloc_text(PAGE, FuseProtoSendRead) #pragma alloc_text(PAGE, FuseProtoSendWrite) #pragma alloc_text(PAGE, FuseProtoSendFsyncdir) #pragma alloc_text(PAGE, FuseProtoSendFsync) #pragma alloc_text(PAGE, FuseAttrToFileInfo) #pragma alloc_text(PAGE, FuseNtStatusFromErrno) #endif #define FUSE_PROTO_SEND_BEGIN \ coro_block(Context->CoroState) \ { \ FuseContextWaitRequest(Context); #define FUSE_PROTO_SEND_END \ FuseContextWaitResponse(Context);\ Context->InternalResponse->IoStatus.Status = 0 == Context->FuseResponse->error ?\ STATUS_SUCCESS :\ FuseNtStatusFromErrno(Context->Instance->InstanceType, Context->FuseResponse->error);\ } #define FUSE_PROTO_SEND_BEGIN_(OPCODE) \ coro_block(Context->CoroState) \ { \ if (FuseInstanceGetOpcodeENOSYS(Context->Instance, FUSE_PROTO_OPCODE_ ## OPCODE))\ { \ Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_DEVICE_REQUEST;\ coro_break; \ } \ FuseContextWaitRequest(Context); #define FUSE_PROTO_SEND_END_(OPCODE) \ FuseContextWaitResponse(Context);\ Context->InternalResponse->IoStatus.Status = 0 == Context->FuseResponse->error ?\ STATUS_SUCCESS :\ FuseNtStatusFromErrno(Context->Instance->InstanceType, Context->FuseResponse->error);\ if (STATUS_INVALID_DEVICE_REQUEST == Context->InternalResponse->IoStatus.Status)\ FuseInstanceSetOpcodeENOSYS(Context->Instance, FUSE_PROTO_OPCODE_ ## OPCODE);\ } static inline VOID FuseProtoInitRequest(FUSE_CONTEXT *Context, UINT32 len, UINT32 opcode, UINT64 nodeid) { Context->FuseRequest->len = len; Context->FuseRequest->opcode = opcode; Context->FuseRequest->unique = (UINT64)(UINT_PTR)Context; Context->FuseRequest->nodeid = nodeid; Context->FuseRequest->uid = Context->OrigUid; Context->FuseRequest->gid = Context->OrigGid; Context->FuseRequest->pid = Context->OrigPid; } NTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance) { PAGED_CODE(); FUSE_CONTEXT *Context; FuseContextCreate(&Context, Instance, 0); ASSERT(0 != Context); if (FuseContextIsStatus(Context)) return FuseContextToStatus(Context); Context->InternalResponse->Hint = FUSE_PROTO_OPCODE_INIT; FuseIoqPostPending(Instance->Ioq, Context); return STATUS_SUCCESS; } VOID FuseProtoSendInit(FUSE_CONTEXT *Context) /* * Send INIT message. */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(init), FUSE_PROTO_OPCODE_INIT, 0); Context->FuseRequest->req.init.major = FUSE_PROTO_VERSION; Context->FuseRequest->req.init.minor = FUSE_PROTO_MINOR_VERSION; Context->FuseRequest->req.init.max_readahead = 0; /* !!!: REVISIT */ Context->FuseRequest->req.init.flags = 0; /* !!!: REVISIT */ FUSE_PROTO_SEND_END } NTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance) { PAGED_CODE(); FUSE_CONTEXT *Context; FuseContextCreate(&Context, Instance, 0); ASSERT(0 != Context); if (FuseContextIsStatus(Context)) return FuseContextToStatus(Context); Context->InternalResponse->Hint = FUSE_PROTO_OPCODE_DESTROY; FuseIoqPostPendingAndStop(Instance->Ioq, Context); return STATUS_SUCCESS; } VOID FuseProtoSendDestroy(FUSE_CONTEXT *Context) /* * Send DESTROY message. */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_HEADER_SIZE, FUSE_PROTO_OPCODE_DESTROY, 0); if (0 != Context->Instance->ProtoSendDestroyHandler) Context->Instance->ProtoSendDestroyHandler(Context->Instance->ProtoSendDestroyData); FUSE_PROTO_SEND_END } VOID FuseProtoSendLookup(FUSE_CONTEXT *Context) /* * Send LOOKUP message. * * Context->Lookup.Ino * parent directory inode number * Context->Lookup.Name * name to lookup */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(lookup) + Context->Lookup.Name.Length + 1), FUSE_PROTO_OPCODE_LOOKUP, Context->Lookup.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); RtlCopyMemory(Context->FuseRequest->req.lookup.name, Context->Lookup.Name.Buffer, Context->Lookup.Name.Length); Context->FuseRequest->req.lookup.name[Context->Lookup.Name.Length] = '\0'; FUSE_PROTO_SEND_END } NTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY ForgetList) { PAGED_CODE(); FUSE_CONTEXT *Context; FuseContextCreate(&Context, Instance, 0); ASSERT(0 != Context); if (FuseContextIsStatus(Context)) return FuseContextToStatus(Context); Context->Fini = FuseProtoPostForget_ContextFini; Context->InternalResponse->Hint = FUSE_PROTO_OPCODE_FORGET; ASSERT(ForgetList != ForgetList->Flink); Context->Forget.ForgetList = *ForgetList; /* fixup first/last list entry */ Context->Forget.ForgetList.Flink->Blink = &Context->Forget.ForgetList; Context->Forget.ForgetList.Blink->Flink = &Context->Forget.ForgetList; FuseIoqPostPending(Instance->Ioq, Context); return STATUS_SUCCESS; } static VOID FuseProtoPostForget_ContextFini(FUSE_CONTEXT *Context) { PAGED_CODE(); FuseCacheDeleteForgotten(&Context->Forget.ForgetList); } VOID FuseProtoFillForget(FUSE_CONTEXT *Context) /* * Fill FORGET message. This message is used to forget a single inode number. * * Context->Forget.ForgetList * list that contains items to forget */ { PAGED_CODE(); FUSE_PROTO_FORGET_ONE ForgetOne; BOOLEAN Ok; Ok = FuseCacheForgetOne(&Context->Forget.ForgetList, &ForgetOne); ASSERT(Ok); FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(forget), FUSE_PROTO_OPCODE_FORGET, ForgetOne.nodeid); Context->FuseRequest->req.forget.nlookup = ForgetOne.nlookup; } VOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context) /* * Fill BATCH_FORGET message. This message is used to forget multiple inode numbers. * * Context->Forget.ForgetList * list that contains items to forget */ { PAGED_CODE(); FUSE_PROTO_FORGET_ONE *StartP, *EndP, *P; StartP = (PVOID)((PUINT8)Context->FuseRequest + FUSE_PROTO_REQ_SIZE(batch_forget)); EndP = (PVOID)((PUINT8)StartP + (FUSE_PROTO_REQ_SIZEMIN - FUSE_PROTO_REQ_SIZE(batch_forget))); for (P = StartP; DEBUGTEST(90) && EndP > P && FuseCacheForgetOne(&Context->Forget.ForgetList, P); P++) ; FuseProtoInitRequest(Context, (UINT32)((PUINT8)P - (PUINT8)Context->FuseRequest), FUSE_PROTO_OPCODE_BATCH_FORGET, 0); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); Context->FuseRequest->req.batch_forget.count = (ULONG)(P - StartP); } VOID FuseProtoSendStatfs(FUSE_CONTEXT *Context) /* * Send STATFS message. */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_HEADER_SIZE, FUSE_PROTO_OPCODE_STATFS, 0); FUSE_PROTO_SEND_END } VOID FuseProtoSendGetattr(FUSE_CONTEXT *Context) /* * Send GETATTR message. * * Context->Lookup.Ino * inode number to get attributes for */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(getattr), FUSE_PROTO_OPCODE_GETATTR, Context->Lookup.Ino); FUSE_PROTO_SEND_END } VOID FuseProtoSendFgetattr(FUSE_CONTEXT *Context) /* * Send GETATTR message given a file. * * Context->File->IsDirectory * true if file is a directory * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file; use only when file is not a directory */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN if (Context->File->IsDirectory) { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(getattr), FUSE_PROTO_OPCODE_GETATTR, Context->File->Ino); } else { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(getattr), FUSE_PROTO_OPCODE_GETATTR, Context->File->Ino); Context->FuseRequest->req.getattr.getattr_flags = FUSE_PROTO_GETATTR_FH; Context->FuseRequest->req.getattr.fh = Context->File->Fh; } FUSE_PROTO_SEND_END } VOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context) /* * Send SETATTR message for truncate. * * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file * Context->Setattr.Attr.size * new size of file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); Context->FuseRequest->req.setattr.valid = FUSE_PROTO_SETATTR_FH | FUSE_PROTO_SETATTR_SIZE; Context->FuseRequest->req.setattr.fh = Context->File->Fh; Context->FuseRequest->req.setattr.size = Context->Setattr.Attr.size; FUSE_PROTO_SEND_END } VOID FuseProtoSendFutimens(FUSE_CONTEXT *Context) /* * Send SETATTR message for utimens. * * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file * Context->Setattr.Attr.{atime,atimensec} * new access time of file * Context->Setattr.Attr.{mtime,mtimensec} * new modification time of file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN if (Context->File->IsDirectory) { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); } else { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); Context->FuseRequest->req.setattr.valid = FUSE_PROTO_SETATTR_FH; Context->FuseRequest->req.setattr.fh = Context->File->Fh; } if (FUSE_PROTO_UTIME_OMIT != Context->Setattr.Attr.atimensec) { Context->FuseRequest->req.setattr.valid |= FUSE_PROTO_SETATTR_ATIME; Context->FuseRequest->req.setattr.atime = Context->Setattr.Attr.atime; Context->FuseRequest->req.setattr.atimensec = Context->Setattr.Attr.atimensec; } if (FUSE_PROTO_UTIME_OMIT != Context->Setattr.Attr.mtimensec) { Context->FuseRequest->req.setattr.valid |= FUSE_PROTO_SETATTR_MTIME; Context->FuseRequest->req.setattr.mtime = Context->Setattr.Attr.mtime; Context->FuseRequest->req.setattr.mtimensec = Context->Setattr.Attr.mtimensec; } FUSE_PROTO_SEND_END } VOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context) /* * Send SETATTR message for chown. * * Context->File->IsDirectory * true if file is a directory * Context->File->Ino * inode number of related file; use when file is a directory * Context->File->Fh * handle of related file; use when file is not a directory * Context->Lookup.Attr.uid * uid of new file * Context->Lookup.Attr.gid * gid of new file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN if (Context->File->IsDirectory) { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); Context->FuseRequest->req.setattr.valid = FUSE_PROTO_SETATTR_UID | FUSE_PROTO_SETATTR_GID; Context->FuseRequest->req.setattr.uid = Context->Lookup.Attr.uid; Context->FuseRequest->req.setattr.gid = Context->Lookup.Attr.gid; } else { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); Context->FuseRequest->req.setattr.valid = FUSE_PROTO_SETATTR_FH | FUSE_PROTO_SETATTR_UID | FUSE_PROTO_SETATTR_GID; Context->FuseRequest->req.setattr.fh = Context->File->Fh; Context->FuseRequest->req.setattr.uid = Context->Lookup.Attr.uid; Context->FuseRequest->req.setattr.gid = Context->Lookup.Attr.gid; } FUSE_PROTO_SEND_END } VOID FuseProtoSendSetattr(FUSE_CONTEXT *Context) /* * Send SETATTR message. * * Context->File->IsDirectory * true if file is a directory * Context->File->Ino * inode number of related file; use when file is a directory * Context->File->Fh * handle of related file; use when file is not a directory * Context->Setattr.AttrValid * valid attr fields * Context->Setattr.Attr * new attr of file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN if (Context->File->IsDirectory) { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); Context->FuseRequest->req.setattr.size = Context->Setattr.Attr.size; Context->FuseRequest->req.setattr.atime = Context->Setattr.Attr.atime; Context->FuseRequest->req.setattr.mtime = Context->Setattr.Attr.mtime; Context->FuseRequest->req.setattr.ctime = Context->Setattr.Attr.ctime; Context->FuseRequest->req.setattr.atimensec = Context->Setattr.Attr.atimensec; Context->FuseRequest->req.setattr.mtimensec = Context->Setattr.Attr.mtimensec; Context->FuseRequest->req.setattr.ctimensec = Context->Setattr.Attr.ctimensec; Context->FuseRequest->req.setattr.mode = Context->Setattr.Attr.mode; Context->FuseRequest->req.setattr.uid = Context->Setattr.Attr.uid; Context->FuseRequest->req.setattr.gid = Context->Setattr.Attr.gid; Context->FuseRequest->req.setattr.valid = Context->Setattr.AttrValid; } else { FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino); Context->FuseRequest->req.setattr.size = Context->Setattr.Attr.size; Context->FuseRequest->req.setattr.atime = Context->Setattr.Attr.atime; Context->FuseRequest->req.setattr.mtime = Context->Setattr.Attr.mtime; Context->FuseRequest->req.setattr.ctime = Context->Setattr.Attr.ctime; Context->FuseRequest->req.setattr.atimensec = Context->Setattr.Attr.atimensec; Context->FuseRequest->req.setattr.mtimensec = Context->Setattr.Attr.mtimensec; Context->FuseRequest->req.setattr.ctimensec = Context->Setattr.Attr.ctimensec; Context->FuseRequest->req.setattr.mode = Context->Setattr.Attr.mode; Context->FuseRequest->req.setattr.uid = Context->Setattr.Attr.uid; Context->FuseRequest->req.setattr.gid = Context->Setattr.Attr.gid; Context->FuseRequest->req.setattr.fh = Context->File->Fh; Context->FuseRequest->req.setattr.valid = Context->Setattr.AttrValid | FUSE_PROTO_SETATTR_FH; } FUSE_PROTO_SEND_END } VOID FuseProtoSendMkdir(FUSE_CONTEXT *Context) /* * Send MKDIR message. * * Context->Lookup.Ino * parent directory inode number * Context->Lookup.Name * name of new directory * Context->Lookup.Attr.mode * mode of new directory */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(mkdir) + Context->Lookup.Name.Length + 1), FUSE_PROTO_OPCODE_MKDIR, Context->Lookup.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); Context->FuseRequest->req.mkdir.mode = Context->Lookup.Attr.mode; Context->FuseRequest->req.mkdir.umask = 0; /* !!!: REVISIT */ RtlCopyMemory(Context->FuseRequest->req.mkdir.name, Context->Lookup.Name.Buffer, Context->Lookup.Name.Length); Context->FuseRequest->req.mkdir.name[Context->Lookup.Name.Length] = '\0'; FUSE_PROTO_SEND_END } VOID FuseProtoSendMknod(FUSE_CONTEXT *Context) /* * Send MKNOD message. * * Context->Lookup.Ino * parent directory inode number * Context->Lookup.Name * name of new file * Context->Lookup.Attr.mode * mode of new file * Context->Lookup.Attr.rdev * device number of new file (when file is a device) */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(mknod) + Context->Lookup.Name.Length + 1), FUSE_PROTO_OPCODE_MKNOD, Context->Lookup.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); Context->FuseRequest->req.mknod.mode = Context->Lookup.Attr.mode; Context->FuseRequest->req.mknod.rdev = Context->Lookup.Attr.rdev; Context->FuseRequest->req.mknod.umask = 0; /* !!!: REVISIT */ RtlCopyMemory(Context->FuseRequest->req.mknod.name, Context->Lookup.Name.Buffer, Context->Lookup.Name.Length); Context->FuseRequest->req.mknod.name[Context->Lookup.Name.Length] = '\0'; FUSE_PROTO_SEND_END } VOID FuseProtoSendRmdir(FUSE_CONTEXT *Context) /* * Send RMDIR message. * * Context->Lookup.Ino * parent directory inode number * Context->Lookup.Name * name of directory */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(rmdir) + Context->Lookup.Name.Length + 1), FUSE_PROTO_OPCODE_RMDIR, Context->Lookup.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); RtlCopyMemory(Context->FuseRequest->req.rmdir.name, Context->Lookup.Name.Buffer, Context->Lookup.Name.Length); Context->FuseRequest->req.rmdir.name[Context->Lookup.Name.Length] = '\0'; FUSE_PROTO_SEND_END } VOID FuseProtoSendUnlink(FUSE_CONTEXT *Context) /* * Send UNLINK message. * * Context->Lookup.Ino * parent directory inode number * Context->Lookup.Name * name of file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(unlink) + Context->Lookup.Name.Length + 1), FUSE_PROTO_OPCODE_UNLINK, Context->Lookup.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); RtlCopyMemory(Context->FuseRequest->req.unlink.name, Context->Lookup.Name.Buffer, Context->Lookup.Name.Length); Context->FuseRequest->req.unlink.name[Context->Lookup.Name.Length] = '\0'; FUSE_PROTO_SEND_END } VOID FuseProtoSendRename(FUSE_CONTEXT *Context) /* * Send RENAME message. * * Context->LookupPath.Ino * old parent directory inode number * Context->LookupPath.Name * old name of file * Context->LookupPath.Ino2 * new parent directory inode number * Context->LookupPath.Name2 * new name of file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(rename) + Context->LookupPath.Name.Length + 1 + Context->LookupPath.Name2.Length + 1), FUSE_PROTO_OPCODE_RENAME, Context->LookupPath.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); Context->FuseRequest->req.rename.newdir = Context->LookupPath.Ino2; RtlCopyMemory(Context->FuseRequest->req.rename.name, Context->LookupPath.Name.Buffer, Context->LookupPath.Name.Length); Context->FuseRequest->req.rename.name[Context->LookupPath.Name.Length] = '\0'; RtlCopyMemory(Context->FuseRequest->req.rename.name + Context->LookupPath.Name.Length + 1, Context->LookupPath.Name2.Buffer, Context->LookupPath.Name2.Length); (Context->FuseRequest->req.rename.name + Context->LookupPath.Name.Length + 1) [Context->LookupPath.Name2.Length] = '\0'; FUSE_PROTO_SEND_END } VOID FuseProtoSendCreate(FUSE_CONTEXT *Context) /* * Send CREATE message. * * Context->Lookup.Ino * parent directory inode number * Context->Lookup.Name * name of new file * Context->Lookup.Attr.mode * mode of new file * Context->File->OpenFlags * open (O_*) flags */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN_(CREATE) FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(create) + Context->Lookup.Name.Length + 1), FUSE_PROTO_OPCODE_CREATE, Context->Lookup.Ino); ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len); Context->FuseRequest->req.create.flags = Context->File->OpenFlags; Context->FuseRequest->req.create.mode = Context->Lookup.Attr.mode; Context->FuseRequest->req.create.umask = 0; /* !!!: REVISIT */ RtlCopyMemory(Context->FuseRequest->req.create.name, Context->Lookup.Name.Buffer, Context->Lookup.Name.Length); Context->FuseRequest->req.create.name[Context->Lookup.Name.Length] = '\0'; FUSE_PROTO_SEND_END_(CREATE) } VOID FuseProtoSendOpendir(FUSE_CONTEXT *Context) /* * Send OPENDIR message. * * Context->Lookup.Ino * inode number of directory to open */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(open), FUSE_PROTO_OPCODE_OPENDIR, Context->Lookup.Ino); Context->FuseRequest->req.open.flags = Context->File->OpenFlags; FUSE_PROTO_SEND_END } VOID FuseProtoSendOpen(FUSE_CONTEXT *Context) /* * Send OPEN message. * * Context->Lookup.Ino * inode number of file to open */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(open), FUSE_PROTO_OPCODE_OPEN, Context->Lookup.Ino); Context->FuseRequest->req.open.flags = Context->File->OpenFlags; FUSE_PROTO_SEND_END } VOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context) /* * Send RELEASEDIR message. * * Context->File->Ino * inode number of related directory * Context->File->Fh * handle of related directory * Context->File->OpenFlags * open (O_*) flags */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(release), FUSE_PROTO_OPCODE_RELEASEDIR, Context->File->Ino); Context->FuseRequest->req.release.fh = Context->File->Fh; Context->FuseRequest->req.release.flags = Context->File->OpenFlags; FUSE_PROTO_SEND_END } VOID FuseProtoSendRelease(FUSE_CONTEXT *Context) /* * Send RELEASE message. * * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file * Context->File->OpenFlags * open (O_*) flags */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(release), FUSE_PROTO_OPCODE_RELEASE, Context->File->Ino); Context->FuseRequest->req.release.fh = Context->File->Fh; Context->FuseRequest->req.release.flags = Context->File->OpenFlags; Context->FuseRequest->req.release.release_flags = 0;/* !!!: REVISIT */ Context->FuseRequest->req.release.lock_owner = 0; /* !!!: REVISIT */ FUSE_PROTO_SEND_END } VOID FuseProtoSendReaddir(FUSE_CONTEXT *Context) /* * Send READDIR message. * * Context->File->Ino * inode number of related directory * Context->File->Fh * handle of related directory * Context->QueryDirectory.NextOffset * offset of next directory entry or 0 * Context->QueryDirectory.Length * readdir buffer length */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(read), FUSE_PROTO_OPCODE_READDIR, Context->File->Ino); Context->FuseRequest->req.read.fh = Context->File->Fh; Context->FuseRequest->req.read.offset = Context->QueryDirectory.NextOffset; Context->FuseRequest->req.read.size = Context->QueryDirectory.Length; Context->FuseRequest->req.read.read_flags = 0; /* !!!: REVISIT */ Context->FuseRequest->req.read.lock_owner = 0; /* !!!: REVISIT */ Context->FuseRequest->req.read.flags = Context->File->OpenFlags; FUSE_PROTO_SEND_END } VOID FuseProtoSendRead(FUSE_CONTEXT *Context) /* * Send READ message. * * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file * Context->Read.Offset * offset to read * Context->Read.Length * read buffer length */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(read), FUSE_PROTO_OPCODE_READ, Context->File->Ino); Context->FuseRequest->req.read.fh = Context->File->Fh; Context->FuseRequest->req.read.offset = Context->Read.StartOffset + Context->Read.Offset; Context->FuseRequest->req.read.size = Context->Read.Length; Context->FuseRequest->req.read.read_flags = 0; /* !!!: REVISIT */ Context->FuseRequest->req.read.lock_owner = 0; /* !!!: REVISIT */ Context->FuseRequest->req.read.flags = Context->File->OpenFlags; FUSE_PROTO_SEND_END } VOID FuseProtoSendWrite(FUSE_CONTEXT *Context) /* * Send WRITE message. * * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file * Context->Write.Offset * offset to write * Context->Write.Length * write buffer length */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(write) + Context->Write.Length, FUSE_PROTO_OPCODE_WRITE, Context->File->Ino); Context->FuseRequest->req.write.fh = Context->File->Fh; Context->FuseRequest->req.write.offset = Context->Write.StartOffset + Context->Write.Offset; Context->FuseRequest->req.write.size = Context->Write.Length; Context->FuseRequest->req.write.write_flags = 0; /* !!!: REVISIT */ Context->FuseRequest->req.write.lock_owner = 0; /* !!!: REVISIT */ Context->FuseRequest->req.write.flags = Context->File->OpenFlags; FUSE_PROTO_SEND_END } VOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context) /* * Send FSYNCDIR message. * * Context->File->Ino * inode number of related directory * Context->File->Fh * handle of related directory */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN_(FSYNCDIR) FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(fsync), FUSE_PROTO_OPCODE_FSYNCDIR, Context->File->Ino); Context->FuseRequest->req.fsync.fh = Context->File->Fh; FUSE_PROTO_SEND_END_(FSYNCDIR) } VOID FuseProtoSendFsync(FUSE_CONTEXT *Context) /* * Send FSYNC message. * * Context->File->Ino * inode number of related file * Context->File->Fh * handle of related file */ { PAGED_CODE(); FUSE_PROTO_SEND_BEGIN_(FSYNC) FuseProtoInitRequest(Context, FUSE_PROTO_REQ_SIZE(fsync), FUSE_PROTO_OPCODE_FSYNC, Context->File->Ino); Context->FuseRequest->req.fsync.fh = Context->File->Fh; FUSE_PROTO_SEND_END_(FSYNC) } VOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance, FUSE_PROTO_ATTR *Attr, FSP_FSCTL_FILE_INFO *FileInfo) { PAGED_CODE(); UINT64 AllocationUnit; AllocationUnit = (UINT64)Instance->VolumeParams->SectorSize * (UINT64)Instance->VolumeParams->SectorsPerAllocationUnit; switch (Attr->mode & 0170000) { case 0040000: /* S_IFDIR */ FileInfo->FileAttributes = FILE_ATTRIBUTE_DIRECTORY; FileInfo->ReparseTag = 0; break; case 0010000: /* S_IFIFO */ case 0020000: /* S_IFCHR */ case 0060000: /* S_IFBLK */ case 0140000: /* S_IFSOCK */ FileInfo->FileAttributes = FILE_ATTRIBUTE_REPARSE_POINT; FileInfo->ReparseTag = IO_REPARSE_TAG_NFS; break; case 0120000: /* S_IFLNK */ /* !!!: if target is directory FILE_ATTRIBUTE_DIRECTORY must also be set! */ FileInfo->FileAttributes = FILE_ATTRIBUTE_REPARSE_POINT; FileInfo->ReparseTag = IO_REPARSE_TAG_SYMLINK; break; default: FileInfo->FileAttributes = 0; FileInfo->ReparseTag = 0; break; } FileInfo->FileSize = Attr->size; FileInfo->AllocationSize = (FileInfo->FileSize + AllocationUnit - 1) / AllocationUnit * AllocationUnit; FuseUnixTimeToFileTime(Attr->atime, Attr->atimensec, &FileInfo->LastAccessTime); FuseUnixTimeToFileTime(Attr->mtime, Attr->mtimensec, &FileInfo->LastWriteTime); FuseUnixTimeToFileTime(Attr->ctime, Attr->ctimensec, &FileInfo->ChangeTime); FileInfo->CreationTime = FileInfo->ChangeTime; FileInfo->IndexNumber = Attr->ino; FileInfo->HardLinks = 0; FileInfo->EaSize = 0; } NTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno) { PAGED_CODE(); if (0 > Errno) Errno = -Errno; switch (InstanceType) { default: case FuseInstanceWindows: switch (Errno) { #undef FUSE_ERRNO #define FUSE_ERRNO 87 #include "errno.i" default: return STATUS_ACCESS_DENIED; } case FuseInstanceCygwin: switch (Errno) { #undef FUSE_ERRNO #define FUSE_ERRNO 67 #include "errno.i" default: return STATUS_ACCESS_DENIED; } case FuseInstanceLinux: switch (Errno) { #undef FUSE_ERRNO #define FUSE_ERRNO 76 #include "errno.i" default: return STATUS_ACCESS_DENIED; } } } ================================================ FILE: src/shared/km/proto.h ================================================ /** * @file shared/km/proto.h * * This file is derived from libfuse/include/fuse_kernel.h: * FUSE: Filesystem in Userspace * Copyright (C) 2001-2007 Miklos Szeredi * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef SHARED_KM_PROTO_H_INCLUDED #define SHARED_KM_PROTO_H_INCLUDED #define FUSE_PROTO_VERSION 7 #define FUSE_PROTO_MINOR_VERSION 29 #define FUSE_PROTO_ROOT_INO 1 #define FUSE_PROTO_UNKNOWN_INO 0xffffffff enum FUSE_PROTO_OPCODE { FUSE_PROTO_OPCODE_LOOKUP = 1, FUSE_PROTO_OPCODE_FORGET = 2, FUSE_PROTO_OPCODE_GETATTR = 3, FUSE_PROTO_OPCODE_SETATTR = 4, FUSE_PROTO_OPCODE_READLINK = 5, FUSE_PROTO_OPCODE_SYMLINK = 6, FUSE_PROTO_OPCODE_MKNOD = 8, FUSE_PROTO_OPCODE_MKDIR = 9, FUSE_PROTO_OPCODE_UNLINK = 10, FUSE_PROTO_OPCODE_RMDIR = 11, FUSE_PROTO_OPCODE_RENAME = 12, FUSE_PROTO_OPCODE_LINK = 13, FUSE_PROTO_OPCODE_OPEN = 14, FUSE_PROTO_OPCODE_READ = 15, FUSE_PROTO_OPCODE_WRITE = 16, FUSE_PROTO_OPCODE_STATFS = 17, FUSE_PROTO_OPCODE_RELEASE = 18, FUSE_PROTO_OPCODE_FSYNC = 20, FUSE_PROTO_OPCODE_SETXATTR = 21, FUSE_PROTO_OPCODE_GETXATTR = 22, FUSE_PROTO_OPCODE_LISTXATTR = 23, FUSE_PROTO_OPCODE_REMOVEXATTR = 24, FUSE_PROTO_OPCODE_FLUSH = 25, FUSE_PROTO_OPCODE_INIT = 26, FUSE_PROTO_OPCODE_OPENDIR = 27, FUSE_PROTO_OPCODE_READDIR = 28, FUSE_PROTO_OPCODE_RELEASEDIR = 29, FUSE_PROTO_OPCODE_FSYNCDIR = 30, FUSE_PROTO_OPCODE_GETLK = 31, FUSE_PROTO_OPCODE_SETLK = 32, FUSE_PROTO_OPCODE_SETLKW = 33, FUSE_PROTO_OPCODE_ACCESS = 34, FUSE_PROTO_OPCODE_CREATE = 35, FUSE_PROTO_OPCODE_INTERRUPT = 36, FUSE_PROTO_OPCODE_BMAP = 37, FUSE_PROTO_OPCODE_DESTROY = 38, FUSE_PROTO_OPCODE_IOCTL = 39, FUSE_PROTO_OPCODE_POLL = 40, FUSE_PROTO_OPCODE_NOTIFY_REPLY = 41, FUSE_PROTO_OPCODE_BATCH_FORGET = 42, FUSE_PROTO_OPCODE_FALLOCATE = 43, FUSE_PROTO_OPCODE_READDIRPLUS = 44, FUSE_PROTO_OPCODE_RENAME2 = 45, FUSE_PROTO_OPCODE_LSEEK = 46, FUSE_PROTO_OPCODE_COPY_FILE_RANGE = 47, }; enum FUSE_PROTO_NOTIFY_CODE { FUSE_PROTO_NOTIFY_POLL = 1, FUSE_PROTO_NOTIFY_INVAL_INODE = 2, FUSE_PROTO_NOTIFY_INVAL_ENTRY = 3, FUSE_PROTO_NOTIFY_STORE = 4, FUSE_PROTO_NOTIFY_RETRIEVE = 5, FUSE_PROTO_NOTIFY_DELETE = 6, FUSE_PROTO_NOTIFY_CODE_MAX, }; enum { FUSE_PROTO_SETATTR_MODE = (1 << 0), FUSE_PROTO_SETATTR_UID = (1 << 1), FUSE_PROTO_SETATTR_GID = (1 << 2), FUSE_PROTO_SETATTR_SIZE = (1 << 3), FUSE_PROTO_SETATTR_ATIME = (1 << 4), FUSE_PROTO_SETATTR_MTIME = (1 << 5), FUSE_PROTO_SETATTR_FH = (1 << 6), FUSE_PROTO_SETATTR_ATIME_NOW = (1 << 7), FUSE_PROTO_SETATTR_MTIME_NOW = (1 << 8), FUSE_PROTO_SETATTR_LOCKOWNER = (1 << 9), FUSE_PROTO_SETATTR_CTIME = (1 << 10), FUSE_PROTO_OPEN_DIRECT_IO = (1 << 0), FUSE_PROTO_OPEN_KEEP_CACHE = (1 << 1), FUSE_PROTO_OPEN_NONSEEKABLE = (1 << 2), FUSE_PROTO_OPEN_CACHE_DIR = (1 << 3), FUSE_PROTO_GETATTR_FH = (1 << 0), FUSE_PROTO_INIT_ASYNC_READ = (1 << 0), FUSE_PROTO_INIT_POSIX_LOCKS = (1 << 1), FUSE_PROTO_INIT_FILE_OPS = (1 << 2), FUSE_PROTO_INIT_ATOMIC_O_TRUNC = (1 << 3), FUSE_PROTO_INIT_EXPORT_SUPPORT = (1 << 4), FUSE_PROTO_INIT_BIG_WRITES = (1 << 5), FUSE_PROTO_INIT_DONT_MASK = (1 << 6), FUSE_PROTO_INIT_SPLICE_WRITE = (1 << 7), FUSE_PROTO_INIT_SPLICE_MOVE = (1 << 8), FUSE_PROTO_INIT_SPLICE_READ = (1 << 9), FUSE_PROTO_INIT_FLOCK_LOCKS = (1 << 10), FUSE_PROTO_INIT_HAS_IOCTL_DIR = (1 << 11), FUSE_PROTO_INIT_AUTO_INVAL_DATA = (1 << 12), FUSE_PROTO_INIT_DO_READDIRPLUS = (1 << 13), FUSE_PROTO_INIT_READDIRPLUS_AUTO = (1 << 14), FUSE_PROTO_INIT_ASYNC_DIO = (1 << 15), FUSE_PROTO_INIT_WRITEBACK_CACHE = (1 << 16), FUSE_PROTO_INIT_NO_OPEN_SUPPORT = (1 << 17), FUSE_PROTO_INIT_PARALLEL_DIROPS = (1 << 18), FUSE_PROTO_INIT_HANDLE_KILLPRIV = (1 << 19), FUSE_PROTO_INIT_POSIX_ACL = (1 << 20), FUSE_PROTO_INIT_ABORT_ERROR = (1 << 21), FUSE_PROTO_INIT_MAX_PAGES = (1 << 22), FUSE_PROTO_INIT_CACHE_SYMLINKS = (1 << 23), FUSE_PROTO_INIT_NO_OPENDIR_SUPPORT = (1 << 24), FUSE_PROTO_IOCTL_COMPAT = (1 << 0), FUSE_PROTO_IOCTL_UNRESTRICTED = (1 << 1), FUSE_PROTO_IOCTL_RETRY = (1 << 2), FUSE_PROTO_IOCTL_32BIT = (1 << 3), FUSE_PROTO_IOCTL_DIR = (1 << 4), FUSE_PROTO_LK_FLOCK = (1 << 0), FUSE_PROTO_POLL_SCHEDULE_NOTIFY = (1 << 0), FUSE_PROTO_READ_LOCKOWNER = (1 << 1), FUSE_PROTO_RELEASE_FLUSH = (1 << 0), FUSE_PROTO_RELEASE_FLOCK_UNLOCK = (1 << 1), FUSE_PROTO_WRITE_CACHE = (1 << 0), FUSE_PROTO_WRITE_LOCKOWNER = (1 << 1), }; enum { FUSE_PROTO_UTIME_NOW = ((1 << 30) - 1), FUSE_PROTO_UTIME_OMIT = ((1 << 30) - 2), }; typedef struct { UINT64 blocks; UINT64 bfree; UINT64 bavail; UINT64 files; UINT64 ffree; UINT32 bsize; UINT32 namelen; UINT32 frsize; UINT32 padding; UINT32 spare[6]; } FUSE_PROTO_STATFS; typedef struct { UINT64 ino; UINT64 size; UINT64 blocks; UINT64 atime; UINT64 mtime; UINT64 ctime; UINT32 atimensec; UINT32 mtimensec; UINT32 ctimensec; UINT32 mode; UINT32 nlink; UINT32 uid; UINT32 gid; UINT32 rdev; UINT32 blksize; UINT32 padding; } FUSE_PROTO_ATTR; typedef struct { UINT64 nodeid; UINT64 generation; UINT64 entry_valid; UINT64 attr_valid; UINT32 entry_valid_nsec; UINT32 attr_valid_nsec; FUSE_PROTO_ATTR attr; } FUSE_PROTO_ENTRY; typedef struct { UINT64 ino; UINT64 off; UINT32 namelen; UINT32 type; CHAR name[]; } FUSE_PROTO_DIRENT; typedef struct { FUSE_PROTO_ENTRY entry; FUSE_PROTO_DIRENT dirent; } FUSE_PROTO_DIRENTPLUS; typedef struct { UINT64 start; UINT64 end; UINT32 type; UINT32 pid; } FUSE_PROTO_FILE_LOCK; typedef struct { UINT64 base; UINT64 len; } FUSE_PROTO_IOCTL_IOVEC; typedef struct { UINT64 nodeid; UINT64 nlookup; } FUSE_PROTO_FORGET_ONE; typedef struct { UINT32 len; UINT32 opcode; UINT64 unique; UINT64 nodeid; UINT32 uid; UINT32 gid; UINT32 pid; UINT32 padding; union { struct { /* LOOKUP */ CHAR name[]; } lookup; struct { /* FORGET */ UINT64 nlookup; } forget; struct { /* GETATTR */ UINT32 getattr_flags; UINT32 dummy; UINT64 fh; } getattr; struct { /* SETATTR */ UINT32 valid; UINT32 padding; UINT64 fh; UINT64 size; UINT64 lock_owner; UINT64 atime; UINT64 mtime; UINT64 ctime; UINT32 atimensec; UINT32 mtimensec; UINT32 ctimensec; UINT32 mode; UINT32 unused4; UINT32 uid; UINT32 gid; UINT32 unused5; } setattr; struct { /* SYMLINK */ CHAR name[]; /* 2 names */ } symlink; struct { /* MKNOD */ UINT32 mode; UINT32 rdev; UINT32 umask; UINT32 padding; CHAR name[]; } mknod; struct { /* MKDIR */ UINT32 mode; UINT32 umask; CHAR name[]; } mkdir; struct { /* UNLINK */ CHAR name[]; } unlink; struct { /* RMDIR */ CHAR name[]; } rmdir; struct { /* RENAME */ UINT64 newdir; CHAR name[]; /* 2 names */ } rename; struct { /* LINK */ UINT64 oldnodeid; CHAR name[]; } link; struct { /* OPEN, OPENDIR */ UINT32 flags; UINT32 unused; } open; struct { /* READ, READDIR, READDIRPLUS */ UINT64 fh; UINT64 offset; UINT32 size; UINT32 read_flags; UINT64 lock_owner; UINT32 flags; UINT32 padding; } read; struct { /* WRITE */ UINT64 fh; UINT64 offset; UINT32 size; UINT32 write_flags; UINT64 lock_owner; UINT32 flags; UINT32 padding; } write; struct { /* RELEASE, RELEASEDIR */ UINT64 fh; UINT32 flags; UINT32 release_flags; UINT64 lock_owner; } release; struct { /* FSYNC, FSYNCDIR */ UINT64 fh; UINT32 fsync_flags; UINT32 padding; } fsync; struct { /* SETXATTR */ UINT32 size; UINT32 flags; CHAR name[]; } setxattr; struct { /* GETXATTR */ UINT32 size; UINT32 padding; CHAR name[]; } getxattr; struct { /* LISTXATTR */ UINT32 size; UINT32 padding; } listxattr; struct { /* REMOVEXATTR */ CHAR name[]; } removexattr; struct { /* FLUSH */ UINT64 fh; UINT32 unused; UINT32 padding; UINT64 lock_owner; } flush; struct { /* INIT */ UINT32 major; UINT32 minor; UINT32 max_readahead; UINT32 flags; } init; struct { /* GETLK, SETLK, SETLKW */ UINT64 fh; UINT64 owner; FUSE_PROTO_FILE_LOCK lk; UINT32 lk_flags; UINT32 padding; } lk; struct { /* ACCESS */ UINT32 mask; UINT32 padding; } access; struct { /* CREATE */ UINT32 flags; UINT32 mode; UINT32 umask; UINT32 padding; CHAR name[]; } create; struct { /* INTERRUPT */ UINT64 unique; } interrupt; struct { /* BMAP */ UINT64 block; UINT32 blocksize; UINT32 padding; } bmap; struct { /* IOCTL */ UINT64 fh; UINT32 flags; UINT32 cmd; UINT64 arg; UINT32 in_size; UINT32 out_size; } ioctl; struct { /* POLL */ UINT64 fh; UINT64 kh; UINT32 flags; UINT32 events; } poll; struct { /* NOTIFY_REPLY */ UINT64 dummy1; UINT64 offset; UINT32 size; UINT32 dummy2; UINT64 dummy3; UINT64 dummy4; } notify_reply; struct { /* BATCH_FORGET */ UINT32 count; UINT32 dummy; } batch_forget; struct { /* FALLOCATE */ UINT64 fh; UINT64 offset; UINT64 length; UINT32 mode; UINT32 padding; } fallocate; struct { /* RENAME2 */ UINT64 newdir; UINT32 flags; UINT32 padding; CHAR name[]; /* 2 names */ } rename2; struct { /* LSEEK */ UINT64 fh; UINT64 offset; UINT32 whence; UINT32 padding; } lseek; struct { /* COPY_FILE_RANGE */ UINT64 fh_in; UINT64 off_in; UINT64 nodeid_out; UINT64 fh_out; UINT64 off_out; UINT64 len; UINT64 flags; } copy_file_range; } req; } FUSE_PROTO_REQ; #define FUSE_PROTO_REQ_HEADER_SIZE ((ULONG)FIELD_OFFSET(FUSE_PROTO_REQ, req)) #define FUSE_PROTO_REQ_SIZEMIN 8192 // FUSE_MIN_READ_BUFFER #define FUSE_PROTO_REQ_SIZE(F) RTL_SIZEOF_THROUGH_FIELD(FUSE_PROTO_REQ, req.F) typedef struct { UINT32 len; INT32 error; UINT64 unique; union { struct { /* LOOKUP */ FUSE_PROTO_ENTRY entry; } lookup; struct { /* GETATTR */ UINT64 attr_valid; UINT32 attr_valid_nsec; UINT32 dummy; FUSE_PROTO_ATTR attr; } getattr; struct { /* SETATTR */ UINT64 attr_valid; UINT32 attr_valid_nsec; UINT32 dummy; FUSE_PROTO_ATTR attr; } setattr; struct { /* SYMLINK */ FUSE_PROTO_ENTRY entry; } symlink; struct { /* MKNOD */ FUSE_PROTO_ENTRY entry; } mknod; struct { /* MKDIR */ FUSE_PROTO_ENTRY entry; } mkdir; struct { /* LINK */ FUSE_PROTO_ENTRY entry; } link; struct { /* OPEN, OPENDIR */ UINT64 fh; UINT32 open_flags; UINT32 padding; } open; struct { /* WRITE */ UINT32 size; UINT32 padding; } write; struct { /* STATFS */ FUSE_PROTO_STATFS st; } statfs; struct { /* GETXATTR */ UINT32 size; UINT32 padding; } getxattr; struct { /* LISTXATTR */ UINT32 size; UINT32 padding; } listxattr; struct { /* INIT */ UINT32 major; UINT32 minor; UINT32 max_readahead; UINT32 flags; UINT16 max_background; UINT16 congestion_threshold; UINT32 max_write; UINT32 time_gran; UINT16 max_pages; UINT16 padding; UINT32 unused[8]; } init; struct { /* GETLK */ FUSE_PROTO_FILE_LOCK lk; } lk; struct { /* CREATE */ FUSE_PROTO_ENTRY entry; UINT64 fh; UINT32 open_flags; UINT32 padding; } create; struct { /* BMAP */ UINT64 block; } bmap; struct { /* IOCTL */ INT32 result; UINT32 flags; UINT32 in_iovs; UINT32 out_iovs; } ioctl; struct { /* POLL */ UINT32 revents; UINT32 padding; } poll; struct { /* LSEEK */ UINT64 offset; } lseek; struct { /* COPY_FILE_RANGE */ UINT32 size; UINT32 padding; } copy_file_range; /* notify */ struct { /* NOTIFY_POLL */ UINT64 kh; } notify_poll; struct { /* NOTIFY_INVAL_INODE */ UINT64 ino; INT64 off; INT64 len; } notify_inval_inode; struct { /* NOTIFY_INVAL_ENTRY */ UINT64 parent; UINT32 namelen; UINT32 padding; } notify_inval_entry; struct { /* NOTIFY_STORE */ UINT64 nodeid; UINT64 offset; UINT32 size; UINT32 padding; } notify_store; struct { /* NOTIFY_RETRIEVE */ UINT64 notify_unique; UINT64 nodeid; UINT64 offset; UINT32 size; UINT32 padding; } notify_retrieve; struct { /* NOTIFY_DELETE */ UINT64 parent; UINT64 child; UINT32 namelen; UINT32 padding; } notify_delete; } rsp; } FUSE_PROTO_RSP; #define FUSE_PROTO_RSP_HEADER_SIZE ((ULONG)FIELD_OFFSET(FUSE_PROTO_RSP, rsp)) #define FUSE_PROTO_RSP_SIZE(F) RTL_SIZEOF_THROUGH_FIELD(FUSE_PROTO_RSP, rsp.F) #endif ================================================ FILE: src/shared/km/shared.h ================================================ /** * @file shared/km/shared.h * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef SHARED_KM_SHARED_H_INCLUDED #define SHARED_KM_SHARED_H_INCLUDED #include #include /* disable warnings */ #pragma warning(disable:4100) /* unreferenced formal parameter */ #pragma warning(disable:4127) /* conditional expression is constant */ #pragma warning(disable:4200) /* zero-sized array in struct/union */ #pragma warning(disable:4201) /* nameless struct/union */ #include #include /* debug */ #if DBG enum { fuse_debug_dt = 0x01000000, /* DEBUGTEST switch */ fuse_debug_dp = 0x10000000, /* DbgPrint switch */ }; extern __declspec(selectany) int fuse_debug = fuse_debug_dt; ULONG DebugRandom(VOID); BOOLEAN DebugMemory(PVOID Memory, SIZE_T Size, BOOLEAN Test); VOID FuseDebugLogRequest(FUSE_PROTO_REQ *Request); VOID FuseDebugLogResponse(FUSE_PROTO_RSP *Response); #endif /* DbgPrint */ #if DBG #define DbgPrint(...) \ ((void)((fuse_debug & fuse_debug_dp) ? DbgPrint(__VA_ARGS__) : 0)) #endif /* debug tools */ #if DBG #define DEBUGLOG(fmt, ...) \ DbgPrint("[%d] FUSE!" __FUNCTION__ ": " fmt "\n", KeGetCurrentIrql(), __VA_ARGS__) #define DEBUGTEST(Percent) \ (0 == (fuse_debug & fuse_debug_dt) || DebugRandom() <= (Percent) * 0x7fff / 100) #define DEBUGFILL(M, S) DebugMemory(M, S, FALSE) #define DEBUGGOOD(M, S) DebugMemory(M, S, TRUE) #else #define DEBUGLOG(fmt, ...) ((void)0) #define DEBUGTEST(Percent) (TRUE) #define DEBUGFILL(M, S) (TRUE) #define DEBUGGOOD(M, S) (TRUE) #endif /* memory allocation */ #define FUSE_ALLOC_TAG 'ESUF' #define FuseAlloc(Size) ExAllocatePoolWithTag(PagedPool, Size, FUSE_ALLOC_TAG) #define FuseAllocNonPaged(Size) ExAllocatePoolWithTag(NonPagedPool, Size, FUSE_ALLOC_TAG) #define FuseAllocMustSucceed(Size) FuseAllocatePoolMustSucceed(PagedPool, Size, FUSE_ALLOC_TAG) #define FuseFree(Pointer) ExFreePoolWithTag(Pointer, FUSE_ALLOC_TAG) #define FuseFreeExternal(Pointer) ExFreePool(Pointer) /* hash mix */ /* Based on the MurmurHash3 fmix32/fmix64 function: * See: https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp?r=152#68 */ static inline UINT32 FuseHashMix32(UINT32 h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } static inline UINT64 FuseHashMix64(UINT64 k) { k ^= k >> 33; k *= 0xff51afd7ed558ccdULL; k ^= k >> 33; k *= 0xc4ceb9fe1a85ec53ULL; k ^= k >> 33; return k; } static inline ULONG FuseHashMixPointer(PVOID Pointer) { #if _WIN64 return (ULONG)FuseHashMix64((UINT64)Pointer); #else return (ULONG)FuseHashMix32((UINT32)Pointer); #endif } /* POSIX paths */ VOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain); VOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix); /* utility */ PVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag); NTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len); NTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS InfoClass, PUINT32 PUid); /* read/write locks */ #define FUSE_RWLOCK_USE_SEMAPHORE //#define FUSE_RWLOCK_USE_ERESOURCE typedef struct _FUSE_RWLOCK { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) KSEMAPHORE OrderSem; KSEMAPHORE WriteSem; LONG Readers; #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ERESOURCE Resource; #else #error One of FUSE_RWLOCK_USE_SEMAPHORE or FUSE_RWLOCK_USE_ERESOURCE must be defined. #endif } FUSE_RWLOCK; static inline VOID FuseRwlockInitialize(FUSE_RWLOCK *Lock) { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) KeInitializeSemaphore(&Lock->OrderSem, 1, 1); KeInitializeSemaphore(&Lock->WriteSem, 1, 1); Lock->Readers = 0; #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ExInitializeResourceLite(&Lock->Resource); #endif } static inline VOID FuseRwlockFinalize(FUSE_RWLOCK *Lock) { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ExDeleteResourceLite(&Lock->Resource); #endif } static inline BOOLEAN FuseRwlockEnterWriter(FUSE_RWLOCK *Lock, PVOID Owner) { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) NTSTATUS Result; Result = FsRtlCancellableWaitForSingleObject(&Lock->OrderSem, 0, 0); if (STATUS_SUCCESS == Result) { Result = FsRtlCancellableWaitForSingleObject(&Lock->WriteSem, 0, 0); KeReleaseSemaphore(&Lock->OrderSem, 1, 1, FALSE); } return STATUS_SUCCESS == Result; #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ExAcquireResourceExclusiveLite(&Lock->Resource, TRUE); ExSetResourceOwnerPointer(&Lock->Resource, (PVOID)((UINT_PTR)Owner | 3)); return TRUE; #endif } static inline BOOLEAN FuseRwlockEnterReader(FUSE_RWLOCK *Lock, PVOID Owner) { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) NTSTATUS Result; Result = FsRtlCancellableWaitForSingleObject(&Lock->OrderSem, 0, 0); if (STATUS_SUCCESS == Result) { if (1 == InterlockedIncrement(&Lock->Readers)) { Result = FsRtlCancellableWaitForSingleObject(&Lock->WriteSem, 0, 0); if (STATUS_SUCCESS != Result) InterlockedDecrement(&Lock->Readers); } KeReleaseSemaphore(&Lock->OrderSem, 1, 1, FALSE); } return STATUS_SUCCESS == Result; #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ExAcquireResourceSharedLite(&Lock->Resource, TRUE); ExSetResourceOwnerPointer(&Lock->Resource, (PVOID)((UINT_PTR)Owner | 3)); return TRUE; #endif } static inline VOID FuseRwlockLeaveWriter(FUSE_RWLOCK *Lock, PVOID Owner) { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) KeReleaseSemaphore(&Lock->WriteSem, 1, 1, FALSE); #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ExReleaseResourceForThreadLite(&Lock->Resource, (ERESOURCE_THREAD)((UINT_PTR)Owner | 3)); #endif } static inline VOID FuseRwlockLeaveReader(FUSE_RWLOCK *Lock, PVOID Owner) { #if defined(FUSE_RWLOCK_USE_SEMAPHORE) if (0 == InterlockedDecrement(&Lock->Readers)) KeReleaseSemaphore(&Lock->WriteSem, 1, 1, FALSE); #elif defined(FUSE_RWLOCK_USE_ERESOURCE) ExReleaseResourceForThreadLite(&Lock->Resource, (ERESOURCE_THREAD)((UINT_PTR)Owner | 3)); #endif } /* FUSE instances */ typedef struct _FUSE_IOQ FUSE_IOQ; typedef struct _FUSE_CACHE FUSE_CACHE; typedef enum _FUSE_INSTANCE_TYPE { FuseInstanceWindows = 'W', FuseInstanceCygwin = 'C', FuseInstanceLinux = 'L', } FUSE_INSTANCE_TYPE; typedef struct _FUSE_INSTANCE { FSP_FSCTL_VOLUME_PARAMS *VolumeParams; FUSE_INSTANCE_TYPE InstanceType; FUSE_RWLOCK OpGuardLock; FUSE_IOQ *Ioq; FUSE_CACHE *Cache; KSPIN_LOCK FileListLock; LIST_ENTRY FileList; KEVENT InitEvent; UINT32 VersionMajor, VersionMinor; VOID (*ProtoSendDestroyHandler)(PVOID); PVOID ProtoSendDestroyData; /* * The following bitmap is used to remember which opcodes have returned ENOSYS. * * It is assumed that an opcode that returned ENOSYS once, will continue returning * ENOSYS in the future. Thus an expensive message to user space can be eliminated. * * This bitmap may be accessed from multiple threads without locking. This is * because the bitmap is used for optimization purposes ONLY, and it is ok for * extraneous requests (that will result in ENOSYS) to be sent to the user mode * file system. */ UINT32 OpcodeENOSYS[2]; } FUSE_INSTANCE; NTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance, FSP_FSCTL_VOLUME_PARAMS *VolumeParams, FUSE_INSTANCE_TYPE InstanceType); VOID FuseInstanceFini(FUSE_INSTANCE *Instance); VOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 ExpirationTime); NTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance, FUSE_PROTO_RSP *FuseResponse, ULONG InputBufferLength, FUSE_PROTO_REQ *FuseRequest, PULONG POutputBufferLength, PDEVICE_OBJECT DeviceObject, PFILE_OBJECT FileObject, PIRP CancellableIrp); static inline BOOLEAN FuseInstanceGetOpcodeENOSYS(FUSE_INSTANCE *Instance, UINT32 Opcode) { ASSERT(sizeof Instance->OpcodeENOSYS / sizeof Instance->OpcodeENOSYS[0] > (Opcode >> 5)); ASSERT(8 * sizeof Instance->OpcodeENOSYS[0] > (Opcode & 0x1f)); return !!(Instance->OpcodeENOSYS[Opcode >> 5] & (1 << (Opcode & 0x1f))); } static inline VOID FuseInstanceSetOpcodeENOSYS(FUSE_INSTANCE *Instance, UINT32 Opcode) { ASSERT(sizeof Instance->OpcodeENOSYS / sizeof Instance->OpcodeENOSYS[0] > (Opcode >> 5)); ASSERT(8 * sizeof Instance->OpcodeENOSYS[0] > (Opcode & 0x1f)); Instance->OpcodeENOSYS[Opcode >> 5] |= (1 << (Opcode & 0x1f)); } /* FUSE files */ typedef struct _FUSE_FILE { LIST_ENTRY ListEntry; UINT64 Ino; UINT64 Fh; UINT32 OpenFlags; UINT32 IsDirectory:1; UINT32 IsReparsePoint:1; PVOID CacheItem; } FUSE_FILE; VOID FuseFileInstanceInit(FUSE_INSTANCE *Instance); VOID FuseFileInstanceFini(FUSE_INSTANCE *Instance); NTSTATUS FuseFileCreate(FUSE_INSTANCE *Instance, FUSE_FILE **PFile); VOID FuseFileDelete(FUSE_INSTANCE *Instance, FUSE_FILE *File); /* FUSE processing context */ typedef struct _FUSE_CONTEXT FUSE_CONTEXT; typedef VOID FUSE_CONTEXT_FINI(FUSE_CONTEXT *Context); typedef BOOLEAN FUSE_OPERATION_PROC(FUSE_CONTEXT *Context); typedef INT FUSE_OPERATION_GUARD(FUSE_CONTEXT *Context, BOOLEAN Acquire); enum { FuseOpGuardCancel = -1, FuseOpGuardFalse = 0, FuseOpGuardTrue = 1, }; typedef struct _FUSE_OPERATION { FUSE_OPERATION_PROC *Proc; FUSE_OPERATION_GUARD *Guard; } FUSE_OPERATION; typedef struct _FUSE_CONTEXT_LOOKUP { PVOID CacheGen; PVOID CacheItem; UINT64 Ino; STRING Name; FUSE_PROTO_ATTR Attr; } FUSE_CONTEXT_LOOKUP; typedef struct _FUSE_CONTEXT_FORGET { LIST_ENTRY ForgetList; } FUSE_CONTEXT_FORGET; typedef struct _FUSE_CONTEXT_SETATTR { FUSE_PROTO_ATTR Attr; UINT32 AttrValid; } FUSE_CONTEXT_SETATTR; struct _FUSE_CONTEXT { FUSE_CONTEXT *DictNext; LIST_ENTRY ListEntry; FUSE_CONTEXT_FINI *Fini; FUSE_INSTANCE *Instance; FSP_FSCTL_TRANSACT_REQ *InternalRequest; FSP_FSCTL_TRANSACT_RSP *InternalResponse; FSP_FSCTL_DECLSPEC_ALIGN UINT8 InternalResponseBuf[sizeof(FSP_FSCTL_TRANSACT_RSP)]; FUSE_PROTO_REQ *FuseRequest; FUSE_PROTO_RSP *FuseResponse; ULONG FuseRequestLength; #if DBG UINT32 DebugLogOpcode; #endif INT OpGuardResult; SHORT CoroState[16]; UINT32 OrigUid, OrigGid, OrigPid; FUSE_FILE *File; union { FUSE_CONTEXT_LOOKUP Lookup; FUSE_CONTEXT_FORGET Forget; struct { FUSE_CONTEXT_LOOKUP; STRING OrigPath; STRING Remain; UINT32 DesiredAccess, GrantedAccess; UINT32 UserMode:1; UINT32 HasTraversePrivilege:1; UINT32 DisableCache:1; UINT32 Chown:1; UINT32 RenameIsNonExistent:1; UINT32 RenameIsDirectory:1; /* 2 path operations (rename) */ STRING OrigPath2; STRING Name2; UINT64 Ino2; } LookupPath; FUSE_CONTEXT_SETATTR Setattr; struct { FUSE_PROTO_ATTR Attr; UINT64 StartOffset; UINT32 Remain; UINT32 Offset; UINT32 Length; } Read, Write; struct { FUSE_CONTEXT_LOOKUP; STRING OrigName; UINT64 NextOffset; UINT32 Length; ULONG BytesTransferred; PUINT8 Buffer, BufferEndP, BufferP; } QueryDirectory; struct { FUSE_CONTEXT_SETATTR; PSECURITY_DESCRIPTOR SecurityDescriptor; } Security; }; }; extern FUSE_OPERATION FuseOperations[]; VOID FuseContextCreate(FUSE_CONTEXT **PContext, FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest); VOID FuseContextDelete(FUSE_CONTEXT *Context); static inline BOOLEAN FuseContextProcess(FUSE_CONTEXT *Context, FUSE_PROTO_RSP *FuseResponse, FUSE_PROTO_REQ *FuseRequest, ULONG FuseRequestLength) { ASSERT(0 == FuseRequest || 0 == FuseResponse); ASSERT(0 != FuseRequest || 0 != FuseResponse); UINT32 Kind = 0 == Context->InternalRequest ? FspFsctlTransactReservedKind : Context->InternalRequest->Kind; if (0 == Context->FuseRequest && 0 == Context->FuseResponse && 0 != FuseOperations[Kind].Guard) { ASSERT(FuseOpGuardFalse == Context->OpGuardResult); Context->OpGuardResult = FuseOperations[Kind].Guard(Context, TRUE); if (FuseOpGuardCancel == Context->OpGuardResult) { Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_CANCELLED; return FALSE; } } Context->FuseRequest = FuseRequest; Context->FuseResponse = FuseResponse; Context->FuseRequestLength = FuseRequestLength; BOOLEAN Result = FuseOperations[Kind].Proc(Context); if (!Result && FuseOpGuardTrue == Context->OpGuardResult) { FuseOperations[Kind].Guard(Context, FALSE); Context->OpGuardResult = FuseOpGuardFalse; } return Result; } static inline INT FuseOpGuardResult_(BOOLEAN RwlockResult) { ASSERT( ( RwlockResult && FuseOpGuardTrue == (((INT)RwlockResult - 1) | 1)) || (!RwlockResult && FuseOpGuardCancel == (((INT)RwlockResult - 1) | 1))); return ((INT)RwlockResult - 1) | 1; } static inline INT FuseOpGuardAcquireExclusive(FUSE_CONTEXT *Context) { return FuseOpGuardResult_(FuseRwlockEnterWriter(&Context->Instance->OpGuardLock, Context)); } static inline INT FuseOpGuardAcquireShared(FUSE_CONTEXT *Context) { return FuseOpGuardResult_(FuseRwlockEnterReader(&Context->Instance->OpGuardLock, Context)); } static inline INT FuseOpGuardReleaseExclusive(FUSE_CONTEXT *Context) { FuseRwlockLeaveWriter(&Context->Instance->OpGuardLock, Context); return FuseOpGuardFalse; } static inline INT FuseOpGuardReleaseShared(FUSE_CONTEXT *Context) { FuseRwlockLeaveReader(&Context->Instance->OpGuardLock, Context); return FuseOpGuardFalse; } #define FuseContextStatus(S) \ ( \ ASSERT(0xC0000000 == ((UINT32)(S) & 0xFFFF0000)),\ (FUSE_CONTEXT *)(UINT_PTR)((UINT32)(S) & 0x0000FFFF)\ ) #define FuseContextIsStatus(C) ((UINT_PTR)0x0000FFFF >= (UINT_PTR)(C)) #define FuseContextToStatus(C) ((NTSTATUS)(0xC0000000 | (UINT32)(UINT_PTR)(C))) #define FuseContextWaitRequest(C) do { while (0 == (C)->FuseRequest) coro_yield; } while (0,0) #define FuseContextWaitResponse(C) do { coro_yield; } while (0 == (C)->FuseResponse) /* FUSE I/O queue */ NTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq); VOID FuseIoqDelete(FUSE_IOQ *Ioq); VOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context); FUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique); VOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context); VOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context); FUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq); /* does not block! */ /* FUSE "entry" cache */ typedef struct _FUSE_CACHE_GEN FUSE_CACHE_GEN; NTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache); VOID FuseCacheDelete(FUSE_CACHE *Cache); VOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache, FUSE_INSTANCE *Instance, UINT64 ExpirationTime); NTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen); VOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen); BOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name, FUSE_PROTO_ENTRY *Entry, PVOID *PItem); VOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name, FUSE_PROTO_ENTRY *Entry, PVOID *PItem); VOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name); VOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item); VOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item); VOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item); VOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList); BOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne); /* protocol implementation */ NTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance); VOID FuseProtoSendInit(FUSE_CONTEXT *Context); NTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance); VOID FuseProtoSendDestroy(FUSE_CONTEXT *Context); VOID FuseProtoSendLookup(FUSE_CONTEXT *Context); NTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY ForgetList); VOID FuseProtoFillForget(FUSE_CONTEXT *Context); VOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context); VOID FuseProtoSendStatfs(FUSE_CONTEXT *Context); VOID FuseProtoSendGetattr(FUSE_CONTEXT *Context); VOID FuseProtoSendFgetattr(FUSE_CONTEXT *Context); VOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context); VOID FuseProtoSendFutimens(FUSE_CONTEXT *Context); VOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context); VOID FuseProtoSendSetattr(FUSE_CONTEXT *Context); VOID FuseProtoSendMkdir(FUSE_CONTEXT *Context); VOID FuseProtoSendMknod(FUSE_CONTEXT *Context); VOID FuseProtoSendRmdir(FUSE_CONTEXT *Context); VOID FuseProtoSendUnlink(FUSE_CONTEXT *Context); VOID FuseProtoSendRename(FUSE_CONTEXT *Context); VOID FuseProtoSendCreate(FUSE_CONTEXT *Context); VOID FuseProtoSendOpendir(FUSE_CONTEXT *Context); VOID FuseProtoSendOpen(FUSE_CONTEXT *Context); VOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context); VOID FuseProtoSendRelease(FUSE_CONTEXT *Context); VOID FuseProtoSendReaddir(FUSE_CONTEXT *Context); VOID FuseProtoSendRead(FUSE_CONTEXT *Context); VOID FuseProtoSendWrite(FUSE_CONTEXT *Context); VOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context); VOID FuseProtoSendFsync(FUSE_CONTEXT *Context); VOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance, FUSE_PROTO_ATTR *Attr, FSP_FSCTL_FILE_INFO *FileInfo); static inline VOID FuseFileTimeToUnixTime(UINT64 FileTime0, PUINT64 sec, PUINT32 nsec) { INT64 FileTime = (INT64)FileTime0 - 116444736000000000LL; INT32 Remain = FileTime % 10000000; *sec = (UINT64)(FileTime / 10000000); *nsec = (UINT32)(0 <= Remain ? Remain : Remain + 10000000) * 100; } static inline VOID FuseUnixTimeToFileTime(UINT64 sec, UINT32 nsec, PUINT64 PFileTime) { INT64 FileTime = (INT64)sec * 10000000 + (INT64)nsec / 100 + 116444736000000000LL; *PFileTime = FileTime; } NTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno); #endif ================================================ FILE: src/shared/km/util.c ================================================ /** * @file shared/km/util.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include PVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag); NTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len); NTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS InfoClass, PUINT32 PUid); #ifdef ALLOC_PRAGMA // !#pragma alloc_text(PAGE, FuseAllocatePoolMustSucceed) #pragma alloc_text(PAGE, FuseSafeCopyMemory) #pragma alloc_text(PAGE, FuseGetTokenUid) #endif static const LONG Delays[] = { 10/*ms*/ * -10000, 10/*ms*/ * -10000, 50/*ms*/ * -10000, 50/*ms*/ * -10000, 100/*ms*/ * -10000, 100/*ms*/ * -10000, 300/*ms*/ * -10000, }; PVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag) { // !PAGED_CODE(); PVOID Result; LARGE_INTEGER Delay; for (ULONG i = 0, n = sizeof(Delays) / sizeof(Delays[0]);; i++) { Result = DEBUGTEST(99) ? ExAllocatePoolWithTag(PoolType, Size, Tag) : 0; if (0 != Result) return Result; Delay.QuadPart = n > i ? Delays[i] : Delays[n - 1]; KeDelayExecutionThread(KernelMode, FALSE, &Delay); } } NTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len) { PAGED_CODE(); try { RtlCopyMemory(Dst, Src, Len); return STATUS_SUCCESS; } except (EXCEPTION_EXECUTE_HANDLER) { NTSTATUS Result = GetExceptionCode(); return FsRtlIsNtstatusExpected(Result) ? STATUS_INVALID_USER_BUFFER : Result; } } NTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS InfoClass, PUINT32 PUid) { PAGED_CODE(); NTSTATUS Result; PVOID Info = 0; PSID *PSid; Result = SeQueryInformationToken(Token, InfoClass, &Info); if (!NT_SUCCESS(Result)) goto exit; switch (InfoClass) { case TokenUser: PSid = &((PTOKEN_USER)Info)->User.Sid; break; case TokenOwner: PSid = &((PTOKEN_OWNER)Info)->Owner; break; case TokenPrimaryGroup: PSid = &((PTOKEN_PRIMARY_GROUP)Info)->PrimaryGroup; break; default: ASSERT(0); Result = STATUS_INVALID_PARAMETER; goto exit; } Result = FspPosixMapSidToUid(*PSid, PUid); exit: if (0 != Info) FuseFreeExternal(Info); return Result; } ================================================ FILE: src/shared/ku/wslfuse.h ================================================ /** * @file shared/ku/wslfuse.h * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef SHARED_KU_WSLFUSE_H_INCLUDED #define SHARED_KU_WSLFUSE_H_INCLUDED #if defined(__linux__) /* * We duplicate some of the definitions from WinFsp and WinFuse * to avoid having either of them as a build dependency when * building on Linux. */ #include #include #include typedef char CHAR; typedef uint16_t WCHAR; typedef uint8_t UINT8; typedef uint16_t UINT16; typedef uint32_t UINT32; typedef uint64_t UINT64; #define FSP_FSCTL_DISK_DEVICE_NAME "WinFsp.Disk" #define FSP_FSCTL_NET_DEVICE_NAME "WinFsp.Net" #define FSP_FSCTL_VOLUME_NAME_SIZE (64 * sizeof(WCHAR)) #define FSP_FSCTL_VOLUME_PREFIX_SIZE (192 * sizeof(WCHAR)) #define FSP_FSCTL_VOLUME_FSNAME_SIZE (16 * sizeof(WCHAR)) #define FSP_FSCTL_VOLUME_NAME_SIZEMAX (FSP_FSCTL_VOLUME_NAME_SIZE + FSP_FSCTL_VOLUME_PREFIX_SIZE) #define FSP_FSCTL_VOLUME_PARAMS_V0_FIELD_DEFN\ UINT16 Version; /* set to 0 or sizeof(FSP_FSCTL_VOLUME_PARAMS) */\ /* volume information */\ UINT16 SectorSize;\ UINT16 SectorsPerAllocationUnit;\ UINT16 MaxComponentLength; /* maximum file name component length (bytes) */\ UINT64 VolumeCreationTime;\ UINT32 VolumeSerialNumber;\ /* I/O timeouts, capacity, etc. */\ UINT32 TransactTimeout; /* DEPRECATED: (millis; 1 sec - 10 sec) */\ UINT32 IrpTimeout; /* pending IRP timeout (millis; 1 min - 10 min) */\ UINT32 IrpCapacity; /* maximum number of pending IRP's (100 - 1000)*/\ UINT32 FileInfoTimeout; /* FileInfo/Security/VolumeInfo timeout (millis) */\ /* FILE_FS_ATTRIBUTE_INFORMATION::FileSystemAttributes */\ UINT32 CaseSensitiveSearch:1; /* file system supports case-sensitive file names */\ UINT32 CasePreservedNames:1; /* file system preserves the case of file names */\ UINT32 UnicodeOnDisk:1; /* file system supports Unicode in file names */\ UINT32 PersistentAcls:1; /* file system preserves and enforces access control lists */\ UINT32 ReparsePoints:1; /* file system supports reparse points */\ UINT32 ReparsePointsAccessCheck:1; /* file system performs reparse point access checks */\ UINT32 NamedStreams:1; /* file system supports named streams */\ UINT32 HardLinks:1; /* unimplemented; set to 0 */\ UINT32 ExtendedAttributes:1; /* file system supports extended attributes */\ UINT32 ReadOnlyVolume:1;\ /* kernel-mode flags */\ UINT32 PostCleanupWhenModifiedOnly:1; /* post Cleanup when a file was modified/deleted */\ UINT32 PassQueryDirectoryPattern:1; /* pass Pattern during QueryDirectory operations */\ UINT32 AlwaysUseDoubleBuffering:1;\ UINT32 PassQueryDirectoryFileName:1; /* pass FileName during QueryDirectory (GetDirInfoByName) */\ UINT32 FlushAndPurgeOnCleanup:1; /* keeps file off "standby" list */\ UINT32 DeviceControl:1; /* support user-mode ioctl handling */\ /* user-mode flags */\ UINT32 UmFileContextIsUserContext2:1; /* user mode: FileContext parameter is UserContext2 */\ UINT32 UmFileContextIsFullContext:1; /* user mode: FileContext parameter is FullContext */\ UINT32 UmReservedFlags:6;\ /* additional kernel-mode flags */\ UINT32 AllowOpenInKernelMode:1; /* allow kernel mode to open files when possible */\ UINT32 CasePreservedExtendedAttributes:1; /* preserve case of EA (default is UPPERCASE) */\ UINT32 WslFeatures:1; /* support features required for WSLinux */\ UINT32 KmReservedFlags:5;\ WCHAR Prefix[FSP_FSCTL_VOLUME_PREFIX_SIZE / sizeof(WCHAR)]; /* UNC prefix (\Server\Share) */\ WCHAR FileSystemName[FSP_FSCTL_VOLUME_FSNAME_SIZE / sizeof(WCHAR)]; #define FSP_FSCTL_VOLUME_PARAMS_V1_FIELD_DEFN\ /* additional fields; specify .Version == sizeof(FSP_FSCTL_VOLUME_PARAMS) */\ UINT32 VolumeInfoTimeoutValid:1; /* VolumeInfoTimeout field is valid */\ UINT32 DirInfoTimeoutValid:1; /* DirInfoTimeout field is valid */\ UINT32 SecurityTimeoutValid:1; /* SecurityTimeout field is valid*/\ UINT32 StreamInfoTimeoutValid:1; /* StreamInfoTimeout field is valid */\ UINT32 EaTimeoutValid:1; /* EaTimeout field is valid */\ UINT32 KmAdditionalReservedFlags:27;\ UINT32 VolumeInfoTimeout; /* volume info timeout (millis); overrides FileInfoTimeout */\ UINT32 DirInfoTimeout; /* dir info timeout (millis); overrides FileInfoTimeout */\ UINT32 SecurityTimeout; /* security info timeout (millis); overrides FileInfoTimeout */\ UINT32 StreamInfoTimeout; /* stream info timeout (millis); overrides FileInfoTimeout */\ UINT32 EaTimeout; /* EA timeout (millis); overrides FileInfoTimeout */\ UINT32 FsextControlCode;\ UINT32 Reserved32[1];\ UINT64 Reserved64[2]; typedef struct { FSP_FSCTL_VOLUME_PARAMS_V0_FIELD_DEFN FSP_FSCTL_VOLUME_PARAMS_V1_FIELD_DEFN } FSP_FSCTL_VOLUME_PARAMS; _Static_assert(504 == sizeof(FSP_FSCTL_VOLUME_PARAMS), "sizeof(FSP_FSCTL_VOLUME_PARAMS) must be 504."); #endif typedef union { FSP_FSCTL_VOLUME_PARAMS VolumeParams; struct { CHAR VolumeName[(FSP_FSCTL_VOLUME_NAME_SIZEMAX / sizeof(WCHAR)) * 3 / 2]; UINT64 VolumeId; }; } WSLFUSE_IOCTL_CREATEVOLUME_ARG; #if defined(__linux__) _Static_assert(504 == sizeof(WSLFUSE_IOCTL_CREATEVOLUME_ARG), "sizeof(WSLFUSE_IOCTL_CREATEVOLUME_ARG) must be 504."); #endif typedef struct { CHAR WinMountPoint[260]; } WSLFUSE_IOCTL_WINMOUNT_ARG; #if defined(__linux__) _Static_assert(260 == sizeof(WSLFUSE_IOCTL_WINMOUNT_ARG), "sizeof(WSLFUSE_IOCTL_WINMOUNT_ARG) must be 260."); #endif typedef struct { UINT8 Operation; UINT64 VolumeId; UINT64 LxMountId; } WSLFUSE_IOCTL_LXMOUNT_ARG; #if defined(__linux__) _Static_assert(24 == sizeof(WSLFUSE_IOCTL_LXMOUNT_ARG), "sizeof(WSLFUSE_IOCTL_LXMOUNT_ARG) must be 16."); #endif /* * _IOWR('F', 'C', WSLFUSE_IOCTL_CREATEVOLUME_ARG) * sh tools/ioc.c 3 70 67 504 */ #define WSLFUSE_IOCTL_CREATEVOLUME 0xc1f84643 #if defined(__linux__) _Static_assert(WSLFUSE_IOCTL_CREATEVOLUME == _IOWR('F', 'C', WSLFUSE_IOCTL_CREATEVOLUME_ARG), "WSLFUSE_IOCTL_CREATEVOLUME"); #endif /* * _IOW('F', 'M', WSLFUSE_IOCTL_WINMOUNT_ARG) * sh tools/ioc.c 1 70 77 260 */ #define WSLFUSE_IOCTL_WINMOUNT 0x4104464d #if defined(__linux__) _Static_assert(WSLFUSE_IOCTL_WINMOUNT == _IOW('F', 'M', WSLFUSE_IOCTL_WINMOUNT_ARG), "WSLFUSE_IOCTL_WINMOUNT"); #endif /* * _IOW('F', 'm', WSLFUSE_IOCTL_LXMOUNT_ARG) * sh tools/ioc.c 1 70 109 24 */ #define WSLFUSE_IOCTL_LXMOUNT 0x4018466d #if defined(__linux__) _Static_assert(WSLFUSE_IOCTL_LXMOUNT == _IOW('F', 'm', WSLFUSE_IOCTL_LXMOUNT_ARG), "WSLFUSE_IOCTL_LXMOUNT"); #endif #endif ================================================ FILE: src/winfuse/device.c ================================================ /** * @file winfuse/device.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include static NTSTATUS FuseDeviceInit(PDEVICE_OBJECT DeviceObject, FSP_FSCTL_VOLUME_PARAMS *VolumeParams); static VOID FuseDeviceFini(PDEVICE_OBJECT DeviceObject); static VOID FuseDeviceExpirationRoutine(PDEVICE_OBJECT DeviceObject, UINT64 ExpirationTime); static NTSTATUS FuseDeviceTransact(PDEVICE_OBJECT DeviceObject, PIRP Irp); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE, FuseDeviceInit) #pragma alloc_text(PAGE, FuseDeviceFini) #pragma alloc_text(PAGE, FuseDeviceExpirationRoutine) #pragma alloc_text(PAGE, FuseDeviceTransact) #endif static NTSTATUS FuseDeviceInit(PDEVICE_OBJECT DeviceObject, FSP_FSCTL_VOLUME_PARAMS *VolumeParams) { PAGED_CODE(); FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject); NTSTATUS Result; KeEnterCriticalRegion(); Result = FuseInstanceInit(Instance, VolumeParams, FuseInstanceWindows); KeLeaveCriticalRegion(); return Result; } static VOID FuseDeviceFini(PDEVICE_OBJECT DeviceObject) { PAGED_CODE(); FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject); KeEnterCriticalRegion(); FuseInstanceFini(Instance); KeLeaveCriticalRegion(); } static VOID FuseDeviceExpirationRoutine(PDEVICE_OBJECT DeviceObject, UINT64 ExpirationTime) { PAGED_CODE(); FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject); KeEnterCriticalRegion(); FuseInstanceExpirationRoutine(Instance, ExpirationTime); KeLeaveCriticalRegion(); } static NTSTATUS FuseDeviceTransact(PDEVICE_OBJECT DeviceObject, PIRP Irp) { PAGED_CODE(); ASSERT(KeAreApcsDisabled()); PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp); ASSERT(IRP_MJ_FILE_SYSTEM_CONTROL == IrpSp->MajorFunction); ASSERT(IRP_MN_USER_FS_REQUEST == IrpSp->MinorFunction); ASSERT(FUSE_FSCTL_TRANSACT == IrpSp->Parameters.FileSystemControl.FsControlCode); ASSERT(METHOD_BUFFERED == (IrpSp->Parameters.FileSystemControl.FsControlCode & 3)); ASSERT(IrpSp->FileObject->FsContext2 == DeviceObject); FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject); ULONG InputBufferLength = IrpSp->Parameters.FileSystemControl.InputBufferLength; ULONG OutputBufferLength = IrpSp->Parameters.FileSystemControl.OutputBufferLength; FUSE_PROTO_RSP *FuseResponse = 0 != InputBufferLength ? Irp->AssociatedIrp.SystemBuffer : 0; FUSE_PROTO_REQ *FuseRequest = 0 != OutputBufferLength ? Irp->AssociatedIrp.SystemBuffer : 0; NTSTATUS Result; Result = FuseInstanceTransact(Instance, FuseResponse, InputBufferLength, FuseRequest, &OutputBufferLength, IrpSp->DeviceObject, IrpSp->FileObject, Irp); Irp->IoStatus.Information = OutputBufferLength; return Result; } FSP_FSEXT_PROVIDER FuseProvider = { /* Version */ sizeof FuseProvider, /* DeviceTransactCode */ FUSE_FSCTL_TRANSACT, /* DeviceExtensionSize */ sizeof(FUSE_INSTANCE), /* DeviceInit */ FuseDeviceInit, /* DeviceFini */ FuseDeviceFini, /* DeviceExpirationRoutine */ FuseDeviceExpirationRoutine, /* DeviceTransact */ FuseDeviceTransact, }; ================================================ FILE: src/winfuse/driver.c ================================================ /** * @file winfuse/driver.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include DRIVER_INITIALIZE DriverEntry; #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, DriverEntry) #endif NTSTATUS DriverEntry( PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { #if DBG if (!KD_DEBUGGER_NOT_PRESENT) DbgBreakPoint(); #endif return FspFsextProviderRegister(&FuseProvider); } ================================================ FILE: src/winfuse/driver.h ================================================ /** * @file winfuse/driver.h * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef WINFUSE_DRIVER_H_INCLUDED #define WINFUSE_DRIVER_H_INCLUDED #include #define FUSE_FSCTL_TRANSACT \ CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 0xC00 + 'F', METHOD_BUFFERED, FILE_ANY_ACCESS) extern FSP_FSEXT_PROVIDER FuseProvider; static inline FUSE_INSTANCE *FuseInstanceFromDeviceObject(PDEVICE_OBJECT DeviceObject) { return (PVOID)((PUINT8)DeviceObject->DeviceExtension + FuseProvider.DeviceExtensionOffset); } #endif ================================================ FILE: src/winfuse/driver.inf.in ================================================ [Version] Signature = "$WINDOWS NT$" Class = Volume ClassGuid = {71a27cdd-812a-11d0-bec7-08002be2092f} CatalogFile = !CatalogFile! Provider = !Provider! [DestinationDirs] DefaultDestDir = 12 [DefaultInstall] CopyFiles = Driver.CopyFiles [Driver.CopyFiles] !DriverFile! [SourceDisksFiles] !DriverFile! = 1 [SourceDisksNames] 1 = Disk1 ================================================ FILE: src/winfuse/version.rc ================================================ #include #define STR(x) STR_(x) #define STR_(x) #x VS_VERSION_INFO VERSIONINFO FILEVERSION MyVersionWithCommas PRODUCTVERSION MyVersionWithCommas FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0 #endif FILEOS VOS_NT FILETYPE VFT_DRV FILESUBTYPE VFT2_DRV_SYSTEM BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", STR(MyCompanyName) VALUE "FileDescription", STR(MyDescription) VALUE "FileVersion", STR(MyFullVersion) VALUE "InternalName", "winfuse.sys" VALUE "LegalCopyright", STR(MyCopyright) VALUE "OriginalFilename", "winfuse.sys" VALUE "ProductName", STR(MyProductName) VALUE "ProductVersion", STR(MyProductVersion) END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END ================================================ FILE: src/wslfuse/device.c ================================================ /** * @file wslfuse/device.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #define FUSE_MINOR 229 typedef struct _FILE FILE; typedef struct _MOUNT MOUNT; typedef struct _DEVICE DEVICE; struct _FILE { LX_FILE Base; LIST_ENTRY ListEntry; DEVICE *Device; MOUNT *Mount; EX_PUSH_LOCK VolumeLock; FSP_FSCTL_VOLUME_PARAMS VolumeParams; FUSE_INSTANCE *FuseInstance; UINT64 VolumeId; HANDLE VolumeHandle; PFILE_OBJECT VolumeFileObject; HANDLE WinMountHandle; }; struct _MOUNT { LONG RefCount; LIST_ENTRY ListEntry; UINT64 LxMountId; FILE *File; }; struct _DEVICE { LX_DEVICE Base; EX_PUSH_LOCK MountListLock; LIST_ENTRY MountList; }; static VOID FuseMiscFileListInsert(FILE *File); static VOID FuseMiscFileListRemove(FILE *File); static MOUNT *FuseMiscFileListGetMount(DEVICE *Device, UINT64 VolumeId); static inline MOUNT *MountCreate(VOID) { MOUNT *Mount; Mount = FuseAllocNonPaged(sizeof *Mount); if (0 == Mount) return 0; RtlZeroMemory(Mount, sizeof *Mount); Mount->RefCount = 1; Mount->LxMountId = (UINT64)-1LL; return Mount; } static inline VOID MountReference(MOUNT *Mount) { InterlockedIncrement(&Mount->RefCount); } static inline VOID MountDereference(MOUNT *Mount) { LONG RefCount; RefCount = InterlockedDecrement(&Mount->RefCount); if (0 == RefCount) FuseFree(Mount); } static VOID FileProtoSendDestroyHandler(PVOID File0) { FILE *File = (FILE *)File0; IO_STATUS_BLOCK IoStatus; ZwFsControlFile( File->VolumeHandle, 0/*Event*/, 0/*ApcRoutine*/, 0/*ApcContext*/, &IoStatus, FSP_FSCTL_STOP, 0/*InputBuffer*/, 0/*InputBufferLength*/, 0/*OutputBuffer*/, 0/*OutputBufferLength*/); } static INT FileIoctlCreateVolume( FILE *File, WSLFUSE_IOCTL_CREATEVOLUME_ARG *Arg) { SIZE_T VolumeParamsSize; UNICODE_STRING DevicePath; WCHAR DevicePathBuf[260/*MAX_PATH*/ + sizeof(FSP_FSCTL_VOLUME_PARAMS)]; WCHAR *DevicePathPtr, *DevicePathEnd; OBJECT_ATTRIBUTES ObjectAttributes; IO_STATUS_BLOCK IoStatus; FUSE_INSTANCE *FuseInstance = 0; BOOLEAN InitDoneInstance = FALSE; HANDLE VolumeHandle = 0; PFILE_OBJECT VolumeFileObject = 0; WCHAR VolumeName[FSP_FSCTL_VOLUME_NAME_SIZEMAX / sizeof(WCHAR)]; ULONG VolumeNameSize; ExAcquirePushLockExclusive(&File->VolumeLock); if (0 != File->VolumeFileObject) { IoStatus.Status = STATUS_INVALID_PARAMETER; goto exit; } VolumeParamsSize = 0 == Arg->VolumeParams.Version ? sizeof(FSP_FSCTL_VOLUME_PARAMS_V0) : Arg->VolumeParams.Version; if (sizeof(FSP_FSCTL_VOLUME_PARAMS) < VolumeParamsSize) { IoStatus.Status = STATUS_INVALID_PARAMETER; goto exit; } RtlCopyMemory(&File->VolumeParams, &Arg->VolumeParams, VolumeParamsSize); FuseInstance = FuseAllocNonPaged(sizeof *FuseInstance); if (0 == FuseInstance) { IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; goto exit; } IoStatus.Status = FuseInstanceInit(FuseInstance, &File->VolumeParams, FuseInstanceLinux); if (!NT_SUCCESS(IoStatus.Status)) goto exit; FuseInstance->ProtoSendDestroyHandler = FileProtoSendDestroyHandler; FuseInstance->ProtoSendDestroyData = File; File->VolumeParams.TransactTimeout = 3000; /* transact timeout allows poll with LxpThreadWait */ InitDoneInstance = TRUE; RtlInitEmptyUnicodeString(&DevicePath, DevicePathBuf, sizeof DevicePathBuf); RtlAppendUnicodeToString(&DevicePath, L'\0' == File->VolumeParams.Prefix[0] ? L"\\Device\\" FSP_FSCTL_DISK_DEVICE_NAME : L"\\Device\\" FSP_FSCTL_NET_DEVICE_NAME); RtlAppendUnicodeToString(&DevicePath, L"" FSP_FSCTL_VOLUME_PARAMS_PREFIX); DevicePathPtr = (PVOID)((PUINT8)DevicePath.Buffer + DevicePath.Length); DevicePathEnd = (PVOID)((PUINT8)DevicePathPtr + VolumeParamsSize * sizeof(WCHAR)); for (PUINT8 VolumeParamsPtr = (PVOID)&File->VolumeParams; DevicePathEnd > DevicePathPtr; DevicePathPtr++, VolumeParamsPtr++) { WCHAR Value = 0xF000 | *VolumeParamsPtr; *DevicePathPtr = Value; } DevicePath.Length = (USHORT)((PUINT8)DevicePathPtr - (PUINT8)DevicePath.Buffer); InitializeObjectAttributes( &ObjectAttributes, &DevicePath, OBJ_KERNEL_HANDLE, 0/*RootDirectory*/, 0/*SecurityDescriptor*/); IoStatus.Status = ZwOpenFile( &VolumeHandle, 0/*DesiredAccess*/, &ObjectAttributes, &IoStatus, FILE_SHARE_READ | FILE_SHARE_WRITE, 0/*OpenOptions*/); if (!NT_SUCCESS(IoStatus.Status)) goto exit; IoStatus.Status = ObReferenceObjectByHandle( VolumeHandle, 0/*DesiredAccess*/, *IoFileObjectType, KernelMode, &VolumeFileObject, 0/*HandleInformation*/); if (!NT_SUCCESS(IoStatus.Status)) goto exit; IoStatus.Status = ZwFsControlFile( VolumeHandle, 0/*Event*/, 0/*ApcRoutine*/, 0/*ApcContext*/, &IoStatus, FSP_FSCTL_VOLUME_NAME, 0/*InputBuffer*/, 0/*InputBufferLength*/, VolumeName, sizeof VolumeName); if (!NT_SUCCESS(IoStatus.Status)) goto exit; RtlZeroMemory(Arg, sizeof *Arg); VolumeNameSize = (ULONG)(wcslen(VolumeName) + 1) * sizeof(WCHAR); IoStatus.Status = RtlUnicodeToUTF8N( Arg->VolumeName, sizeof Arg->VolumeName, &VolumeNameSize, VolumeName, VolumeNameSize); if (!NT_SUCCESS(IoStatus.Status)) goto exit; Arg->VolumeId = File->VolumeId; File->FuseInstance = FuseInstance; File->VolumeHandle = VolumeHandle; InterlockedExchangePointer(&File->VolumeFileObject, VolumeFileObject); FuseMiscFileListInsert(File); IoStatus.Status = STATUS_SUCCESS; exit: if (!NT_SUCCESS(IoStatus.Status)) { if (0 != VolumeFileObject) ObDereferenceObject(VolumeFileObject); if (0 != VolumeHandle) ZwClose(VolumeHandle); if (InitDoneInstance) FuseInstanceFini(FuseInstance); if (0 != FuseInstance) FuseFree(FuseInstance); } ExReleasePushLockExclusive(&File->VolumeLock); /* !!!: REVISIT */ return NT_SUCCESS(IoStatus.Status) ? 0 : -EIO; } static INT FileIoctlWinMount( FILE *File, WSLFUSE_IOCTL_WINMOUNT_ARG *Arg) { UNICODE_STRING WinMountPoint; WCHAR WinMountPointBuf[4 + sizeof Arg->WinMountPoint]; ULONG WinMountPointSize; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE WinMountHandle; NTSTATUS Result; ExAcquirePushLockExclusive(&File->VolumeLock); if (0 != File->WinMountHandle) { Result = STATUS_INVALID_PARAMETER; goto exit; } Arg->WinMountPoint[sizeof Arg->WinMountPoint - 1] = '\0'; WinMountPointSize = (ULONG)strlen(Arg->WinMountPoint); WinMountPointBuf[0] = '\\'; WinMountPointBuf[1] = '?'; WinMountPointBuf[2] = '?'; WinMountPointBuf[3] = '\\'; Result = RtlUTF8ToUnicodeN( WinMountPointBuf + 4, sizeof WinMountPointBuf - 4, &WinMountPointSize, Arg->WinMountPoint, WinMountPointSize); if (!NT_SUCCESS(Result)) goto exit; WinMountPoint.Length = WinMountPoint.MaximumLength = (USHORT)(4 * sizeof(WCHAR) + WinMountPointSize); WinMountPoint.Buffer = WinMountPointBuf; InitializeObjectAttributes( &ObjectAttributes, &WinMountPoint, OBJ_KERNEL_HANDLE, 0/*RootDirectory*/, 0/*SecurityDescriptor*/); Result = ZwOpenSymbolicLinkObject(&WinMountHandle, 0, &ObjectAttributes); if (!NT_SUCCESS(Result)) goto exit; File->WinMountHandle = WinMountHandle; Result = STATUS_SUCCESS; exit: ExReleasePushLockExclusive(&File->VolumeLock); /* !!!: REVISIT */ return NT_SUCCESS(Result) ? 0 : -EIO; } static INT FileIoctlLxMount( FILE *File, WSLFUSE_IOCTL_LXMOUNT_ARG *Arg) { DEVICE *Device = File->Device; MOUNT *Mount; FILE *MountFile; INT Error = 0; ExAcquirePushLockExclusive(&Device->MountListLock); if ((UINT64)-1LL == Arg->LxMountId) Mount = File->Mount; else { Mount = 0; for (PLIST_ENTRY Entry = Device->MountList.Flink; &Device->MountList != Entry;) { MOUNT *Temp = CONTAINING_RECORD(Entry, MOUNT, ListEntry); Entry = Entry->Flink; if (Temp->LxMountId == Arg->LxMountId) { Mount = Temp; break; } } } switch (Arg->Operation) { case '+': if (0 != Mount) { Error = -EEXIST; break; } Mount = FuseMiscFileListGetMount(Device, Arg->VolumeId); if (0 == Mount) { Error = -ENOENT; break; } if ((UINT64)-1LL != Mount->LxMountId) { Error = -EEXIST; break; } MountReference(Mount); Mount->LxMountId = Arg->LxMountId; InsertTailList(&Device->MountList, &Mount->ListEntry); break; case '-': if (0 == Mount || (UINT64)-1LL == Mount->LxMountId) { Error = -ENOENT; break; } MountFile = Mount->File; RemoveEntryList(&Mount->ListEntry); Mount->LxMountId = (UINT64)-1LL; MountDereference(Mount); if (0 != MountFile && 0 != InterlockedCompareExchangePointer(&MountFile->VolumeFileObject, 0, 0)) FuseProtoPostDestroy(MountFile->FuseInstance); /* ignore errors */ break; case '?': if (0 == Mount || (UINT64)-1LL == Mount->LxMountId) { Error = -ENOENT; break; } break; default: Error = -EINVAL; break; } ExReleasePushLockExclusive(&Device->MountListLock); return Error; } static INT FileIoctlBegin( ULONG Code, PVOID Buffer, PVOID *PSystemBuffer) { ULONG Size = (Code >> 16) & 0x3fff; PVOID SystemBuffer = 0; INT Error; *PSystemBuffer = 0; if (FlagOn(Code, 0xc0000000/* _IOC_WRITE | _IOC_READ */) && 0 != Size) { SystemBuffer = FuseAllocNonPaged(Size); if (0 == SystemBuffer) { Error = -ENOMEM; goto exit; } try { if (FlagOn(Code, 0x80000000/* _IOC_READ */)) ProbeForWrite(Buffer, Size, 1); else ProbeForRead(Buffer, Size, 1); if (FlagOn(Code, 0x40000000/* _IOC_WRITE */)) RtlCopyMemory(SystemBuffer, Buffer, Size); else RtlZeroMemory(SystemBuffer, Size); } except (EXCEPTION_EXECUTE_HANDLER) { Error = -EFAULT; goto exit; } } *PSystemBuffer = SystemBuffer; SystemBuffer = 0; Error = 0; exit: if (0 != SystemBuffer) FuseFree(SystemBuffer); return Error; } static INT FileIoctlEnd( ULONG Code, PVOID Buffer, PVOID *PSystemBuffer, INT Error) { ULONG Size = (Code >> 16) & 0x3fff; PVOID SystemBuffer = *PSystemBuffer; if (0 == Error && FlagOn(Code, 0x80000000/* _IOC_READ */) && 0 != Size) { try { ProbeForWrite(Buffer, Size, 1); RtlCopyMemory(Buffer, SystemBuffer, Size); } except (EXCEPTION_EXECUTE_HANDLER) { Error = -EFAULT; goto exit; } } *PSystemBuffer = 0; exit: if (0 != SystemBuffer) FuseFree(SystemBuffer); return Error; } static INT FileIoctl( PLX_CALL_CONTEXT CallContext, PLX_FILE File0, ULONG Code, PVOID Buffer) { INT (*IoctlProc)(FILE *File, PVOID Arg); FILE *File = (FILE *)File0; PVOID SystemBuffer; INT Error; switch (Code) { case WSLFUSE_IOCTL_CREATEVOLUME: IoctlProc = FileIoctlCreateVolume; break; case WSLFUSE_IOCTL_WINMOUNT: IoctlProc = FileIoctlWinMount; break; case WSLFUSE_IOCTL_LXMOUNT: IoctlProc = FileIoctlLxMount; break; default: return -EINVAL; } Error = FileIoctlBegin(Code, Buffer, &SystemBuffer); if (0 == Error) { Error = IoctlProc(File, SystemBuffer); Error = FileIoctlEnd(Code, Buffer, &SystemBuffer, Error); } return Error; } static INT FileRead( PLX_CALL_CONTEXT CallContext, PLX_FILE File0, PVOID Buffer, SIZE_T Length, POFF_T POffset, PSIZE_T PBytesTransferred) { FILE *File = (FILE *)File0; ULONG OutputBufferLength; PFILE_OBJECT VolumeFileObject; NTSTATUS Result; VolumeFileObject = InterlockedCompareExchangePointer(&File->VolumeFileObject, 0, 0); if (0 == VolumeFileObject) return -ENODEV; for (;;) { OutputBufferLength = (ULONG)Length; Result = FuseInstanceTransact(File->FuseInstance, 0, 0, Buffer, &OutputBufferLength, 0, VolumeFileObject, 0); if (!NT_SUCCESS(Result)) return STATUS_CANCELLED == Result ? -ENODEV : -EIO; if (0 != OutputBufferLength) break; LARGE_INTEGER ZeroTimeout = { 0 }; Result = LxpThreadWait(0, &ZeroTimeout, FALSE); if (STATUS_TIMEOUT != Result) return -EINTR; } *PBytesTransferred = OutputBufferLength; return 0; } static INT FileWriteVector( PLX_CALL_CONTEXT CallContext, PLX_FILE File0, PLX_IOVECTOR IoVector, POFF_T POffset, ULONG Flags, PSIZE_T PBytesTransferred) { FILE *File = (FILE *)File0; FUSE_PROTO_RSP FuseResponseBuf, *FuseResponse = &FuseResponseBuf; ULONG InputBufferLength; ULONG OutputBufferLength = 0; PFILE_OBJECT VolumeFileObject; NTSTATUS Result; INT Error; VolumeFileObject = InterlockedCompareExchangePointer(&File->VolumeFileObject, 0, 0); if (0 == VolumeFileObject) return -ENODEV; InputBufferLength = 0; for (ULONG I = 0; (ULONG)IoVector->Count > I; I++) InputBufferLength += (ULONG)IoVector->Vector[I].Length; if (FUSE_PROTO_RSP_HEADER_SIZE > InputBufferLength) return -EINVAL; try { ULONG L = sizeof(FUSE_PROTO_RSP) < InputBufferLength ? FUSE_PROTO_RSP_HEADER_SIZE : sizeof(FUSE_PROTO_RSP); PUINT8 P = (PUINT8)&FuseResponseBuf, EndP = P + L; for (ULONG I = 0; (ULONG)IoVector->Count > I && EndP > P; I++) { L = (ULONG)(EndP - P); if (L > (ULONG)IoVector->Vector[I].Length) L = (ULONG)IoVector->Vector[I].Length; RtlCopyMemory(P, IoVector->Vector[I].Buffer, L); P += L; } if (sizeof(FUSE_PROTO_RSP) < InputBufferLength) { P = FuseAlloc(InputBufferLength); if (0 == P) { Error = -ENOMEM; goto exit; } FuseResponse = (PVOID)P; L = InputBufferLength; EndP = P + L; for (ULONG I = 0; (ULONG)IoVector->Count > I && EndP > P; I++) { L = (ULONG)(EndP - P); if (L > (ULONG)IoVector->Vector[I].Length) L = (ULONG)IoVector->Vector[I].Length; RtlCopyMemory(P, IoVector->Vector[I].Buffer, L); P += L; } } } except (EXCEPTION_EXECUTE_HANDLER) { Error = -EFAULT; goto exit; } Result = FuseInstanceTransact(File->FuseInstance, FuseResponse, InputBufferLength, 0, &OutputBufferLength, 0, VolumeFileObject, 0); if (!NT_SUCCESS(Result)) { Error = STATUS_CANCELLED == Result ? -ENODEV : -EIO; goto exit; } *PBytesTransferred = InputBufferLength; Error = 0; exit: if (&FuseResponseBuf != FuseResponse) FuseFree(FuseResponse); return Error; } static INT FileDelete( PLX_CALL_CONTEXT CallContext, PLX_FILE File0) { FILE *File = (FILE *)File0; DEVICE *Device = File->Device; if (0 != File->VolumeFileObject) FuseMiscFileListRemove(File); ExAcquirePushLockExclusive(&Device->MountListLock); File->Mount->File = 0; ExReleasePushLockExclusive(&Device->MountListLock); if (0 != File->WinMountHandle) ZwClose(File->WinMountHandle); if (0 != File->VolumeFileObject) { ObDereferenceObject(File->VolumeFileObject); ZwClose(File->VolumeHandle); FuseInstanceFini(File->FuseInstance); FuseFree(File->FuseInstance); } MountDereference(File->Mount); return 0; } static INT DeviceOpen( PLX_CALL_CONTEXT CallContext, PLX_DEVICE Device0, ULONG Flags, PLX_FILE *PFile) { static LX_FILE_CALLBACKS FileCallbacks = { .Delete = FileDelete, .Ioctl = FileIoctl, .Read = FileRead, .WriteVector = FileWriteVector, }; static LONG64 StaticVolumeId = -1LL; DEVICE *Device = (DEVICE *)Device0; MOUNT *Mount = 0; FILE *File; INT Error; *PFile = 0; Mount = MountCreate(); if (0 == Mount) { Error = -ENOMEM; goto exit; } File = (FILE *)VfsFileAllocate(sizeof *File, &FileCallbacks); if (0 == File) { Error = -ENOMEM; goto exit; } /* File: initialize fields. File->Base MUST be zeroed out. */ RtlZeroMemory(File, sizeof *File); File->Device = (DEVICE *)Device; File->Mount = Mount; ExInitializePushLock(&File->VolumeLock); File->VolumeId = InterlockedIncrement64(&StaticVolumeId); Mount->File = File; Mount = 0; *PFile = &File->Base; Error = 0; exit: if (0 != Mount) MountDereference(Mount); return Error; } static INT DeviceDelete( PLX_DEVICE Device0) { DEVICE *Device = (DEVICE *)Device0; MOUNT *Mount; for (PLIST_ENTRY Entry = Device->MountList.Flink; &Device->MountList != Entry;) { Mount = CONTAINING_RECORD(Entry, MOUNT, ListEntry); Entry = Entry->Flink; MountDereference(Mount); } return 0; } static EX_PUSH_LOCK FuseMiscLock; static LIST_ENTRY FuseMiscFileList; static KTIMER FuseMiscTimer; static KDPC FuseMiscTimerDpc; static WORK_QUEUE_ITEM FuseMiscTimerItem; static BOOLEAN FuseMiscTimerInitDone; static VOID FuseMiscFileListInsert(FILE *File) { ExAcquirePushLockExclusive(&FuseMiscLock); InsertTailList(&FuseMiscFileList, &File->ListEntry); ExReleasePushLockExclusive(&FuseMiscLock); } static VOID FuseMiscFileListRemove(FILE *File) { ExAcquirePushLockExclusive(&FuseMiscLock); RemoveEntryList(&File->ListEntry); ExReleasePushLockExclusive(&FuseMiscLock); } static MOUNT *FuseMiscFileListGetMount(DEVICE *Device, UINT64 VolumeId) { /* NOTE: * This function is assumed to be called with the Device->MountListLock * acquired. */ FILE *File; MOUNT *Mount; ExAcquirePushLockShared(&FuseMiscLock); Mount = 0; for (PLIST_ENTRY Entry = FuseMiscFileList.Flink; &FuseMiscFileList != Entry;) { File = CONTAINING_RECORD(Entry, FILE, ListEntry); Entry = Entry->Flink; if (File->Device == Device && File->VolumeId == VolumeId) { Mount = File->Mount; break; } } ExReleasePushLockShared(&FuseMiscLock); return Mount; } static VOID FuseMiscExpirationRoutine(PVOID Context) { UINT64 InterruptTime; FILE *File; InterruptTime = KeQueryInterruptTime(); ExAcquirePushLockShared(&FuseMiscLock); for (PLIST_ENTRY Entry = FuseMiscFileList.Flink; &FuseMiscFileList != Entry;) { File = CONTAINING_RECORD(Entry, FILE, ListEntry); Entry = Entry->Flink; FuseInstanceExpirationRoutine(File->FuseInstance, InterruptTime); } ExReleasePushLockShared(&FuseMiscLock); } static VOID FuseMiscTimerDpcRoutine(PKDPC Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) { // !PAGED_CODE(); ExQueueWorkItem(&FuseMiscTimerItem, DelayedWorkQueue); } static VOID FuseMiscTimerInit(VOID) { PAGED_CODE(); ExAcquirePushLockExclusive(&FuseMiscLock); if (!FuseMiscTimerInitDone) { KeInitializeTimer(&FuseMiscTimer); KeInitializeDpc(&FuseMiscTimerDpc, FuseMiscTimerDpcRoutine, 0); ExInitializeWorkItem(&FuseMiscTimerItem, FuseMiscExpirationRoutine, 0); LONG Period = 1000; /* 1000ms = 1s */ LARGE_INTEGER DueTime; DueTime.QuadPart = -10000LL * Period; KeSetTimerEx(&FuseMiscTimer, DueTime, Period, &FuseMiscTimerDpc); FuseMiscTimerInitDone = TRUE; } ExReleasePushLockExclusive(&FuseMiscLock); } INT FuseMiscRegister(PLX_INSTANCE Instance) { static LX_DEVICE_CALLBACKS DeviceCallbacks = { .Open = DeviceOpen, .Delete = DeviceDelete, }; DEVICE *Device = 0; INT Error; FuseMiscTimerInit(); Device = (DEVICE *)VfsDeviceMinorAllocate(&DeviceCallbacks, sizeof *Device); if (0 == Device) { Error = -ENOMEM; goto exit; } /* Device: initialize fields. Device->Base MUST NOT be zeroed out. */ ExInitializePushLock(&Device->MountListLock); InitializeListHead(&Device->MountList); LxpDevMiscRegister(Instance, &Device->Base, FUSE_MINOR); Error = 0; exit: if (0 != Device) VfsDeviceMinorDereference(&Device->Base); return Error; } VOID FuseMiscInitialize(VOID) { ExInitializePushLock(&FuseMiscLock); InitializeListHead(&FuseMiscFileList); } ================================================ FILE: src/wslfuse/driver.c ================================================ /** * @file wslfuse/driver.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include DRIVER_INITIALIZE DriverEntry; #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, DriverEntry) #endif NTSTATUS DriverEntry( PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { #if DBG if (!KD_DEBUGGER_NOT_PRESENT) DbgBreakPoint(); #endif FuseMiscInitialize(); return LxldrRegisterService(DriverObject, TRUE, FuseMiscRegister); } ================================================ FILE: src/wslfuse/driver.h ================================================ /** * @file wslfuse/driver.h * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef WSLFUSE_DRIVER_H_INCLUDED #define WSLFUSE_DRIVER_H_INCLUDED #include #include #include INT FuseMiscRegister(PLX_INSTANCE Instance); VOID FuseMiscInitialize(VOID); #endif ================================================ FILE: src/wslfuse/driver.inf.in ================================================ [Version] Signature = "$WINDOWS NT$" Class = Volume ClassGuid = {71a27cdd-812a-11d0-bec7-08002be2092f} CatalogFile = !CatalogFile! Provider = !Provider! [DestinationDirs] DefaultDestDir = 12 [DefaultInstall] CopyFiles = Driver.CopyFiles [Driver.CopyFiles] !DriverFile! [SourceDisksFiles] !DriverFile! = 1 [SourceDisksNames] 1 = Disk1 ================================================ FILE: src/wslfuse/version.rc ================================================ #include #define STR(x) STR_(x) #define STR_(x) #x VS_VERSION_INFO VERSIONINFO FILEVERSION MyVersionWithCommas PRODUCTVERSION MyVersionWithCommas FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0 #endif FILEOS VOS_NT FILETYPE VFT_DRV FILESUBTYPE VFT2_DRV_SYSTEM BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", STR(MyCompanyName) VALUE "FileDescription", STR(MyDescription) VALUE "FileVersion", STR(MyFullVersion) VALUE "InternalName", "wslfuse.sys" VALUE "LegalCopyright", STR(MyCopyright) VALUE "OriginalFilename", "wslfuse.sys" VALUE "ProductName", STR(MyProductName) VALUE "ProductVersion", STR(MyProductVersion) END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END ================================================ FILE: tools/DigiCert High Assurance EV Root CA.crt ================================================ -----BEGIN CERTIFICATE----- MIIFOzCCAyOgAwIBAgIKYSBNtAAAAAAAJzANBgkqhkiG9w0BAQUFADB/MQswCQYD VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3Nv ZnQgQ29kZSBWZXJpZmljYXRpb24gUm9vdDAeFw0xMTA0MTUxOTQ1MzNaFw0yMTA0 MTUxOTU1MzNaMGwxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMx GTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xKzApBgNVBAMTIkRpZ2lDZXJ0IEhp Z2ggQXNzdXJhbmNlIEVWIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw ggEKAoIBAQDGzOVz5vvUu+UtLTKm3+WBP8nNJUm2cSrD1ZQ0Z6IKHLBfaaZAscS3 so/QmKSpQVk609yU1jzbdDikSsxNJYL3SqVTEjju80ltcZF+Y7arpl/DpIT4T2JR vvjF7Ns4kuMG5QiRDMQoQVX7y1qJFX5x6DW/TXIJPb46OFBbdzEbjbPHJEWap6xt ABRaBLe6E+tRCphBQSJOZWGHgUFQpnlcid4ZSlfVLuZdHFMsfpjNGgYWpGhz0DQE E1yhcdNafFXbXmThN4cwVgTlEbQpgBLxeTmIogIRfCdmt4i3ePLKCqg4qwpkwr9m XZWEwaElHoddGlALIBLMQbtuC1E4uEvLAgMBAAGjgcswgcgwEQYDVR0gBAowCDAG BgRVHSAAMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSx PsNpA/i/RwHUmCYaCALvY2QrwzAfBgNVHSMEGDAWgBRi+wohW39DbhHaCVRQa/XS lnHxnjBVBgNVHR8ETjBMMEqgSKBGhkRodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20v cGtpL2NybC9wcm9kdWN0cy9NaWNyb3NvZnRDb2RlVmVyaWZSb290LmNybDANBgkq hkiG9w0BAQUFAAOCAgEAIIzBWe1vnGstwUo+dR1FTEFQHL2A6tmwkosGKhM/Uxae VjlqimO2eCR59X24uUehCpbC9su9omafBuGs0nkJDv083KwCDHCvPxvseH7U60sF YCbZc2GRIe2waGPglxKrb6AS7dmf0tonPLPkVvnR1IEPcb1CfKaJ3M3VvZWiq/GT EX3orDEpqF1mcEGd/HXJ1bMaOSrQhQVQi6yRysSTy3GlnaSUb1gM+m4gxAgxtYWd foH50j3KWxiFbAqG7CIJG6V0NE9/KLyVSqsdtpiwXQmkd3Z+76eOXYT2GCTL0W2m w6GcwhB1gP+dMv3mz0M6gvfOj+FyKptit1/tlRo5XC+UbUi3AV8zL7vcLXM0iQRC ChyLefmj+hfv+qEaEN/gssGV61wMBZc7NT4YiE3bbL8kiY3Ivdifezk6JKDV39Hz ShqX9qZveh+wkKmzrAE5kdNht2TxPlc4A6/OetK1kPWu3DmZ1bY8l+2myxbHfWsq TJCU5kxU/R7NIOzOaJyHWOlhYL7rDsnVGX2f6Xi9DqwhdQePqW7gjGoqa5zj52W8 vC08bdwE3GdFNjKvBIG8qABuYUyVxVzUjo6fL8EydL29EWUDB83vt14CV9qG1Boo NK+ISbLPpd2CVm9oqhTiWVT+/+ru7+qScCJggeMlI8CfzA9JsjWqWMM6w9kWlBA= -----END CERTIFICATE----- ================================================ FILE: tools/build-libfuse.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion if not X%1==X set Config=%1 if not X%2==X set Arch=%2 if not X%3==X set DESTDIR=%3 if X!Config!==X (echo usage: build-libfuse Config Arch [DestDir] >&2 & goto fail) if X!Config!==XDebug set Buildtype=debug if X!Config!==XRelease set Buildtype=release rem ninja uses DESTDIR for installation if not X!DESTDIR!==X ( if exist !DESTDIR! rmdir /s/q !DESTDIR! mkdir !DESTDIR! pushd !DESTDIR! set DESTDIR=!cd! popd ) set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" for /f "usebackq tokens=*" %%i in (`%vswhere% -find VC\**\vcvarsall.bat`) do ( call "%%i" !Arch! ) rem workaround getting Cygwin's meson/ninja set PATH=C:\Program Files\Meson;%PATH% cd %~dp0..\ext\libfuse if exist build\!Config!\!Arch! rmdir /s/q build\!Config!\!Arch! mkdir build\!Config!\!Arch! && cd build\!Config!\!Arch! meson --buildtype=!Buildtype! -D examples=false ..\..\.. if errorlevel 1 goto fail ninja if errorlevel 1 goto fail if not X!DestDir!==X ( ninja install if errorlevel 1 goto fail copy ..\..\..\LGPL2.txt !DestDir!\License.txt if errorlevel 1 goto fail ) rem The pkgconfig prefix in file !InstallDir!\lib\pkgconfig\fuse3.pc rem is erroneously set as: prefix=c:/ rem We should somehow set it to: prefix=${pcfiledir}/../.. exit /b 0 :fail exit /b 1 ================================================ FILE: tools/build-lxdk.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion if not X%1==X set Config=%1 if not X%2==X set DestDir=%2 if X!Config!==X (echo usage: build-lxdk Config [DestDir] >&2 & goto fail) if not X!DestDir!==X ( if exist !DestDir! rmdir /s/q !DestDir! mkdir !DestDir! pushd !DestDir! set DestDir=!cd! popd ) cd %~dp0.. call ext\lxdk\tools\build.bat %Config% if !ERRORLEVEL! neq 0 goto :fail if not X!DestDir!==X ( copy %~dp0..\ext\lxdk\build\VStudio\build\%Config%\lxdk-*.msi !DestDir! ) exit /b 0 :fail exit /b 1 ================================================ FILE: tools/build-sample.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion if not X%1==X set Config=%1 if not X%2==X set Arch=%2 if not X%3==X set Sample=%3 if not X%4==X set DestDir=%4 if X!Sample!==X (echo usage: build-sample Config Arch Sample [DestDir] >&2 & goto fail) set SampleProj= for /F "tokens=1,2 delims=*" %%k in ("!Sample!") do ( set Sample=%%k set SampleProj=%%l ) set SampleDir=%~dp0..\tst if not exist "!SampleDir!\!Sample!" (echo sample !Sample! not found >&2 & goto fail) if not X!DestDir!==X ( if exist !DestDir! rmdir /s/q !DestDir! mkdir !DestDir! cd !DestDir! xcopy /s/e/q/y "!SampleDir!\!Sample!" . ) else ( cd "!SampleDir!\!Sample!" ) set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" for /f "usebackq tokens=*" %%i in (`%vswhere% -find VC\**\vcvarsall.bat`) do ( call "%%i" x64 ) if exist build rmdir /s/q build if X!SampleProj!==X ( devenv "!Sample!.sln" /build "!Config!|!Arch!" ) else ( devenv "!Sample!.sln" /build "!Config!|!Arch!" /project "!SampleProj!" ) if !ERRORLEVEL! neq 0 goto :fail exit /b 0 :fail exit /b 1 ================================================ FILE: tools/build-winfsp.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion if not X%1==X set Config=%1 if not X%2==X set DestDir=%2 if X!Config!==X (echo usage: build-winfsp Config [DestDir] >&2 & goto fail) if not X!DestDir!==X ( if exist !DestDir! rmdir /s/q !DestDir! mkdir !DestDir! pushd !DestDir! set DestDir=!cd! popd ) set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" for /f "usebackq tokens=*" %%i in (`%vswhere% -find VC\**\vcvarsall.bat`) do ( call "%%i" x64 ) cd %~dp0.. set VS140COMNTOOLS= call ext\winfsp\tools\build.bat %Config% if !ERRORLEVEL! neq 0 goto :fail if not X!DestDir!==X ( copy %~dp0..\ext\winfsp\build\VStudio\build\%Config%\winfsp-*.msi !DestDir! copy %~dp0..\ext\winfsp\build\VStudio\build\%Config%\winfsp-tests-x64.exe !DestDir! ) exit /b 0 :fail exit /b 1 ================================================ FILE: tools/build.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion set MsiName="WinFuse - FUSE for the Windows kernel" set CrossCert="%~dp0DigiCert High Assurance EV Root CA.crt" set Issuer="DigiCert" set Subject="Navimatics LLC" set Configuration=Release set SignedPackage= if not X%1==X set Configuration=%1 if not X%2==X set SignedPackage=%2 set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" for /f "usebackq tokens=*" %%i in (`%vswhere% -find VC\**\vcvarsall.bat`) do ( call "%%i" x64 ) if not X%SignedPackage%==X ( if not exist "%~dp0..\build\VStudio\build\%Configuration%\winfuse-*.msi" (echo previous build not found >&2 & exit /b 1) if not exist "%SignedPackage%" (echo signed package not found >&2 & exit /b 1) del "%~dp0..\build\VStudio\build\%Configuration%\winfuse-*.msi" if exist "%~dp0..\build\VStudio\build\%Configuration%\winfuse.*.nupkg" del "%~dp0..\build\VStudio\build\%Configuration%\winfuse.*.nupkg" for /R "%SignedPackage%" %%f in (*.sys) do ( copy "%%f" "%~dp0..\build\VStudio\build\%Configuration%" >nul ) ) cd %~dp0..\build\VStudio set signfail=0 if X%SignedPackage%==X ( if exist build\ for /R build\ %%d in (%Configuration%) do ( if exist "%%d" rmdir /s/q "%%d" ) devenv winfuse.sln /build "%Configuration%|x64" if errorlevel 1 goto fail call %~dp0build-libfuse.bat %Configuration% x64 build\%Configuration%\libfuse\x64 if errorlevel 1 goto fail devenv winfuse.sln /build "%Configuration%|x86" if errorlevel 1 goto fail call %~dp0build-libfuse.bat %Configuration% x86 build\%Configuration%\libfuse\x86 if errorlevel 1 goto fail for %%f in (build\%Configuration%\winfuse-x64.sys build\%Configuration%\wslfuse-x64.sys build\%Configuration%\winfuse-x86.sys) do ( signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha1 /t http://timestamp.digicert.com %%f if errorlevel 1 set /a signfail=signfail+1 signtool sign /as /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha256 /tr http://timestamp.digicert.com /td sha256 %%f if errorlevel 1 set /a signfail=signfail+1 ) pushd build\%Configuration% echo .OPTION EXPLICIT >driver.ddf echo .Set CabinetFileCountThreshold=0 >>driver.ddf echo .Set FolderFileCountThreshold=0 >>driver.ddf echo .Set FolderSizeThreshold=0 >>driver.ddf echo .Set MaxCabinetSize=0 >>driver.ddf echo .Set MaxDiskFileCount=0 >>driver.ddf echo .Set MaxDiskSize=0 >>driver.ddf echo .Set CompressionType=MSZIP >>driver.ddf echo .Set Cabinet=on >>driver.ddf echo .Set Compress=on >>driver.ddf echo .Set CabinetNameTemplate=driver.cab >>driver.ddf echo .Set DiskDirectory1=. >>driver.ddf echo .Set DestinationDir=x64 >>driver.ddf echo winfuse-x64.inf >>driver.ddf echo winfuse-x64.sys >>driver.ddf echo wslfuse-x64.inf >>driver.ddf echo wslfuse-x64.sys >>driver.ddf echo .Set DestinationDir=x86 >>driver.ddf echo winfuse-x86.inf >>driver.ddf echo winfuse-x86.sys >>driver.ddf makecab /F driver.ddf signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /t http://timestamp.digicert.com driver.cab if errorlevel 1 set /a signfail=signfail+1 popd ) devenv winfuse.sln /build "Installer.%Configuration%|x64" if errorlevel 1 goto fail devenv winfuse.sln /build "Installer.%Configuration%|x86" if errorlevel 1 goto fail for %%f in (build\%Configuration%\winfuse-*.msi) do ( signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha1 /t http://timestamp.digicert.com /d %MsiName% %%f if errorlevel 1 set /a signfail=signfail+1 REM signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha256 /tr http://timestamp.digicert.com /td sha256 /d %MsiName% %%f REM if errorlevel 1 set /a signfail=signfail+1 ) if not %signfail%==0 echo SIGNING FAILED! The product has been successfully built, but not signed. exit /b 0 :fail exit /b 1 ================================================ FILE: tools/debug.bat ================================================ @echo off setlocal set DebugWorkspace=winfuse set DebugPort=50000 set DebugKey=1.1.1.1 set RegKey="HKLM\SOFTWARE\Microsoft\Windows Kits\Installed Roots" set RegVal="KitsRoot10" reg query %RegKey% /v %RegVal% >nul 2>&1 || (echo Cannot find Windows Kit >&2 & exit /b 1) for /f "tokens=2,*" %%i in ('reg query %RegKey% /v %RegVal% ^| findstr %RegVal%') do ( set KitRoot="%%j" ) start "%DebugWorkspace%" %KitRoot%\Debuggers\x64\windbg -W %DebugWorkspace% -k net:port=%DebugPort%,key=%DebugKey% ================================================ FILE: tools/deploy.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion set Config=Debug set Suffix=x64 set Deploy=C:\Deploy\winfuse set Target=Win10DBG set Chkpnt=winfuse if not X%1==X set Target=%1 if not X%2==X set Chkpnt=%2 ( echo sc create WinFsp type=filesys binPath=%%~dp0winfsp-%SUFFIX%.sys echo sc create LxLdr type=kernel binPath=%%~dp0lxldr.sys echo sc create WinFuse type=kernel binPath=%%~dp0winfuse-%SUFFIX%.sys echo sc create WslFuse type=kernel binPath=%%~dp0wslfuse-%SUFFIX%.sys echo reg add HKLM\Software\WinFsp\Fsext /v 00093118 /d "winfuse" /f /reg:32 echo reg add HKLM\Software\LxDK\Services\wslfuse /v Depends /d "winfsp" /f echo sc start winfsp echo sc start lxldr ) >%~dp0..\build\VStudio\build\%Config%\deploy-setup.bat (set LF=^ %=this line is empty=% ) ( set /p =sudo mknod /dev/fuse c 10 229!LF! set /p =sudo chmod a+w /dev/fuse!LF! set /p =sudo cp fusermount.out /usr/bin/fusermount!LF! set /p =sudo cp fusermount.out /usr/bin/fusermount3!LF! set /p =sudo cp fusermount-helper.exe /usr/bin/fusermount-helper.exe!LF! set /p =sudo chmod u+s /usr/bin/fusermount!LF! set /p =sudo chmod u+s /usr/bin/fusermount3!LF! ) %~dp0..\build\VStudio\build\%Config%\deploy-setup.sh if exist %~dp0..\ext\winfsp\build\VStudio\build\%Config% ( set WINFSP=%~dp0..\ext\winfsp\build\VStudio\build\%Config%\ ) else ( set RegKey="HKLM\SOFTWARE\WinFsp" set RegVal="InstallDir" reg query !RegKey! /v !RegVal! /reg:32 >nul 2>&1 if !ERRORLEVEL! equ 0 ( for /f "tokens=2,*" %%i in ('reg query !RegKey! /v !RegVal! /reg:32 ^| findstr !RegVal!') do ( set WINFSP=%%jbin\ ) ) if not exist "!WINFSP!" (echo cannot find WinFsp installation >&2 & goto fail) ) if exist %~dp0..\ext\lxdk\build\VStudio\build\%Config% ( set LXDK=%~dp0..\ext\lxdk\build\VStudio\build\%Config%\ ) else ( set RegKey="HKLM\SOFTWARE\LxDK" set RegVal="InstallDir" reg query !RegKey! /v !RegVal! >nul 2>&1 if !ERRORLEVEL! equ 0 ( for /f "tokens=2,*" %%i in ('reg query !RegKey! /v !RegVal! ^| findstr !RegVal!') do ( set LXDK=%%jbin\ ) ) if not exist "!LXDK!" (echo cannot find LxDK installation >&2 & goto fail) ) set MEMFS_FUSE3_EXE= if exist %~dp0..\tst\memfs-fuse3\build\%Config%\memfs-fuse3-x64.exe ( set MEMFS_FUSE3_EXE=memfs-fuse3-x64.exe fuse3-x64.dll ) set MEMFS_FUSE3_OUT= if exist %~dp0..\tst\memfs-fuse3\build\%Config%\memfs-fuse3.out ( set MEMFS_FUSE3_OUT=memfs-fuse3.out ) set Files= for %%f in ( %~dp0..\build\VStudio\build\%Config%\ winfuse-%Suffix%.sys wslfuse-%Suffix%.sys winfuse-tests-%Suffix%.exe wslfuse-tests.out fusermount.out fusermount-helper.exe deploy-setup.bat deploy-setup.sh %~dp0..\tst\memfs-fuse3\build\%Config%\ !MEMFS_FUSE3_EXE! !MEMFS_FUSE3_OUT! "!WINFSP!" winfsp-%Suffix%.sys winfsp-%Suffix%.dll "!LXDK!" lxldr.sys ) do ( set File=%%~f if [!File:~-1!] == [\] ( set Dir=!File! ) else ( if not [!Files!] == [] set Files=!Files!, set Files=!Files!'!Dir!!File!' ) ) powershell -NoProfile -ExecutionPolicy Bypass -Command "& '%~dp0deploy.ps1' -Name '%Target%' -CheckpointName '%Chkpnt%' -Files !Files! -Destination '%Deploy%'" ================================================ FILE: tools/deploy.ps1 ================================================ param ( [Parameter(Mandatory)][string]$Name, [string]$CheckpointName, [Parameter(Mandatory)][string[]]$Files, [Parameter(Mandatory)][string]$Destination ) function Restore-VM ($Name, $CheckpointName) { $VM = Get-VM -Name $Name if ($VM.State -eq "Running") { Stop-VM -Name $Name -TurnOff } if (-not $CheckpointName) { $Checkpoint = Get-VMCheckpoint -VMName $Name | Sort-Object -Property CreationTime -Descending | select -First 1 } else { $Checkpoint = Get-VMCheckpoint -VMName $Name -Name $CheckpointName } Restore-VMCheckpoint -VMCheckpoint $Checkpoint -Confirm:$false Start-VM -Name $Name } function Deploy-VMFiles ($Name, $Files, $Destination) { foreach ($File in $Files) { $Leaf = Split-Path -Path $File -Leaf $Dest = Join-Path $Destination $Leaf Copy-VMFile -Name $Name -SourcePath $File -DestinationPath $Dest -FileSource Host -CreateFullPath -Force } } Restore-VM -Name $Name -CheckpointName $CheckpointName Deploy-VMFiles -Name $Name -Files $Files -Destination $Destination ================================================ FILE: tools/gensrc/errno.sh ================================================ #!/bin/bash # run from Cygwin! gensrc() { echo "#if FUSE_ERRNO == 87 /* Windows */" echo vcvars="$(/mnt/c/Program\ Files\ \(x86\)/Microsoft\ Visual\ Studio/Installer/vswhere.exe -latest -find 'VC\**\vcvarsall.bat')" cmd /c "call" "$vcvars" "x64" "&&" cl /nologo /EP /C errno.src 2>/dev/null | sed -e '1,/beginbeginbeginbegin/d' -e 's/\r$//' echo echo "#elif FUSE_ERRNO == 67 /* Cygwin */" echo cpp -C -P errno.src | sed -e '1,/beginbeginbeginbegin/d' echo echo "#elif FUSE_ERRNO == 76 /* Linux */" echo # this produces very strange results without the intermediate file (GitHub microsoft/WSL#5063 ?) wsl -- cpp -C -P errno.src \| sed -e '1,/beginbeginbeginbegin/d' \> errno.out cat errno.out echo echo "#endif" } cd $(dirname "$0") pwd ( echo '#include ' echo '/*beginbeginbeginbegin*/' awk '{ printf "case %s: return %s;\n", $1, $2 }' errno.txt ) > errno.src gensrc > ../../src/shared/km/errno.i ( echo '#include ' echo '/*beginbeginbeginbegin*/' awk '{ printf "case %s: return \"%s\";\n", $1, $1 }' errno.txt ) > errno.src gensrc > ../../src/shared/km/errnosym.i rm errno.src errno.out ================================================ FILE: tools/gensrc/errno.txt ================================================ 0 STATUS_SUCCESS EPERM STATUS_ACCESS_DENIED ENOENT STATUS_OBJECT_NAME_NOT_FOUND ESRCH STATUS_PROCEDURE_NOT_FOUND EINTR STATUS_CANCELLED EIO STATUS_IO_DEVICE_ERROR ENXIO STATUS_FILE_INVALID E2BIG STATUS_INSUFFICIENT_RESOURCES ENOEXEC STATUS_INVALID_IMAGE_FORMAT EBADF STATUS_INVALID_HANDLE ENOMEM STATUS_INSUFFICIENT_RESOURCES EACCES STATUS_ACCESS_DENIED EFAULT STATUS_ACCESS_VIOLATION EBUSY STATUS_DEVICE_BUSY EEXIST STATUS_OBJECT_NAME_COLLISION EXDEV STATUS_NOT_SAME_DEVICE ENODEV STATUS_NO_SUCH_DEVICE ENOTDIR STATUS_NOT_A_DIRECTORY EISDIR STATUS_FILE_IS_A_DIRECTORY EINVAL STATUS_INVALID_PARAMETER ENFILE STATUS_TOO_MANY_OPENED_FILES EMFILE STATUS_TOO_MANY_OPENED_FILES EFBIG STATUS_DISK_FULL ENOSPC STATUS_DISK_FULL ESPIPE STATUS_INVALID_PARAMETER EROFS STATUS_MEDIA_WRITE_PROTECTED EMLINK STATUS_TOO_MANY_LINKS EPIPE STATUS_PIPE_BROKEN EDOM STATUS_INVALID_PARAMETER ERANGE STATUS_INVALID_PARAMETER EDEADLK STATUS_POSSIBLE_DEADLOCK ENAMETOOLONG STATUS_NAME_TOO_LONG ENOLCK STATUS_LOCK_NOT_GRANTED ENOSYS STATUS_INVALID_DEVICE_REQUEST ENOTEMPTY STATUS_DIRECTORY_NOT_EMPTY EILSEQ STATUS_INVALID_PARAMETER EADDRINUSE STATUS_ADDRESS_ALREADY_ASSOCIATED EALREADY STATUS_CONNECTION_ACTIVE ECANCELED STATUS_CANCELLED ECONNABORTED STATUS_CONNECTION_ABORTED ECONNREFUSED STATUS_CONNECTION_REFUSED ECONNRESET STATUS_CONNECTION_RESET EHOSTUNREACH STATUS_HOST_UNREACHABLE EISCONN STATUS_CONNECTION_ACTIVE ELOOP STATUS_REPARSE_POINT_NOT_RESOLVED ENETDOWN STATUS_HOST_DOWN ENETRESET STATUS_CONNECTION_RESET ENETUNREACH STATUS_NETWORK_UNREACHABLE ENOBUFS STATUS_INSUFFICIENT_RESOURCES ENODATA STATUS_END_OF_FILE ENOLINK STATUS_CONNECTION_INVALID ENOTCONN STATUS_CONNECTION_INVALID ENOTSOCK STATUS_INVALID_HANDLE ETIMEDOUT STATUS_TRANSACTION_TIMED_OUT ================================================ FILE: tools/ioc.c ================================================ ///usr/bin/gcc -o /tmp/ioc.$$ "$0"; /tmp/ioc.$$ "$@"; rm /tmp/ioc.$$; exit // usage: sh ioc.c dir typ num siz #include #include #include int main(int argc, char *argv[]) { unsigned dir, typ, num, siz; if (5 != argc) { fprintf(stderr, "usage: sh ioc.c dir typ num siz\n"); exit(2); } dir = strtoul(argv[1], 0, 0); typ = strtoul(argv[2], 0, 0); num = strtoul(argv[3], 0, 0); siz = strtoul(argv[4], 0, 0); printf( "dir=%u typ=%u num=%u siz=%u\n" "ioc=0x%08x\n", dir, typ, num, siz, _IOC(dir, typ, num, siz)); return 0; } ================================================ FILE: tools/license-headers/fix.ps1 ================================================ #!/usr/bin/env powershell param ( [Parameter(Mandatory=$true)][string]$srcfile, [string]$dstfile = $srcfile ) $content = Get-Content -Raw $srcfile $fileext = [System.IO.Path]::GetExtension($srcfile) $lichead = Get-Content -Raw "$PSScriptRoot\header$fileext" $content = $content -replace "(?sm)/\*((?!\*/).)*This file is part of((?!\*/).)*\*/", $lichead Set-Content -Path $dstfile -NoNewline -Value $content ================================================ FILE: tools/license-headers/header.c ================================================ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ ================================================ FILE: tools/license-headers/header.cpp ================================================ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ ================================================ FILE: tools/license-headers/header.h ================================================ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ ================================================ FILE: tools/nmake-ext-test.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" for /f "usebackq tokens=*" %%i in (`%vswhere% -find VC\**\vcvarsall.bat`) do ( call "%%i" x64 ) cd %~dp0..\ext\winfsp\ext\test nmake /f Nmakefile ================================================ FILE: tools/run-tests.bat ================================================ @echo off setlocal setlocal EnableDelayedExpansion set Configuration=Release if not X%1==X set Configuration=%1 cd %~dp0.. set ProjRoot=%cd% cd build\VStudio if not exist build\%Configuration% echo === No tests found >&2 & goto fail cd build\%Configuration% set dfl_tests=^ winfuse-tests-x64 ^ winfuse-tests-x86 ^ wslfuse-tests set opt_tests=^ sample-build-memfs-fuse3-x64 ^ sample-test0-memfs-fuse3-x64 ^ sample-test1-memfs-fuse3-x64 ^ sample-testinf-memfs-fuse3-x64 ^ sample-fsx0-memfs-fuse3-x64 ^ sample-fsx1-memfs-fuse3-x64 ^ sample-fsxinf-memfs-fuse3-x64 ^ sample-build-memfs-fuse3-x86 ^ sample-test0-memfs-fuse3-x86 ^ sample-test1-memfs-fuse3-x86 ^ sample-testinf-memfs-fuse3-x86 ^ sample-fsx0-memfs-fuse3-x86 ^ sample-fsx1-memfs-fuse3-x86 ^ sample-fsxinf-memfs-fuse3-x86 ^ sample-build-memfs-fuse3-wsl REM disable WSL tests that do not pass on AppVeyor (because it uses old Windows/WSL build) REM sample-test0-memfs-fuse3-wsl ^ REM sample-test1-memfs-fuse3-wsl ^ REM sample-testinf-memfs-fuse3-wsl ^ REM sample-fsx0-memfs-fuse3-wsl ^ REM sample-fsx1-memfs-fuse3-wsl ^ REM sample-fsxinf-memfs-fuse3-wsl set tests= for %%f in (%dfl_tests%) do ( if X%2==X ( set tests=!tests! %%f ) else ( set test=%%f if not "X!test:%2=!"=="X!test!" set tests=!tests! %%f ) ) for %%f in (%opt_tests%) do ( if X%2==X ( rem ) else ( set test=%%f if not "X!test:%2=!"=="X!test!" set tests=!tests! %%f ) ) set testpass=0 set testfail=0 for %%f in (%tests%) do ( echo === Running %%f if defined APPVEYOR ( appveyor AddTest "%%f" -FileName None -Framework None -Outcome Running ) pushd %cd% call :%%f popd if !ERRORLEVEL! neq 0 ( set /a testfail=testfail+1 echo === Failed %%f if defined APPVEYOR ( appveyor UpdateTest "%%f" -FileName None -Framework None -Outcome Failed -Duration 0 ) ) else ( set /a testpass=testpass+1 echo === Passed %%f if defined APPVEYOR ( appveyor UpdateTest "%%f" -FileName None -Framework None -Outcome Passed -Duration 0 ) ) echo: ) set /a total=testpass+testfail echo === Total: %testpass%/%total% call :leak-test if !ERRORLEVEL! neq 0 goto fail if not %testfail%==0 goto fail exit /b 0 :fail exit /b 1 :winfuse-tests-x64 winfuse-tests-x64 +* if !ERRORLEVEL! neq 0 goto fail exit /b 0 :winfuse-tests-x86 winfuse-tests-x86 +* if !ERRORLEVEL! neq 0 goto fail exit /b 0 :wslfuse-tests wsl -- sudo mknod /dev/fuse c 10 229; sudo ./wslfuse-tests.out if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-build-memfs-fuse3-x64 call :__run_sample_build memfs-fuse3 memfs-fuse3.exe x64 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-build-memfs-fuse3-x86 call :__run_sample_build memfs-fuse3 memfs-fuse3.exe x86 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-build-memfs-fuse3-wsl call :__run_sample_build memfs-fuse3 memfs-fuse3.out x64 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :__run_sample_build call %ProjRoot%\tools\build-sample.bat %Configuration% %3 %1*%2 "%TMP%\%1" if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-test0-memfs-fuse3-x64 call :__run_sample_test memfs-fuse3 x64 0 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-test1-memfs-fuse3-x64 call :__run_sample_test memfs-fuse3 x64 1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-testinf-memfs-fuse3-x64 call :__run_sample_test memfs-fuse3 x64 -1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-test0-memfs-fuse3-x86 call :__run_sample_test memfs-fuse3 x86 0 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-test1-memfs-fuse3-x86 call :__run_sample_test memfs-fuse3 x86 1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-testinf-memfs-fuse3-x86 call :__run_sample_test memfs-fuse3 x86 -1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :__run_sample_test set TestExit=0 start "" /b "%TMP%\%1\build\%Configuration%\%1-%2.exe" -oFileInfoTimeout=%3 L: waitfor 7BF47D72F6664550B03248ECFE77C7DD /t 3 2>nul pushd >nul cd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail) L: "C:\Program Files (x86)\WinFsp\bin\winfsp-tests-x64.exe" ^ --external --resilient ^ create_test create_related_test create_sd_test create_notraverse_test create_backup_test ^ create_restore_test create_share_test create_curdir_test create_namelen_test ^ getfileinfo_test delete_test delete_pending_test delete_mmap_test delete_standby_test ^ rename_* ^ getvolinfo_test ^ getsecurity_test ^ rdwr_* ^ flush_* ^ lock_* ^ querydir_* ^ dirnotify_test ^ exec_* if !ERRORLEVEL! neq 0 set TestExit=1 popd taskkill /f /im %1-%2.exe exit /b !TestExit! :sample-fsx0-memfs-fuse3-x64 call :__run_sample_fsx_test memfs-fuse3 x64 0 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsx1-memfs-fuse3-x64 call :__run_sample_fsx_test memfs-fuse3 x64 1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsxinf-memfs-fuse3-x64 call :__run_sample_fsx_test memfs-fuse3 x64 -1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsx0-memfs-fuse3-x86 call :__run_sample_fsx_test memfs-fuse3 x86 0 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsx1-memfs-fuse3-x86 call :__run_sample_fsx_test memfs-fuse3 x86 1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsxinf-memfs-fuse3-x86 call :__run_sample_fsx_test memfs-fuse3 x86 -1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :__run_sample_fsx_test set TestExit=0 start "" /b "%TMP%\%1\build\%Configuration%\%1-%2.exe" -oFileInfoTimeout=%3 L: waitfor 7BF47D72F6664550B03248ECFE77C7DD /t 3 2>nul pushd >nul cd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail) L: "%ProjRoot%\ext\winfsp\ext\test\fstools\src\fsx\fsx.exe" -N 5000 test xxxxxx if !ERRORLEVEL! neq 0 set TestExit=1 popd taskkill /f /im %1-%2.exe exit /b !TestExit! :sample-test0-memfs-fuse3-wsl call :__run_sample_wsl_test memfs-fuse3 0 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-test1-memfs-fuse3-wsl call :__run_sample_wsl_test memfs-fuse3 1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-testinf-memfs-fuse3-wsl call :__run_sample_wsl_test memfs-fuse3 -1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :__run_sample_wsl_test set TestExit=0 start "" /b /d "%TMP%\%1\build\%Configuration%" wsl -- sudo sh "/mnt/c/Program Files/WinFuse/opt/wslfuse/install.sh"; mkdir -p mnt; ./%1.out -f -ocontext=FileInfoTimeout=%2,context=Volume=L: mnt waitfor 7BF47D72F6664550B03248ECFE77C7DD /t 10 2>nul pushd >nul cd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail) L: "C:\Program Files (x86)\WinFsp\bin\winfsp-tests-x64.exe" ^ --external --resilient ^ create_test create_related_test create_sd_test create_notraverse_test create_backup_test ^ create_restore_test create_share_test create_curdir_test create_namelen_test ^ getfileinfo_test delete_test delete_pending_test delete_mmap_test delete_standby_test ^ rename_* ^ getvolinfo_test ^ getsecurity_test ^ rdwr_* ^ flush_* ^ lock_* ^ querydir_* ^ dirnotify_test ^ exec_* if !ERRORLEVEL! neq 0 set TestExit=1 popd start "" /b /d "%TMP%\%1\build\%Configuration%" wsl -- fusermount3 -u mnt exit /b !TestExit! :sample-fsx0-memfs-fuse3-wsl call :__run_sample_fsx_wsl_test memfs-fuse3 0 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsx1-memfs-fuse3-wsl call :__run_sample_fsx_wsl_test memfs-fuse3 1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :sample-fsxinf-memfs-fuse3-wsl call :__run_sample_fsx_wsl_test memfs-fuse3 -1 if !ERRORLEVEL! neq 0 goto fail exit /b 0 :__run_sample_fsx_wsl_test set TestExit=0 start "" /b /d "%TMP%\%1\build\%Configuration%" wsl -- sudo sh "/mnt/c/Program Files/WinFuse/opt/wslfuse/install.sh"; mkdir -p mnt; ./%1.out -f -ocontext=FileInfoTimeout=%2,context=Volume=L: mnt waitfor 7BF47D72F6664550B03248ECFE77C7DD /t 10 2>nul pushd >nul cd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail) L: "%ProjRoot%\ext\winfsp\ext\test\fstools\src\fsx\fsx.exe" -N 5000 test xxxxxx if !ERRORLEVEL! neq 0 set TestExit=1 popd start "" /b /d "%TMP%\%1\build\%Configuration%" wsl -- fusermount3 -u mnt exit /b !TestExit! :leak-test rem wait a bit to avoid reporting lingering allocations waitfor 7BF47D72F6664550B03248ECFE77C7DD /t 3 2>nul for /F "tokens=1,2 delims=:" %%i in ('verifier /query ^| findstr ^ /c:"Current Pool Allocations:" ^ /c:"CurrentPagedPoolAllocations:" ^ /c:"CurrentNonPagedPoolAllocations:"' ) do ( set FieldName=%%i set FieldName=!FieldName: =! set FieldValue=%%j set FieldValue=!FieldValue: =! set FieldValue=!FieldValue:^(=! set FieldValue=!FieldValue:^)=! if X!FieldName!==XCurrentPoolAllocations ( for /F "tokens=1,2 delims=/" %%k in ("!FieldValue!") do ( set NonPagedAlloc=%%k set PagedAlloc=%%l ) ) else if X!FieldName!==XCurrentPagedPoolAllocations ( set PagedAlloc=!FieldValue! ) else if X!FieldName!==XCurrentNonPagedPoolAllocations ( set NonPagedAlloc=!FieldValue! ) ) set /A TotalAlloc=PagedAlloc+NonPagedAlloc if !TotalAlloc! equ 0 ( echo === Leaks: None ) else ( echo === Leaks: !NonPagedAlloc! NP / !PagedAlloc! P goto fail ) exit /b 0 ================================================ FILE: tst/lockdly/lockdly.c ================================================ /* * Description: * On debug builds of the WinFuse driver, when the special file \$LOCKDLY is created/opened * an artificial delay is introduced. This allows enough time for forcible termination of the * file system (e.g. using Ctrl-C). If using non-alertable locks (kernel ERESOURCE) then the * file system process should become unkillable and the lockdly.exe process should hang. If our * custom implementation of alertable read-write locks (using semaphores and alertable waits) * is used, then this should not happen. * * Compile: * - cl lockdly.c * * Reproduce: * - lockdly.exe * - Quickly kill the file system process (e.g. switch to its command windows and Ctrl-C). * * Correct behavior: * - Normal program termination. * * Incorrect behavior: * - File system process and/or lockdly.exe process hang and become unkillable. */ #include DWORD WINAPI ThreadProc(PVOID Param) { HANDLE Handle = CreateFileW( L"$LOCKDLY", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, 0); if (INVALID_HANDLE_VALUE == Handle) return 1; return 0; } int wmain(int argc, wchar_t *argv[]) { HANDLE Thread = CreateThread(0, 0, ThreadProc, 0, 0, 0); if (0 == Thread) return 1; Sleep(1000); HANDLE Handle = CreateFileW( L"$LOCKDLY", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0, 0); if (INVALID_HANDLE_VALUE == Handle) return 1; WaitForSingleObject(Thread, INFINITE); DWORD ExitCode; GetExitCodeThread(Thread, &ExitCode); return ExitCode; } ================================================ FILE: tst/memfs-fuse3/.gitignore ================================================ build *.ncb *.suo *.vcproj.* *.vcxproj.user *.VC.db *.VC.opendb .vs *.exe *.install ================================================ FILE: tst/memfs-fuse3/compat.h ================================================ /** * @file compat.h * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #ifndef COMPAT_H_INCLUDED #define COMPAT_H_INCLUDED #if defined(_WIN32) && defined(FSP_FUSE_SYM) #include #undef fuse_main #define fuse_main(argc, argv, ops, data)\ (FspLoad(0), fuse_main_real(argc, argv, ops, sizeof *(ops), data)) #endif #if !defined(_WIN32) && !defined(fuse_stat) typedef uint64_t fuse_ino_t; #define fuse_uid_t uid_t #define fuse_gid_t gid_t #define fuse_pid_t pid_t #define fuse_dev_t dev_t #define fuse_mode_t mode_t #define fuse_nlink_t nlink_t #define fuse_off_t off_t #define fuse_fsblkcnt_t fsblkcnt_t #define fuse_fsfilcnt_t fsfilcnt_t #define fuse_blksize_t blksize_t #define fuse_blkcnt_t blkcnt_t #define fuse_timespec timespec #define fuse_stat stat #define fuse_statvfs statvfs #define fuse_flock flock #define fuse_iovec iovec #endif #if !defined(S_IFMT) #define S_IFMT 0170000 #endif #if !defined(S_IFDIR) #define S_IFDIR 0040000 #endif #if !defined(S_IFCHR) #define S_IFCHR 0020000 #endif #if !defined(S_IFBLK) #define S_IFBLK 0060000 #endif #if !defined(S_IFREG) #define S_IFREG 0100000 #endif #if !defined(S_IFLNK) #define S_IFLNK 0120000 #endif #if !defined(S_IFSOCK) #define S_IFSOCK 0140000 #endif #if !defined(S_IFIFO) #define S_IFIFO 0010000 #endif #if defined(__APPLE__) #define st_atim st_atimespec #define st_ctim st_ctimespec #define st_mtim st_mtimespec #endif #if defined(__APPLE__) || defined(__linux__) || defined(__CYGWIN__) #include #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(_WIN32) #define XATTR_CREATE 1 #define XATTR_REPLACE 2 #endif #if !defined(ENOATTR) #define ENOATTR ENODATA #elif !defined(ENODATA) #define ENODATA ENOATTR #endif #endif ================================================ FILE: tst/memfs-fuse3/memfs-fuse3.cpp ================================================ /** * @file memfs-fuse3.cpp * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include #include #include #include #include #include #include #include #include #include "compat.h" class memfs { public: memfs() : _ino(1), _root(std::make_shared(_ino, S_IFDIR | 00777, 0, 0)) { } int main(int argc, char *argv[]) { static fuse_operations ops = { getattr, readlink, mknod, mkdir, unlink, rmdir, symlink, rename, link, chmod, chown, truncate, open, read, write, statfs, flush, release, 0, // fsync setxattr, getxattr, listxattr, removexattr, opendir, readdir, releasedir, 0, // fsyncdir init, 0, // destroy 0, // access 0, // create 0, // lock utimens, 0, // bmap #if 0 ioctl, #endif }; return fuse_main(argc, argv, &ops, this); } private: struct node_t { node_t(fuse_ino_t ino, fuse_mode_t mode, fuse_uid_t uid, fuse_gid_t gid, fuse_dev_t dev = 0) : stat() { stat.st_ino = ino; stat.st_mode = mode; stat.st_nlink = 1; stat.st_uid = uid; stat.st_gid = gid; stat.st_rdev = dev; stat.st_atim = stat.st_mtim = stat.st_ctim = now(); } void resize(size_t size, bool capacity) { if (capacity) { const size_t unit = 64 * 1024; size_t newcap = (size + unit - 1) / unit * unit; size_t oldcap = data.capacity(); if (newcap > oldcap) data.reserve(newcap); else if (newcap < oldcap) { data.resize(newcap); data.shrink_to_fit(); } } data.resize(size); stat.st_size = size; } struct fuse_stat stat; std::vector data; std::unordered_map> childmap; std::unordered_map> xattrmap; }; static fuse_timespec now() { using namespace std::chrono; auto now = system_clock::now(); auto sec = floor(now); auto nsec = floor(now) - floor(sec); return fuse_timespec { static_cast(sec.time_since_epoch().count()), /* std::chrono epoch is UNIX epoch in C++20 */ static_cast(nsec.count()), }; } static memfs *getself() { return static_cast(fuse_get_context()->private_data); } static int getattr(const char *path, struct fuse_stat *stbuf, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; *stbuf = node->stat; return 0; } static int readlink(const char *path, char *buf, size_t size) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path); if (!node) return -ENOENT; if (S_IFLNK != (node->stat.st_mode & S_IFMT)) return EINVAL; size = (std::min)(size - 1, node->data.size()); std::memcpy(buf, node->data.data(), size); buf[size] = '\0'; return 0; } static int mknod(const char *path, fuse_mode_t mode, fuse_dev_t dev) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->make_node(path, mode, dev); } static int mkdir(const char *path, fuse_mode_t mode) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->make_node(path, S_IFDIR | (mode & 07777), 0); } static int unlink(const char *path) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->remove_node(path, false); } static int rmdir(const char *path) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->remove_node(path, true); } static int symlink(const char *dstpath, const char *srcpath) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->make_node(srcpath, S_IFLNK | 00777, 0, dstpath); } static int rename(const char *oldpath, const char *newpath, unsigned int flags) { auto self = getself(); std::lock_guard lock(self->_mutex); auto oldlookup = self->lookup_node(oldpath); auto oldprnt = std::get<0>(oldlookup); auto oldname = std::get<1>(oldlookup); auto oldnode = std::get<2>(oldlookup); if (!oldnode) return -ENOENT; auto newlookup = self->lookup_node(newpath); auto newprnt = std::get<0>(newlookup); auto newname = std::get<1>(newlookup); auto newnode = std::get<2>(newlookup); if (!newprnt) return -ENOENT; if (newname.empty()) // guard against directory loop creation return -EINVAL; if (oldprnt == newprnt && oldname == newname) return 0; if (newnode) { if (int errc = self->remove_node(newpath, S_IFDIR == (oldnode->stat.st_mode & S_IFMT))) return errc; } oldprnt->childmap.erase(oldname); newprnt->childmap[newname] = oldnode; return 0; } static int link(const char *oldpath, const char *newpath) { auto self = getself(); std::lock_guard lock(self->_mutex); auto oldlookup = self->lookup_node(oldpath); auto oldnode = std::get<2>(oldlookup); if (!oldnode) return -ENOENT; auto newlookup = self->lookup_node(newpath); auto newprnt = std::get<0>(newlookup); auto newname = std::get<1>(newlookup); auto newnode = std::get<2>(newlookup); if (!newprnt) return -ENOENT; if (newnode) return -EEXIST; oldnode->stat.st_nlink++; newprnt->childmap[newname] = oldnode; oldnode->stat.st_ctim = newprnt->stat.st_ctim = newprnt->stat.st_mtim = now(); return 0; } static int chmod(const char *path, fuse_mode_t mode, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; node->stat.st_mode = (node->stat.st_mode & S_IFMT) | (mode & 07777); node->stat.st_ctim = now(); return 0; } static int chown(const char *path, fuse_uid_t uid, fuse_gid_t gid, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; if (-1 != uid) node->stat.st_uid = uid; if (-1 != gid) node->stat.st_gid = gid; node->stat.st_ctim = now(); return 0; } static int truncate(const char *path, fuse_off_t size, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; if (SIZE_MAX < size) return -EFBIG; node->resize(static_cast(size), true); node->stat.st_ctim = node->stat.st_mtim = now(); return 0; } static int open(const char *path, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->open_node(path, false, fi); } static int read(const char *path, char *buf, size_t size, fuse_off_t off, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; fuse_off_t endoff = (std::min)( off + static_cast(size), static_cast(node->data.size())); if (off > endoff) return 0; std::memcpy(buf, node->data.data() + off, static_cast(endoff - off)); node->stat.st_atim = now(); return static_cast(endoff - off); } static int write(const char *path, const char *buf, size_t size, fuse_off_t off, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; fuse_off_t endoff = off + static_cast(size); if (SIZE_MAX < endoff) return -EFBIG; if (node->data.size() < endoff) node->resize(static_cast(endoff), true); std::memcpy(node->data.data() + off, buf, static_cast(endoff - off)); node->stat.st_ctim = node->stat.st_mtim = now(); return static_cast(endoff - off); } static int statfs(const char *path, struct fuse_statvfs *stbuf) { std::memset(stbuf, 0, sizeof *stbuf); return 0; } static int flush(const char *path, struct fuse_file_info *fi) { return -ENOSYS; } static int release(const char *path, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->close_node(fi); } static int setxattr(const char *path, const char *name0, const char *value, size_t size, int flags) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path); if (!node) return -ENOENT; if (0 == std::strcmp("com.apple.ResourceFork", name0)) return -ENOTSUP; std::string name = name0; if (XATTR_CREATE == flags) { if (node->xattrmap.end() != node->xattrmap.find(name)) return -EEXIST; } else if (XATTR_REPLACE == flags) { if (node->xattrmap.end() == node->xattrmap.find(name)) return -ENOATTR; } node->xattrmap[name].assign(value, value + size); return 0; } static int getxattr(const char *path, const char *name0, char *value, size_t size) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path); if (!node) return -ENOENT; if (0 == std::strcmp("com.apple.ResourceFork", name0)) return -ENOTSUP; std::string name = name0; auto iter = node->xattrmap.find(name); if (node->xattrmap.end() == iter) return -ENOATTR; if (0 != size) { if (iter->second.size() > size) return -ERANGE; std::memcpy(value, iter->second.data(), iter->second.size()); } return static_cast(iter->second.size()); } static int listxattr(const char *path, char *namebuf, size_t size) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path); if (!node) return -ENOENT; size_t copysize = 0; for (auto elem : node->xattrmap) { size_t namesize = elem.first.size() + 1; if (0 != size) { if (copysize + namesize > size) return -ERANGE; std::memcpy(namebuf + copysize, elem.first.c_str(), namesize); copysize += namesize; } } return static_cast(copysize); } static int removexattr(const char *path, const char *name0) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path); if (!node) return -ENOENT; if (0 == std::strcmp("com.apple.ResourceFork", name0)) return -ENOTSUP; std::string name = name0; return node->xattrmap.erase(name) ? 0 : -ENOATTR; } static int opendir(const char *path, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->open_node(path, true, fi); } static int readdir(const char *path, void *buf, fuse_fill_dir_t filler, fuse_off_t off, struct fuse_file_info *fi, enum fuse_readdir_flags) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; filler(buf, ".", &node->stat, 0, FUSE_FILL_DIR_PLUS); filler(buf, "..", nullptr, 0, FUSE_FILL_DIR_PLUS); for (auto elem : node->childmap) if (0 != filler(buf, elem.first.c_str(), &elem.second->stat, 0, FUSE_FILL_DIR_PLUS)) break; return 0; } static int releasedir(const char *path, struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); return self->close_node(fi); } static void *init(struct fuse_conn_info *conn, struct fuse_config *conf) { conn->want |= (conn->capable & FUSE_CAP_READDIRPLUS); return getself(); } static int utimens(const char *path, const struct fuse_timespec tmsp[2], struct fuse_file_info *fi) { auto self = getself(); std::lock_guard lock(self->_mutex); auto node = self->get_node(path, fi); if (!node) return -ENOENT; if (tmsp) { node->stat.st_ctim = now(); node->stat.st_atim = tmsp[0]; node->stat.st_mtim = tmsp[1]; } else node->stat.st_ctim = node->stat.st_atim = node->stat.st_mtim = now(); return 0; } #if 0 static int ioctl(const char *path, int cmd, void *arg, struct fuse_file_info *fi, unsigned int flags, void *data) { return -ENOSYS; } #endif std::tuple, std::string, std::shared_ptr> lookup_node(const char *path, node_t *ancestor = nullptr) { auto prnt = _root; std::string name; auto node = prnt; for (const char *part = path, *p; *part; part = p + !!(*p)) { for (p = part; *p && '/' != *p; p++) ; if (part == p) continue; prnt = node; if (!node) break; name.assign(part, p); auto iter = node->childmap.find(name); node = node->childmap.end() != iter ? iter->second : nullptr; if (ancestor && node.get() == ancestor) { name.assign(""); // special case loop condition break; } } return std::make_tuple(prnt, name, node); } int make_node(const char *path, fuse_mode_t mode, fuse_dev_t dev, const char *data = nullptr) { auto lookup = lookup_node(path); auto prnt = std::get<0>(lookup); auto name = std::get<1>(lookup); auto node = std::get<2>(lookup); if (!prnt) return -ENOENT; if (node) return -EEXIST; fuse_context *context = fuse_get_context(); node = std::make_shared(++_ino, mode, context->uid, context->gid, dev); if (data) { node->resize(std::strlen(data), false); std::memcpy(node->data.data(), data, node->data.size()); } prnt->childmap[name] = node; prnt->stat.st_ctim = prnt->stat.st_mtim = node->stat.st_ctim; return 0; } int remove_node(const char *path, bool dir) { auto lookup = lookup_node(path); auto prnt = std::get<0>(lookup); auto name = std::get<1>(lookup); auto node = std::get<2>(lookup); if (!node) return -ENOENT; if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT)) return -EISDIR; if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT)) return -ENOTDIR; if (0 < node->childmap.size()) return -ENOTEMPTY; node->stat.st_nlink--; prnt->childmap.erase(name); node->stat.st_ctim = prnt->stat.st_ctim = prnt->stat.st_mtim = now(); return 0; } int open_node(const char *path, bool dir, struct fuse_file_info *fi) { auto node = std::get<2>(lookup_node(path)); if (!node) return -ENOENT; if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT)) return -EISDIR; if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT)) return -ENOTDIR; // A file descriptor is a raw pointer to a shared_ptr. // This has the effect of incrementing the shared_ptr // refcount, thus keeping an open node around even // if the node is unlinked. fi->fh = (uint64_t)(uintptr_t)new std::shared_ptr(node); return 0; } int close_node(struct fuse_file_info *fi) { delete (std::shared_ptr *)(uintptr_t)fi->fh; return 0; } std::shared_ptr get_node(const char *path, struct fuse_file_info *fi = nullptr) { if (!fi || !fi->fh) return std::get<2>(lookup_node(path)); else return *(std::shared_ptr *)(uintptr_t)fi->fh; } private: std::mutex _mutex; fuse_ino_t _ino; std::shared_ptr _root; }; int main(int argc, char *argv[]) { return memfs().main(argc, argv); } ================================================ FILE: tst/memfs-fuse3/memfs-fuse3.exe.vcxproj ================================================  Debug Win32 Release Win32 Debug x64 Release x64 {CF538F42-C714-4653-B351-E72FD7B0B217} Win32Proj memfsfuse3 $(LatestTargetPlatformVersion) Application true $(DefaultPlatformToolset) Unicode Application false $(DefaultPlatformToolset) true Unicode Application true $(DefaultPlatformToolset) Unicode Application false $(DefaultPlatformToolset) true Unicode true $(SolutionDir)build\$(Configuration)\ $(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\ $(SolutionName)-$(PlatformTarget) true $(SolutionDir)build\$(Configuration)\ $(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\ $(SolutionName)-$(PlatformTarget) false $(SolutionDir)build\$(Configuration)\ $(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\ $(SolutionName)-$(PlatformTarget) false $(SolutionDir)build\$(Configuration)\ $(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\ $(SolutionName)-$(PlatformTarget) Level3 Disabled FUSE_USE_VERSION=32;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true C:\Program Files\WinFuse\opt\libfuse\include\fuse3 MultiThreadedDebug 4018 Console true C:\Program Files\WinFuse\opt\libfuse\lib\fuse3-$(PlatformTarget).lib copy "C:\Program Files\WinFuse\opt\libfuse\bin\fuse3-$(PlatformTarget).dll" $(OutDir) Level3 Disabled FUSE_USE_VERSION=32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true C:\Program Files\WinFuse\opt\libfuse\include\fuse3 MultiThreadedDebug 4018 Console true C:\Program Files\WinFuse\opt\libfuse\lib\fuse3-$(PlatformTarget).lib copy "C:\Program Files\WinFuse\opt\libfuse\bin\fuse3-$(PlatformTarget).dll" $(OutDir) Level3 MaxSpeed true true FUSE_USE_VERSION=32;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true C:\Program Files\WinFuse\opt\libfuse\include\fuse3 MultiThreaded 4018 Console true true true C:\Program Files\WinFuse\opt\libfuse\lib\fuse3-$(PlatformTarget).lib copy "C:\Program Files\WinFuse\opt\libfuse\bin\fuse3-$(PlatformTarget).dll" $(OutDir) Level3 MaxSpeed true true FUSE_USE_VERSION=32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true C:\Program Files\WinFuse\opt\libfuse\include\fuse3 MultiThreaded 4018 Console true true true C:\Program Files\WinFuse\opt\libfuse\lib\fuse3-$(PlatformTarget).lib copy "C:\Program Files\WinFuse\opt\libfuse\bin\fuse3-$(PlatformTarget).dll" $(OutDir) ================================================ FILE: tst/memfs-fuse3/memfs-fuse3.exe.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx Source Source ================================================ FILE: tst/memfs-fuse3/memfs-fuse3.out.vcxproj ================================================  Debug x64 Release x64 {38ad1d24-7745-4b6e-9928-bd9731fed72a} Linux memfs_fuse3_out 15.0 Linux 1.0 Generic {2238F9CD-F817-4ECC-BD14-2524D2669B35} true WSL_1_0 false WSL_1_0 $(SolutionDir)build\$(Configuration)\ $(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\ $(SolutionName) $(SolutionDir)build\$(Configuration)\ $(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\ $(SolutionName) /usr/include/fuse3;%(AdditionalIncludeDirectories) FUSE_USE_VERSION=32; c++17 fuse3 /usr/include/fuse3;%(AdditionalIncludeDirectories) FUSE_USE_VERSION=32;NDEBUG;%(PreprocessorDefinitions) c++17 fuse3 ================================================ FILE: tst/memfs-fuse3/memfs-fuse3.out.vcxproj.filters ================================================  {642abec8-4756-443b-ac1f-3de5522812c2} Source Source ================================================ FILE: tst/memfs-fuse3/memfs-fuse3.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30204.135 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "memfs-fuse3.exe", "memfs-fuse3.exe.vcxproj", "{CF538F42-C714-4653-B351-E72FD7B0B217}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "memfs-fuse3.out", "memfs-fuse3.out.vcxproj", "{38AD1D24-7745-4B6E-9928-BD9731FED72A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.ActiveCfg = Debug|x64 {CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.Build.0 = Debug|x64 {CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.ActiveCfg = Debug|Win32 {CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.Build.0 = Debug|Win32 {CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.ActiveCfg = Release|x64 {CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.Build.0 = Release|x64 {CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.ActiveCfg = Release|Win32 {CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.Build.0 = Release|Win32 {38AD1D24-7745-4B6E-9928-BD9731FED72A}.Debug|x64.ActiveCfg = Debug|x64 {38AD1D24-7745-4B6E-9928-BD9731FED72A}.Debug|x86.ActiveCfg = Debug|x64 {38AD1D24-7745-4B6E-9928-BD9731FED72A}.Release|x64.ActiveCfg = Release|x64 {38AD1D24-7745-4B6E-9928-BD9731FED72A}.Release|x86.ActiveCfg = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F8910224-C4C3-4B29-9EB9-AEBDDBFCC250} EndGlobalSection EndGlobal ================================================ FILE: tst/winfuse-tests/coro-test.c ================================================ /** * @file coro-test.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include #include static void bprintf(char **b, const char *format, ...) { va_list ap; va_start(ap, format); int len = wvsprintfA(*b, format, ap); va_end(ap); *b += len; } static int coro_break_dotest(int brk, short stack[8], char **b) { coro_block (stack) { bprintf(b, "%s\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_yield_dotest(int brk, short stack[8], char **b) { coro_block (stack) { bprintf(b, "%s:10\n", __FUNCTION__); coro_yield; bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_loopyield_dotest(int brk, short stack[8], int *state, char **b) { coro_block (stack) { while ((*state)++ < 3) { bprintf(b, "%s:10:%d\n", __FUNCTION__, *state); coro_yield; } bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_await_break_dotest(int brk, short stack[8], char **b) { coro_block (stack) { bprintf(b, "%s:10\n", __FUNCTION__); coro_await (coro_break_dotest(brk, stack, b)); bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_await_yield_dotest(int brk, short stack[8], char **b) { coro_block (stack) { bprintf(b, "%s:10\n", __FUNCTION__); coro_await (coro_yield_dotest(brk, stack, b)); bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_await_loopyield_dotest(int brk, short stack[8], int *state, char **b) { coro_block (stack) { bprintf(b, "%s:10\n", __FUNCTION__); coro_await (coro_loopyield_dotest(brk, stack, state, b)); bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_loopawait_yield_dotest(int brk, short stack[8], int *state, char **b) { coro_block (stack) { while ((*state)++ < 3) { bprintf(b, "%s:10:%d\n", __FUNCTION__, *state); coro_await (coro_yield_dotest(brk, stack, b)); } bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_await_await_yield_dotest(int brk, short stack[8], char **b) { coro_block (stack) { bprintf(b, "%s:10\n", __FUNCTION__); coro_await (coro_await_yield_dotest(brk, stack, b)); bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_await_loopawait_yield_dotest(int brk, short stack[8], int *state, char **b) { coro_block (stack) { bprintf(b, "%s:10\n", __FUNCTION__); coro_await (coro_loopawait_yield_dotest(brk, stack, state, b)); bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static int coro_loopawait_loopawait_yield_dotest(int brk, short stack[8], int *state, char **b) { coro_block (stack) { while ((*state)++ < 2) { bprintf(b, "%s:10:%d\n", __FUNCTION__, *state); state[1] = 0; coro_await (coro_loopawait_yield_dotest(brk, stack, state + 1, b)); } bprintf(b, "%s:20\n", __FUNCTION__); if (brk) coro_break; } return coro_active(); } static void coro_dotest(int brk) { short stack[8]; int state[2]; char buf[2048], *b; memset(stack, 0, sizeof stack); b = buf; ASSERT(!coro_break_dotest(brk, stack, &b)); ASSERT(!coro_break_dotest(brk, stack, &b)); ASSERT(0 == strcmp(buf, "coro_break_dotest\n")); memset(stack, 0, sizeof stack); b = buf; ASSERT( coro_yield_dotest(brk, stack, &b)); ASSERT(!coro_yield_dotest(brk, stack, &b)); ASSERT(!coro_yield_dotest(brk, stack, &b)); ASSERT(0 == strcmp(buf, "coro_yield_dotest:10\ncoro_yield_dotest:20\n")); memset(stack, 0, sizeof stack); state[0] = 0; b = buf; ASSERT( coro_loopyield_dotest(brk, stack, state, &b)); ASSERT( coro_loopyield_dotest(brk, stack, state, &b)); ASSERT( coro_loopyield_dotest(brk, stack, state, &b)); ASSERT(!coro_loopyield_dotest(brk, stack, state, &b)); ASSERT(!coro_loopyield_dotest(brk, stack, state, &b)); ASSERT(0 == strcmp(buf, "coro_loopyield_dotest:10:1\n" "coro_loopyield_dotest:10:2\n" "coro_loopyield_dotest:10:3\n" "coro_loopyield_dotest:20\n")); memset(stack, 0, sizeof stack); b = buf; ASSERT(!coro_await_break_dotest(brk, stack, &b)); ASSERT(!coro_await_break_dotest(brk, stack, &b)); ASSERT(0 == strcmp(buf, "coro_await_break_dotest:10\ncoro_break_dotest\ncoro_await_break_dotest:20\n")); memset(stack, 0, sizeof stack); b = buf; ASSERT( coro_await_yield_dotest(brk, stack, &b)); ASSERT(!coro_await_yield_dotest(brk, stack, &b)); ASSERT(!coro_await_yield_dotest(brk, stack, &b)); ASSERT(0 == strcmp(buf, "coro_await_yield_dotest:10\ncoro_yield_dotest:10\ncoro_yield_dotest:20\ncoro_await_yield_dotest:20\n")); memset(stack, 0, sizeof stack); state[0] = 0; b = buf; ASSERT( coro_await_loopyield_dotest(brk, stack, state, &b)); ASSERT( coro_await_loopyield_dotest(brk, stack, state, &b)); ASSERT( coro_await_loopyield_dotest(brk, stack, state, &b)); ASSERT(!coro_await_loopyield_dotest(brk, stack, state, &b)); ASSERT(!coro_await_loopyield_dotest(brk, stack, state, &b)); ASSERT(0 == strcmp(buf, "coro_await_loopyield_dotest:10\n" "coro_loopyield_dotest:10:1\n" "coro_loopyield_dotest:10:2\n" "coro_loopyield_dotest:10:3\n" "coro_loopyield_dotest:20\n" "coro_await_loopyield_dotest:20\n")); memset(stack, 0, sizeof stack); state[0] = 0; b = buf; ASSERT( coro_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(!coro_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(!coro_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(0 == strcmp(buf, "coro_loopawait_yield_dotest:10:1\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:2\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:3\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:20\n")); memset(stack, 0, sizeof stack); b = buf; ASSERT( coro_await_await_yield_dotest(brk, stack, &b)); ASSERT(!coro_await_await_yield_dotest(brk, stack, &b)); ASSERT(!coro_await_await_yield_dotest(brk, stack, &b)); ASSERT(0 == strcmp(buf, "coro_await_await_yield_dotest:10\n" "coro_await_yield_dotest:10\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_await_yield_dotest:20\n" "coro_await_await_yield_dotest:20\n")); memset(stack, 0, sizeof stack); state[0] = 0; b = buf; ASSERT( coro_await_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_await_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_await_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(!coro_await_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(!coro_await_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(0 == strcmp(buf, "coro_await_loopawait_yield_dotest:10\n" "coro_loopawait_yield_dotest:10:1\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:2\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:3\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:20\n" "coro_await_loopawait_yield_dotest:20\n")); memset(stack, 0, sizeof stack); state[0] = 0; b = buf; ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(!coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(!coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b)); ASSERT(0 == strcmp(buf, "coro_loopawait_loopawait_yield_dotest:10:1\n" "coro_loopawait_yield_dotest:10:1\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:2\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:3\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:20\n" "coro_loopawait_loopawait_yield_dotest:10:2\n" "coro_loopawait_yield_dotest:10:1\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:2\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:10:3\n" "coro_yield_dotest:10\n" "coro_yield_dotest:20\n" "coro_loopawait_yield_dotest:20\n" "coro_loopawait_loopawait_yield_dotest:20\n")); } static void coro_test(void) { coro_dotest(0); coro_dotest(1); } void coro_tests(void) { TEST(coro_test); } ================================================ FILE: tst/winfuse-tests/path-test.c ================================================ /** * @file path-test.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include #define SHARED_KM_SHARED_H_INCLUDED #define PAGED_CODE() #include void path_prefix_test(void) { PSTR ipaths[] = { "", "/", "//", "/a", "//a", "//a/", "//a//", "a/", "a//", "a/b", "a//b", "foo///bar//baz", "foo///bar//baz/", "foo///bar//baz//", "foo", "/foo/bar/baz", }; PSTR opaths[] = { "", "", "/", "", "/", "", "/", "a", "/", "a", "/", "a/", "/", "a//", "a", "", "a", "", "a", "b", "a", "b", "foo", "bar//baz", "foo", "bar//baz/", "foo", "bar//baz//", "foo", "", "/", "foo/bar/baz", }; for (size_t i = 0; sizeof ipaths / sizeof ipaths[0] > i; i++) { STRING Path, Prefix, Remain; Path.Length = Path.MaximumLength = (USHORT)strlen(ipaths[i]); Path.Buffer = ipaths[i]; FusePosixPathPrefix(&Path, &Prefix, &Remain); ASSERT(Prefix.Length == strlen(opaths[2 * i + 0])); ASSERT(Prefix.Length == Prefix.MaximumLength); ASSERT(0 == memcmp(opaths[2 * i + 0], Prefix.Buffer, Prefix.Length)); ASSERT(Remain.Length == strlen(opaths[2 * i + 1])); ASSERT(Remain.Length == Remain.MaximumLength); ASSERT(0 == memcmp(opaths[2 * i + 1], Remain.Buffer, Remain.Length)); } } void path_suffix_test(void) { PSTR ipaths[] = { "", "/", "//", "/a", "//a", "//a/", "//a//", "a/", "a//", "a/b", "a//b", "foo///bar//baz", "foo///bar//baz/", "foo///bar//baz//", "foo", "/foo/bar/baz", }; PSTR opaths[] = { "", "", "/", "", "/", "", "/", "a", "/", "a", "//a", "", "//a", "", "a", "", "a", "", "a", "b", "a", "b", "foo///bar", "baz", "foo///bar//baz", "", "foo///bar//baz", "", "foo", "", "/foo/bar", "baz", }; for (size_t i = 0; sizeof ipaths / sizeof ipaths[0] > i; i++) { STRING Path, Remain, Suffix; Path.Length = Path.MaximumLength = (USHORT)strlen(ipaths[i]); Path.Buffer = ipaths[i]; FusePosixPathSuffix(&Path, &Remain, &Suffix); ASSERT(Remain.Length == strlen(opaths[2 * i + 0])); ASSERT(Remain.Length == Remain.MaximumLength); ASSERT(0 == memcmp(opaths[2 * i + 0], Remain.Buffer, Remain.Length)); ASSERT(Suffix.Length == strlen(opaths[2 * i + 1])); ASSERT(Suffix.Length == Suffix.MaximumLength); ASSERT(0 == memcmp(opaths[2 * i + 1], Suffix.Buffer, Suffix.Length)); } } void path_tests(void) { TEST(path_prefix_test); TEST(path_suffix_test); } ================================================ FILE: tst/winfuse-tests/transact-test.c ================================================ /** * @file transact-test.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include #include #include #include #define FUSE_FSCTL_TRANSACT \ CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 0xC00 + 'F', METHOD_BUFFERED, FILE_ANY_ACCESS) static void transact_init_dotest(PWSTR DeviceName, PWSTR Prefix) { FSP_FSCTL_VOLUME_PARAMS VolumeParams = { .Version = sizeof VolumeParams }; HANDLE VolumeHandle; WCHAR VolumeName[MAX_PATH]; BOOL Success; NTSTATUS Result; if (0 != Prefix && L'\\' == Prefix[0] && L'\\' == Prefix[1]) wcscpy_s(VolumeParams.Prefix, sizeof VolumeParams.Prefix / sizeof(WCHAR), Prefix + 1); VolumeParams.FsextControlCode = FUSE_FSCTL_TRANSACT; Result = FspFsctlCreateVolume(DeviceName, &VolumeParams, VolumeName, sizeof VolumeName, &VolumeHandle); ASSERT(STATUS_SUCCESS == Result); ASSERT(0 == wcsncmp(L"\\Device\\Volume{", VolumeName, 15)); ASSERT(INVALID_HANDLE_VALUE != VolumeHandle); FSP_FSCTL_DECLSPEC_ALIGN UINT8 RequestBuf[FUSE_PROTO_REQ_SIZEMIN]; FUSE_PROTO_RSP ResponseBuf; FUSE_PROTO_REQ *Request = (PVOID)RequestBuf; FUSE_PROTO_RSP *Response = &ResponseBuf; DWORD BytesTransferred; Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT, 0, 0, RequestBuf, sizeof RequestBuf, &BytesTransferred, 0); ASSERT(Success); ASSERT(BytesTransferred == Request->len); ASSERT(FUSE_PROTO_REQ_SIZE(init) == Request->len); ASSERT(FUSE_PROTO_OPCODE_INIT == Request->opcode); ASSERT(0 != Request->unique); ASSERT(0 == Request->nodeid); ASSERT(0 == Request->uid); ASSERT(0 == Request->gid); ASSERT(0 == Request->pid); ASSERT(0 == Request->padding); ASSERT(FUSE_PROTO_VERSION == Request->req.init.major); ASSERT(FUSE_PROTO_MINOR_VERSION == Request->req.init.minor); // max_readahead // flags memset(Response, 0, FUSE_PROTO_RSP_SIZE(init)); Response->len = FUSE_PROTO_RSP_SIZE(init); Response->unique = Request->unique; Response->rsp.init.major = Request->req.init.major; Response->rsp.init.minor = Request->req.init.minor; // max_readahead // flags // max_background // congestion_threshold // max_write // time_gran // max_pages // padding // unused Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT, Response, Response->len, 0, 0, &BytesTransferred, 0); ASSERT(Success); Success = CloseHandle(VolumeHandle); ASSERT(Success); } static void transact_init_test(void) { transact_init_dotest(L"WinFsp.Disk", 0); transact_init_dotest(L"WinFsp.Net", L"\\\\winfuse-tests\\share"); } static HANDLE transact_open_close_dotest_VolumeHandle; static HANDLE transact_open_close_dotest_MainThread; static unsigned __stdcall transact_open_close_dotest_thread(void *FilePath) { FspDebugLog(__FUNCTION__ ": \"%S\"\n", FilePath); HANDLE Handle; Handle = CreateFileW(FilePath, FILE_GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); if (INVALID_HANDLE_VALUE == Handle) return GetLastError(); if (INVALID_HANDLE_VALUE != transact_open_close_dotest_VolumeHandle) { Sleep(300); CloseHandle(transact_open_close_dotest_VolumeHandle); } if (0 != transact_open_close_dotest_MainThread) { Sleep(300); if (!CancelSynchronousIo(transact_open_close_dotest_MainThread)) { DWORD LastError = GetLastError(); CloseHandle(Handle); return LastError; } } CloseHandle(Handle); return 0; } static void transact_open_close_dotest(PWSTR DeviceName, PWSTR Prefix, int Scenario) { FSP_FSCTL_VOLUME_PARAMS VolumeParams = { .Version = sizeof VolumeParams }; HANDLE VolumeHandle; WCHAR VolumeName[MAX_PATH]; WCHAR FilePath[MAX_PATH]; HANDLE Thread, MainThread = 0; DWORD ExitCode; BOOL Success; NTSTATUS Result; if (0 != Prefix && L'\\' == Prefix[0] && L'\\' == Prefix[1]) wcscpy_s(VolumeParams.Prefix, sizeof VolumeParams.Prefix / sizeof(WCHAR), Prefix + 1); VolumeParams.FsextControlCode = FUSE_FSCTL_TRANSACT; Result = FspFsctlCreateVolume(DeviceName, &VolumeParams, VolumeName, sizeof VolumeName, &VolumeHandle); ASSERT(STATUS_SUCCESS == Result); ASSERT(0 == wcsncmp(L"\\Device\\Volume{", VolumeName, 15)); ASSERT(INVALID_HANDLE_VALUE != VolumeHandle); transact_open_close_dotest_VolumeHandle = 'CLOS' == Scenario ? VolumeHandle : INVALID_HANDLE_VALUE; transact_open_close_dotest_MainThread = 'CNCL' == Scenario && DuplicateHandle( GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &MainThread, 0, FALSE, DUPLICATE_SAME_ACCESS) ? MainThread : 0; StringCbPrintfW(FilePath, sizeof FilePath, L"%s%s\\file0", Prefix ? L"" : L"\\\\?\\GLOBALROOT", Prefix ? Prefix : VolumeName); Thread = (HANDLE)_beginthreadex(0, 0, transact_open_close_dotest_thread, FilePath, 0, 0); ASSERT(0 != Thread); Sleep(1000); /* give some time to the thread to execute */ FSP_FSCTL_DECLSPEC_ALIGN UINT8 RequestBuf[FUSE_PROTO_REQ_SIZEMIN]; FUSE_PROTO_RSP ResponseBuf; FUSE_PROTO_REQ *Request = (PVOID)RequestBuf; FUSE_PROTO_RSP *Response = &ResponseBuf; DWORD BytesTransferred; for (BOOLEAN Loop = TRUE; Loop;) { do { Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT, 0, 0, RequestBuf, sizeof RequestBuf, &BytesTransferred, 0); ASSERT(Success || ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError()); if (!Success && (ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError())) goto loopexit; } while (0 == BytesTransferred); ASSERT(FUSE_PROTO_REQ_HEADER_SIZE <= BytesTransferred); ASSERT(Request->len == BytesTransferred); Response->len = 0; switch (Request->opcode) { case FUSE_PROTO_OPCODE_INIT: ASSERT(FUSE_PROTO_REQ_SIZE(init) == Request->len); ASSERT(FUSE_PROTO_OPCODE_INIT == Request->opcode); ASSERT(0 != Request->unique); ASSERT(0 == Request->nodeid); ASSERT(0 == Request->uid); ASSERT(0 == Request->gid); ASSERT(0 == Request->pid); ASSERT(0 == Request->padding); ASSERT(FUSE_PROTO_VERSION == Request->req.init.major); ASSERT(FUSE_PROTO_MINOR_VERSION == Request->req.init.minor); // max_readahead // flags memset(Response, 0, FUSE_PROTO_RSP_SIZE(init)); Response->len = FUSE_PROTO_RSP_SIZE(init); Response->unique = Request->unique; Response->rsp.init.major = Request->req.init.major; Response->rsp.init.minor = Request->req.init.minor; // max_readahead // flags // max_background // congestion_threshold // max_write // time_gran // max_pages // padding // unused break; case FUSE_PROTO_OPCODE_STATFS: ASSERT(FUSE_PROTO_REQ_HEADER_SIZE == Request->len); ASSERT(FUSE_PROTO_OPCODE_STATFS == Request->opcode); ASSERT(0 != Request->unique); ASSERT(0 == Request->nodeid); ASSERT(0 == Request->uid); ASSERT(0 == Request->gid); ASSERT(0 == Request->pid); ASSERT(0 == Request->padding); memset(Response, 0, FUSE_PROTO_RSP_SIZE(statfs)); Response->len = FUSE_PROTO_RSP_SIZE(statfs); Response->unique = Request->unique; Response->rsp.statfs.st.blocks = 1000; Response->rsp.statfs.st.bfree = 1000; Response->rsp.statfs.st.frsize = 4096; break; case FUSE_PROTO_OPCODE_GETATTR: ASSERT(FUSE_PROTO_REQ_SIZE(getattr) == Request->len); ASSERT(FUSE_PROTO_OPCODE_GETATTR == Request->opcode); ASSERT(0 != Request->unique); ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid || FUSE_PROTO_ROOT_INO + 1 == Request->nodeid); ASSERT(0 == Request->padding); ASSERT(0 == Request->req.getattr.getattr_flags); ASSERT(0 == Request->req.getattr.fh); memset(Response, 0, FUSE_PROTO_RSP_SIZE(getattr)); Response->len = FUSE_PROTO_RSP_SIZE(getattr); Response->unique = Request->unique; Response->rsp.getattr.attr.ino = Request->nodeid; Response->rsp.getattr.attr.mode = 0040777; Response->rsp.getattr.attr.nlink = 1; Response->rsp.getattr.attr.uid = Request->uid; Response->rsp.getattr.attr.gid = Request->gid; break; case FUSE_PROTO_OPCODE_LOOKUP: ASSERT(FUSE_PROTO_REQ_SIZE(lookup) + sizeof "file0" == Request->len); ASSERT(FUSE_PROTO_OPCODE_LOOKUP == Request->opcode); ASSERT(0 != Request->unique); ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid); ASSERT(0 != Request->uid); ASSERT(0 != Request->gid); ASSERT(0 != Request->pid); ASSERT(0 == Request->padding); ASSERT(0 == strcmp("file0", Request->req.lookup.name)); memset(Response, 0, FUSE_PROTO_RSP_SIZE(lookup)); Response->len = FUSE_PROTO_RSP_SIZE(lookup); Response->unique = Request->unique; Response->rsp.lookup.entry.nodeid = FUSE_PROTO_ROOT_INO + 1; Response->rsp.lookup.entry.attr.ino = FUSE_PROTO_ROOT_INO + 1; Response->rsp.lookup.entry.attr.mode = 0040777; Response->rsp.lookup.entry.attr.nlink = 1; Response->rsp.lookup.entry.attr.uid = Request->uid; Response->rsp.lookup.entry.attr.gid = Request->gid; break; case FUSE_PROTO_OPCODE_FORGET: case FUSE_PROTO_OPCODE_BATCH_FORGET: continue; case FUSE_PROTO_OPCODE_OPENDIR: case FUSE_PROTO_OPCODE_OPEN: ASSERT(FUSE_PROTO_REQ_SIZE(open) == Request->len); ASSERT(FUSE_PROTO_OPCODE_OPENDIR == Request->opcode || FUSE_PROTO_OPCODE_OPEN == Request->opcode); ASSERT(0 != Request->unique); ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid || FUSE_PROTO_ROOT_INO + 1 == Request->nodeid); ASSERT(0 != Request->uid); ASSERT(0 != Request->gid); ASSERT(0 != Request->pid); ASSERT(0 == Request->padding); ASSERT(0 == Request->req.open.flags); ASSERT(0 == Request->req.open.unused); memset(Response, 0, FUSE_PROTO_RSP_SIZE(open)); Response->len = FUSE_PROTO_RSP_SIZE(open); Response->unique = Request->unique; Response->rsp.open.fh = 100 + Request->nodeid; break; case FUSE_PROTO_OPCODE_RELEASEDIR: case FUSE_PROTO_OPCODE_RELEASE: ASSERT(FUSE_PROTO_REQ_SIZE(release) == Request->len); ASSERT(FUSE_PROTO_OPCODE_RELEASEDIR == Request->opcode || FUSE_PROTO_OPCODE_RELEASE == Request->opcode); ASSERT(0 != Request->unique); ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid || FUSE_PROTO_ROOT_INO + 1 == Request->nodeid); ASSERT(0 == Request->uid); ASSERT(0 == Request->gid); ASSERT(0 == Request->pid); ASSERT(0 == Request->padding); ASSERT( 100 + FUSE_PROTO_ROOT_INO == Request->req.release.fh || 100 + FUSE_PROTO_ROOT_INO + 1 == Request->req.release.fh); ASSERT(0 == Request->req.release.flags); ASSERT(0 == Request->req.release.release_flags); ASSERT(0 == Request->req.release.lock_owner); memset(Response, 0, FUSE_PROTO_RSP_HEADER_SIZE); Response->len = FUSE_PROTO_RSP_HEADER_SIZE; Response->unique = Request->unique; if ('BOGU' == Scenario) Response->unique = Response->unique ^ rand(); if (100 + FUSE_PROTO_ROOT_INO + 1 == Request->req.release.fh) Loop = FALSE; break; } Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT, Response, Response->len, 0, 0, &BytesTransferred, 0); ASSERT(Success || ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError()); if (!Success && (ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError())) goto loopexit; ASSERT(0 == BytesTransferred); } loopexit: if ('CLOS' != Scenario) { Success = CloseHandle(VolumeHandle); ASSERT(Success); } if ('CNCL' == Scenario) { Success = CloseHandle(MainThread); ASSERT(Success); } WaitForSingleObject(Thread, INFINITE); GetExitCodeThread(Thread, &ExitCode); CloseHandle(Thread); ASSERT(0 == ExitCode); } static void transact_open_close_test(void) { transact_open_close_dotest(L"WinFsp.Disk", 0, 0); transact_open_close_dotest(L"WinFsp.Net", L"\\\\winfuse-tests\\share", 0); } static void transact_open_abandon_test(void) { transact_open_close_dotest(L"WinFsp.Disk", 0, 'CLOS'); transact_open_close_dotest(L"WinFsp.Net", L"\\\\winfuse-tests\\share", 'CLOS'); } static void transact_open_cancel_test(void) { transact_open_close_dotest(L"WinFsp.Disk", 0, 'CNCL'); transact_open_close_dotest(L"WinFsp.Net", L"\\\\winfuse-tests\\share", 'CNCL'); } static void transact_open_bogus_test(void) { transact_open_close_dotest(L"WinFsp.Disk", 0, 'BOGU'); transact_open_close_dotest(L"WinFsp.Net", L"\\\\winfuse-tests\\share", 'BOGU'); } void transact_tests(void) { TEST(transact_init_test); TEST(transact_open_close_test); TEST(transact_open_abandon_test); TEST(transact_open_cancel_test); TEST(transact_open_bogus_test); } ================================================ FILE: tst/winfuse-tests/winfuse-tests.c ================================================ /** * @file winfuse-tests.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include int main(int argc, char *argv[]) { FspLoad(0); TESTSUITE(coro_tests); TESTSUITE(path_tests); TESTSUITE(transact_tests); tlib_run_tests(argc, argv); return 0; } ================================================ FILE: tst/wslfuse-tests/mount-test.c ================================================ /** * @file mount-test.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include #include #include #include #include #include #include static void mount_createvol_dotest(wchar_t *Prefix) { WSLFUSE_IOCTL_CREATEVOLUME_ARG CreateArg = { .VolumeParams.Version = sizeof(FSP_FSCTL_VOLUME_PARAMS)}; int fusefd, res; if (0 != Prefix && L'\\' == Prefix[0] && L'\\' == Prefix[1]) { /* note that on Linux: sizeof(wchar_t) != sizeof(WCHAR) */ wchar_t *P = Prefix + 1; WCHAR *Q = CreateArg.VolumeParams.Prefix; while (0 != (*Q++ = (WCHAR)*P++)) ; } fusefd = open("/dev/fuse", O_RDWR); ASSERT(-1 != fusefd); res = ioctl(fusefd, WSLFUSE_IOCTL_CREATEVOLUME, &CreateArg); ASSERT(0 == res); ASSERT(0 == strncmp(CreateArg.VolumeName, "\\Device\\Volume{", 15)); res = close(fusefd); ASSERT(0 == res); } static void mount_createvol_test(void) { mount_createvol_dotest(0); mount_createvol_dotest(L"\\\\wslfuse-tests\\share"); } #if 0 static void mount_unmount_test(void) { WSLFUSE_IOCTL_MOUNTID_ARG MountArg; int fusefd, res; fusefd = open("/dev/fuse", O_RDWR); ASSERT(-1 != fusefd); MountArg.Operation = '?'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(-1 == res); ASSERT(ENOENT == errno); MountArg.Operation = '-'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(-1 == res); ASSERT(ENOENT == errno); MountArg.Operation = '+'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(0 == res); MountArg.Operation = '+'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(-1 == res); ASSERT(EEXIST == errno); MountArg.Operation = '?'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(0 == res); MountArg.Operation = '?'; MountArg.MountId = 0x43434343; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(-1 == res); ASSERT(ENOENT == errno); MountArg.Operation = '-'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(0 == res); MountArg.Operation = '-'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(-1 == res); ASSERT(ENOENT == errno); MountArg.Operation = '?'; MountArg.MountId = 0x42424242; res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg); ASSERT(-1 == res); ASSERT(ENOENT == errno); res = close(fusefd); ASSERT(0 == res); } #endif void mount_tests(void) { TEST(mount_createvol_test); #if 0 TEST(mount_unmount_test); #endif } ================================================ FILE: tst/wslfuse-tests/wslfuse-tests.c ================================================ /** * @file wslfuse-tests.c * * @copyright 2019-2020 Bill Zissimopoulos */ /* * This file is part of WinFuse. * * You can redistribute it and/or modify it under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. * * Licensees holding a valid commercial license may use this software * in accordance with the commercial license agreement provided in * conjunction with the software. The terms and conditions of any such * commercial license agreement shall govern, supersede, and render * ineffective any application of the AGPLv3 license to this software, * notwithstanding of any reference thereto in the software or * associated repository. */ #include int main(int argc, char *argv[]) { TESTSUITE(mount_tests); tlib_run_tests(argc, argv); return 0; }