././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681768758.1281602 pyxattr-0.8.1/0000755000000000000000000000000014417340466012002 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1214856559.0 pyxattr-0.8.1/COPYING0000644000000000000000000006363711032236557013047 0ustar00rootroot GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768079.0 pyxattr-0.8.1/MANIFEST.in0000644000000000000000000000047214417337217013543 0ustar00rootrootinclude COPYING include NEWS.md include README.md include Makefile include doc/conf.py include doc/index.rst include doc/module.rst include doc/news.md include doc/readme.md include doc/contributing.md include doc/security.md include setup.cfg include tests/test_xattr.py include tests/__init__.py include xattr.c ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768560.0 pyxattr-0.8.1/Makefile0000644000000000000000000000506714417340160013441 0ustar00rootrootPYTHON = python3 SPHINXOPTS = -W SPHINXBUILD = $(PYTHON) -m sphinx DOCDIR = doc DOCHTML = $(DOCDIR)/html DOCTREES = $(DOCDIR)/doctrees ALLSPHINXOPTS = -d $(DOCTREES) $(SPHINXOPTS) $(DOCDIR) VERSION = 0.8.1 FULLVER = pyxattr-$(VERSION) DISTFILE = $(FULLVER).tar.gz MODNAME = xattr.so RSTFILES = doc/index.rst doc/module.rst doc/news.md doc/readme.md doc/conf.py PYVERS = 3.7 3.8 3.9 3.10 3.11 REPS = 5 all: doc test $(MODNAME): xattr.c $(PYTHON) ./setup.py build_ext --inplace $(DOCHTML)/index.html: $(MODNAME) $(RSTFILES) $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(DOCHTML) touch $@ doc: $(DOCHTML)/index.html dist: fakeroot $(PYTHON) ./setup.py sdist distcheck: dist set -e; \ TDIR=$$(mktemp -d) && \ trap "rm -rf $$TDIR" EXIT; \ tar xzf dist/$(DISTFILE) -C $$TDIR && \ (cd $$TDIR/$(FULLVER) && make doc && make test && make dist) && \ echo "All good, you can upload $(DISTFILE)!" test: @for ver in $(PYVERS); do \ for flavour in "" "-dbg"; do \ if type python$$ver$$flavour >/dev/null; then \ echo Testing with python$$ver$$flavour; \ python$$ver$$flavour setup.py build_ext -i; \ python$$ver$$flavour -m pytest tests; \ fi; \ done; \ done; @if type pypy3 >/dev/null; then \ echo Testing with pypy3; \ pypy3 setup.py build_ext -i; \ pypy3 -m pytest tests; \ fi fast-test: python3 setup.py build_ext -i python3 -m pytest tests -v benchmark: $(MODNAME) @set -e; \ TESTFILE=`mktemp`;\ trap 'rm $$TESTFILE' EXIT; \ for ver in $(PYVERS) ; do \ if type python$$ver >/dev/null; then \ echo Benchmarking with python$$ver; \ python$$ver ./setup.py build -q; \ echo " - set (with override)"; \ python$$ver -m timeit -r $(REPS) -s 'import xattr' "xattr.set('$$TESTFILE', 'user.comment', 'hello')"; \ echo " - list"; \ python$$ver -m timeit -r $(REPS) -s 'import xattr' "xattr.list('$$TESTFILE')"; \ echo " - get"; \ python$$ver -m timeit -r $(REPS) -s 'import xattr' "xattr.get('$$TESTFILE', 'user.comment')"; \ echo " - set + remove"; \ python$$ver -m timeit -r $(REPS) -s 'import xattr' "xattr.set('$$TESTFILE', 'user.comment', 'hello'); xattr.remove('$$TESTFILE', 'user.comment')"; \ fi; \ done; coverage: $(MAKE) clean $(MAKE) test CFLAGS="-coverage" lcov --capture --directory . --no-external --output-file coverage.info genhtml coverage.info --output-directory out clean: rm -rf $(DOCHTML) $(DOCTREES) rm -f $(MODNAME) rm -f *.so rm -rf build .PHONY: doc test fast-test clean dist distcheck coverage ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768236.0 pyxattr-0.8.1/NEWS.md0000644000000000000000000001731714417337454013114 0ustar00rootroot# News ## Version 0.8.1 *Mon, 17 Apr 2023* Very minor release: * Fix the pypi declared python versions * Add some more documentation - a security policy, and a contributing guide. * Restore yet again the CI environment :/ ## Version 0.8.0 *Mon, 12 Dec 2022* Minor bugfix release, but due to lack of CI environments supporting old Python versions, only Python 3.7+ is supported. Otherwise: * Snape3058@ found some refcount issues (see issue #35), these have been fixed. * Tested and enabled Python 3.10 support, dropped < 3.7. * Various improvements to the CI environments. * Move fully to `setuptools` (where available), in preparation for 3.12 dropping `distutils` support. ## Version 0.7.2 *Sun, 29 Nov 2020* Minor release: * Expand testing by adding better mixed-access checks (e.g. set via symlink and read on file) and by not leaking resources during tests. * Enable testing with Python 3.9 and confirm compatibility with it. * Fix documentation building with Sphinx 3.0+. ## Version 0.7.1 *released Tue, 26 Nov 2019* Typo fix release in the bug tracker link :/ ## Version 0.7.0 *released Tue, 26 Nov 2019* Major change: drop compatibility with Python 2, which allows significant code cleanups. Other changes: * Switch internal implementation of argument parsing to a built-in one (`PyUnicode_FSConverter`), which brings automatic support for path-like objects in Python 3.6+ (#20), and also a more uniform handling of Unicode path arguments with respect to other Python code. * Fix missing error check in list operations in `get_all` (#17). * Switch test library to pytest; not that a reasonable recent version is needed. Additionally, expand test coverage, although not directly visible in actual coverage reports… ## Version 0.6.1 *released Tue, 24 Jul 2018* Minor bugfix, performance and compatibility release. * Minor compatibility fix: on Linux, drop the use of the `attr` library, and instead switch to the glibc header `sys/xattr.h`, which is provided for a really long time (since glibc 2.3). The formerly used header `attr/xattr.h` has been removed from the `attr` library in version 2.4.48. Fix provided by Lars Wendler, many thanks! * Release the GIL when performing I/O. Patch proposed by xwhuang, many thanks. I tested this a long while back it seemed to impact performance on local filesystems, but upon further inspection, the downsides are minor (between 0 and 5%, in many cases negligible). For remote or slow filesystems, this should allow much increased parallelism. * Fix symlink set operation on MacOS X; bugfix provided by adamlin, much appreciated! This also uncovered testing problems related to symlinks, which are now fixed (the bug would be caught by the updated tests). ## Version 0.6.0 *released Mon, 23 Jan 2017* Bugfix and feature release (hence the version bump). The main change is to the implementation of how attributes are listed and read. This was done due to existing race issues when attributes are modified while being read (github issue #12), but basically all various internal paths that dealt with retrieving an attribute value or listing attributes were unified in a single helper function that does handle such concurrent modifications. As a side effect, the size of the buffers used for such reads have changed, which (depending on attribute value) might change the trade-off between number of syscalls done and memory usage. As feature release, OSX support was contributed by Adam Knight , thanks a lot! I don't have access to OSX so the testing for it is done via Travis builds; please report any issues. ## Version 0.5.6 *released Sat, 09 Apr 2016* Small bugfix release: * Fixes some sign-compare warnings * Fixes potential name truncation in merge_ns() * Fixes building on systems which don't have ENODATA Tested with Python 2.7.11, Python 3.5.1 and PyPy 5.0.1. ## Version 0.5.5 *released Fri, 01 May 2015* Bugfix release: * fixes some more memory leaks when handling out-of-memory in get_all() function * improve error reporting when an attribute disappears after we asked for its length but before we managed to read it * fix int/size_t issues found by RedHat/Fedora, https://bugzilla.redhat.com/show_bug.cgi?id=1127310; the fix is different than their fix, but it should accomplish the same thing * convert all code to only do explicit casts after checking boundaries, making the code `-Wconversion`-clean (although that warning is not enabled by default) ## Version 0.5.4 *released Thu, 30 Apr 2015* Fix memory leaks on some of the error-handling paths of the `get()` function. ## Version 0.5.3 *released Fri, 23 May 2014* Small optimisations release: * ari edelkind contributed a speed-up optimisation for handling of files without xattrs (which is, in general, the expected case) * Jonas Borgström contributed a behaviour change to the handling of file names: under Python 3 and up, unicode paths are encoded/decoded using the 'surogatee' handler, instead of the 'strict' handler; while this can hide encoding errors, it mirrors what Python libraries do (e.g. see os.fsencode/fsdecode) * Sean Patrick Santos contributed improvements to the test suite so that it can be used even on files systems which have built-in attributes (e.g. when using SELinux, or NFSv4); to enable this, define the attributes in the TEST_IGNORE_XATTRS environment variable ## Version 0.5.2 *released Thu, 03 Jan 2013* Bug-fix release. Thanks to Michał Górny, it looked like the library had problem running under pypy, but actually there was a bug in the PyArg_ParseTuple use of et# (signed vs. unsigned, and lack of compiler warnings). This was fixed, and now the test suite passed with many CPython versions and PyPy (version 1.9). ## Version 0.5.1 *released Wed, 16 May 2012* Bug-fix release. Thanks to Dave Malcolm and his cpychecker tool, a number of significant bugs (refcount leaks and potential NULL-pointer dereferences) have been fixed. Furthermore, compatibility with Python 3 has been improved; this however required changing the meaning of the ``namespace`` argument to the functions: if passed, None is no longer a valid value; pass an empty string if (due to the structure of your program) you have to pass this argument but want to specify no namespace. Also, the project home page has changed from SourceForge to GitHub, and the documentation has been converted from epydoc-based to sphinx. ## Version 0.5 *released Sun, 27 Dec 2009* Implemented support for Python 3. This required a significant change to the C module, hence the new version number. ## Version 0.4 *released Mon, 30 Jun 2008* ### API The old functions ({get,set,list,remove}xattr) are deprecated and replaced with a new API that is namespace-aware and hopefully will allow other OSes (e.g. FreeBSD) to be supported more naturally. Both the old and the new API are supported in the 0.4 versions, however users are encouraged to migrate to the new API. ### New features A new bulk get function called get_all() has been added that should be somewhat faster in case of querying files which have many attributes. ### License Since LGPLv3 is not compatible with GPLv2 (which unfortunately I didn't realize before), the license was changed to LGPLv2.1 or later. ### Internals Unittest coverage was improved. ## Version 0.3 *released Sun, 09 Mar 2008* * changed licence from GPL to LGPL (3 or later) * changed listxattr return type from tuple to a list * developer-related: added unittests ## Version 0.2.2 *released Sun, 01 Jul 2007* * fixed listing symlink xattrs ## Version 0.2.1 *released Sat, 11 Feb 2006* * fixed a bug when reading symlink EAs (you weren't able to do it, actually) * fixed a possible memory leak when the actual read of the EA failed but the call to get the length of the EA didn't ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681768758.1281602 pyxattr-0.8.1/PKG-INFO0000644000000000000000000000216314417340466013101 0ustar00rootrootMetadata-Version: 2.1 Name: pyxattr Version: 0.8.1 Summary: Filesystem extended attributes for python Home-page: https://pyxattr.k1024.org/ Download-URL: https://pyxattr.k1024.org/downloads/ Author: Iustin Pop Author-email: iustin@k1024.org License: LGPL Project-URL: Bug Tracker, https://github.com/iustin/pyxattr/issues Platform: Linux Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+) Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: POSIX :: Linux Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Filesystems Requires-Python: >=3.7 License-File: COPYING This is a C extension module for Python which implements extended attributes manipulation. It is a wrapper on top of the attr C library - see attr(5). ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681767256.0 pyxattr-0.8.1/README.md0000644000000000000000000000760414417335530013264 0ustar00rootroot# pyxattr This is the pyxattr module, a Python extension module which gives access to the extended attributes for filesystem objects available in some operating systems. [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/iustin/pyxattr/ci.yml?branch=main)](https://github.com/iustin/pyxattr/actions/workflows/ci.yml) [![Codecov](https://img.shields.io/codecov/c/github/iustin/pyxattr)](https://codecov.io/gh/iustin/pyxattr) [![Read the Docs](https://img.shields.io/readthedocs/pyxattr)](https://pyxattr.readthedocs.io/en/latest/?badge=latest) [![GitHub issues](https://img.shields.io/github/issues/iustin/pyxattr)](https://github.com/iustin/pyxattr/issues) ![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/iustin/pyxattr) [![GitHub release (latest by date)](https://img.shields.io/github/v/release/iustin/pyxattr)](https://github.com/iustin/pyxattr/releases) [![PyPI](https://img.shields.io/pypi/v/pyxattr)](https://pypi.org/project/pyxattr/) ![Debian package](https://img.shields.io/debian/v/python-pyxattr) ![Ubuntu package](https://img.shields.io/ubuntu/v/python-pyxattr) ![GitHub Release Date](https://img.shields.io/github/release-date/iustin/pyxattr) ![GitHub commits since latest release](https://img.shields.io/github/commits-since/iustin/pyxattr/latest) ![GitHub last commit](https://img.shields.io/github/last-commit/iustin/pyxattr) [![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/7236/badge)](https://bestpractices.coreinfrastructure.org/projects/7236) Downloads: go to . The source repository is either at or at . See the `CONTRIBUTING.md` file for details on how to contribute. ## Requirements The current supported Python versions are 3.7+ (tested up to 3.10), or PyPy versions 3.7+ (tested up to 3.9). The code should currently be compatible down to Python 3.4, but such versions are no longer tested. The library has been written and tested on Linux, kernel v2.4 or later, with XFS and ext2/ext3/ext4 file systems, and MacOS recent versions. If any other platform implements the same behaviour, pyxattr could be used. To build the module from source, you will need both a Python development environment/libraries and the C compiler, plus the setuptools tool installed, and for building the documentation you need to have Sphinx installed. The exact list of dependencies depends on the operating system/distribution, but should be something along the lines of `python3-devel` (RedHat), `python3-all-dev` (Debian), etc. Alternatively, you can install directly from pip after installing the above depedencies (C compiler, Python development libraries): pip install pyxattr Or you can install already compiled versions from your distribution, e.g. in Debian: sudo apt install python3-pyxattr ## Security For reporting security vulnerabilities, please see `SECURITY.md`. ## Basic example >>> import xattr >>> xattr.listxattr("file.txt") ['user.mime_type'] >>> xattr.getxattr("file.txt", "user.mime_type") 'text/plain' >>> xattr.setxattr("file.txt", "user.comment", "Simple text file") >>> xattr.listxattr("file.txt") ['user.mime_type', 'user.comment'] >>> xattr.removexattr ("file.txt", "user.comment") ## License pyxattr is Copyright 2002-2008, 2012-2015 Iustin Pop. pyxattr is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See the COPYING file for the full license terms. Note that previous versions had different licenses: version 0.3 was licensed under LGPL version 3 (which, I realized later, is not compatible with GPLv2, hence the change to LGPL 2.1), and even older versions were licensed under GPL v2 or later. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681768758.1281602 pyxattr-0.8.1/doc/0000755000000000000000000000000014417340466012547 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768568.0 pyxattr-0.8.1/doc/conf.py0000644000000000000000000001752714417340170014052 0ustar00rootroot# -*- coding: utf-8 -*- # # pyxattr documentation build configuration file, created by # sphinx-quickstart on Sun May 13 01:05:18 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'recommonmark'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = ['.rst', '.md'] # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pyxattr' copyright = u'2002, 2003, 2006, 2008, 2012, 2013, 2014, 2015, Iustin Pop' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.8.1' # The full version, including alpha/beta/rc tags. release = '0.8.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'html'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None default_domain = 'python' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] keep_warnings = True # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True html_domain_indices = False # If false, no index is generated. #html_use_index = True html_use_index = False # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pyxattrdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pyxattr.tex', u'pyxattr Documentation', u'Iustin Pop', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pyxattr', u'pyxattr Documentation', [u'Iustin Pop'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pyxattr', u'pyxattr Documentation', u'Iustin Pop', 'pyxattr', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' autodoc_member_order = 'alphabetical' ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768399.0 pyxattr-0.8.1/doc/contributing.md0000644000000000000000000000421214417337717015604 0ustar00rootroot# Contributing to pyxattr Hi, and thanks for any and all contributions! ## Bugs and patches This is a small project, so let's keep things simple: - Please file all bug reports on github (), as this allows archival and discovery by other people; - Send patches as pull requests; for larger changes, would be good to first open a bug to discuss the plans; Due to simplicity, there are no old branches being kept alive, but if it ever happens that a bug is found in older versions and there is needed to support older Python versions, it is possible to do so. ## Code standards There are no formal standards, but: - Code should be tested - this is why there's a [Codecov integration](https://app.codecov.io/gh/iustin/pyxattr/tree/main). - New functions should have good docstrings (in the C code). - New functions/constants should be listed in the documentation, see `doc/module.rst` for how to include them. - All non-trivial changes should be listed in `NEWS.md` for further inclusion in new releases documentation. Add an "unreleased" section (if one doesn't exist yet) to list the changes. ## Release process Right now, due to GPG signing, I'm doing releases and signing them manually (offline, I mean). Basically, once GitHub workflows are fine: - Bump the version in all places - use `git grep -F $OLD_VER` and update as needed. - Ensure that `setup.py` has the right Python versions listed (bit me more than once). - Update the `NEWS.md` file is up to date (contents), and use the right date. - Check that the generated documentation (`make doc`) looks right. Then run these steps: ``` $ make clean $ make distcheck # this leaves things in dist/ $ git tag -m 'Release pyxattr-0.0.1' --sign v0.0.1 $ gpg --sign -b -a dist/pyxattr-0.0.1.tar.gz $ python3 -m twine upload dist/* ``` Separately: * Upload the `dist/` contents to GitHub and tag a new release. * Upload the `dist/` contents to the old-style download area, . Hopefully one day all this can be more automated. ## Signing key The releases are currently signed by my key, see . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768040.0 pyxattr-0.8.1/doc/index.rst0000644000000000000000000000055114417337150014405 0ustar00rootroot====================================== Welcome to pyxattr's documentation! ====================================== See the :doc:`README ` for start, or the detailed :doc:`module ` information. Contents -------- .. toctree:: :maxdepth: 2 readme.md contributing.md security.md module.rst news.md Also see the :ref:`search`. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1622908239.0 pyxattr-0.8.1/doc/module.rst0000644000000000000000000000223214056716517014570 0ustar00rootrootInterface to extended filesystem attributes =========================================== .. automodule:: xattr Constants --------- .. data:: XATTR_CREATE Used as flags value, the target attribute will be created, giving an error if it already exists. .. data:: XATTR_REPLACE Used as flags value, the target attribute will be replaced, giving an error if it doesn't exist. .. data:: NS_SECURITY The security name space, used by kernel security modules to store (for example) capabilities information. .. data:: NS_SYSTEM The system name space, used by the kernel to store (for example) ACLs. .. data:: NS_TRUSTED The trusted name space, visible and accessibly only to trusted processes, used to implement mechanisms in user space. .. data:: NS_USER The user name space; this is the name space accessible to non-privileged processes. Functions --------- .. autofunction:: list .. autofunction:: get .. autofunction:: get_all .. autofunction:: set .. autofunction:: remove Deprecated functions -------------------- .. autofunction:: getxattr .. autofunction:: setxattr .. autofunction:: listxattr .. autofunction:: removexattr ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768236.0 pyxattr-0.8.1/doc/news.md0000644000000000000000000001731714417337454014061 0ustar00rootroot# News ## Version 0.8.1 *Mon, 17 Apr 2023* Very minor release: * Fix the pypi declared python versions * Add some more documentation - a security policy, and a contributing guide. * Restore yet again the CI environment :/ ## Version 0.8.0 *Mon, 12 Dec 2022* Minor bugfix release, but due to lack of CI environments supporting old Python versions, only Python 3.7+ is supported. Otherwise: * Snape3058@ found some refcount issues (see issue #35), these have been fixed. * Tested and enabled Python 3.10 support, dropped < 3.7. * Various improvements to the CI environments. * Move fully to `setuptools` (where available), in preparation for 3.12 dropping `distutils` support. ## Version 0.7.2 *Sun, 29 Nov 2020* Minor release: * Expand testing by adding better mixed-access checks (e.g. set via symlink and read on file) and by not leaking resources during tests. * Enable testing with Python 3.9 and confirm compatibility with it. * Fix documentation building with Sphinx 3.0+. ## Version 0.7.1 *released Tue, 26 Nov 2019* Typo fix release in the bug tracker link :/ ## Version 0.7.0 *released Tue, 26 Nov 2019* Major change: drop compatibility with Python 2, which allows significant code cleanups. Other changes: * Switch internal implementation of argument parsing to a built-in one (`PyUnicode_FSConverter`), which brings automatic support for path-like objects in Python 3.6+ (#20), and also a more uniform handling of Unicode path arguments with respect to other Python code. * Fix missing error check in list operations in `get_all` (#17). * Switch test library to pytest; not that a reasonable recent version is needed. Additionally, expand test coverage, although not directly visible in actual coverage reports… ## Version 0.6.1 *released Tue, 24 Jul 2018* Minor bugfix, performance and compatibility release. * Minor compatibility fix: on Linux, drop the use of the `attr` library, and instead switch to the glibc header `sys/xattr.h`, which is provided for a really long time (since glibc 2.3). The formerly used header `attr/xattr.h` has been removed from the `attr` library in version 2.4.48. Fix provided by Lars Wendler, many thanks! * Release the GIL when performing I/O. Patch proposed by xwhuang, many thanks. I tested this a long while back it seemed to impact performance on local filesystems, but upon further inspection, the downsides are minor (between 0 and 5%, in many cases negligible). For remote or slow filesystems, this should allow much increased parallelism. * Fix symlink set operation on MacOS X; bugfix provided by adamlin, much appreciated! This also uncovered testing problems related to symlinks, which are now fixed (the bug would be caught by the updated tests). ## Version 0.6.0 *released Mon, 23 Jan 2017* Bugfix and feature release (hence the version bump). The main change is to the implementation of how attributes are listed and read. This was done due to existing race issues when attributes are modified while being read (github issue #12), but basically all various internal paths that dealt with retrieving an attribute value or listing attributes were unified in a single helper function that does handle such concurrent modifications. As a side effect, the size of the buffers used for such reads have changed, which (depending on attribute value) might change the trade-off between number of syscalls done and memory usage. As feature release, OSX support was contributed by Adam Knight , thanks a lot! I don't have access to OSX so the testing for it is done via Travis builds; please report any issues. ## Version 0.5.6 *released Sat, 09 Apr 2016* Small bugfix release: * Fixes some sign-compare warnings * Fixes potential name truncation in merge_ns() * Fixes building on systems which don't have ENODATA Tested with Python 2.7.11, Python 3.5.1 and PyPy 5.0.1. ## Version 0.5.5 *released Fri, 01 May 2015* Bugfix release: * fixes some more memory leaks when handling out-of-memory in get_all() function * improve error reporting when an attribute disappears after we asked for its length but before we managed to read it * fix int/size_t issues found by RedHat/Fedora, https://bugzilla.redhat.com/show_bug.cgi?id=1127310; the fix is different than their fix, but it should accomplish the same thing * convert all code to only do explicit casts after checking boundaries, making the code `-Wconversion`-clean (although that warning is not enabled by default) ## Version 0.5.4 *released Thu, 30 Apr 2015* Fix memory leaks on some of the error-handling paths of the `get()` function. ## Version 0.5.3 *released Fri, 23 May 2014* Small optimisations release: * ari edelkind contributed a speed-up optimisation for handling of files without xattrs (which is, in general, the expected case) * Jonas Borgström contributed a behaviour change to the handling of file names: under Python 3 and up, unicode paths are encoded/decoded using the 'surogatee' handler, instead of the 'strict' handler; while this can hide encoding errors, it mirrors what Python libraries do (e.g. see os.fsencode/fsdecode) * Sean Patrick Santos contributed improvements to the test suite so that it can be used even on files systems which have built-in attributes (e.g. when using SELinux, or NFSv4); to enable this, define the attributes in the TEST_IGNORE_XATTRS environment variable ## Version 0.5.2 *released Thu, 03 Jan 2013* Bug-fix release. Thanks to Michał Górny, it looked like the library had problem running under pypy, but actually there was a bug in the PyArg_ParseTuple use of et# (signed vs. unsigned, and lack of compiler warnings). This was fixed, and now the test suite passed with many CPython versions and PyPy (version 1.9). ## Version 0.5.1 *released Wed, 16 May 2012* Bug-fix release. Thanks to Dave Malcolm and his cpychecker tool, a number of significant bugs (refcount leaks and potential NULL-pointer dereferences) have been fixed. Furthermore, compatibility with Python 3 has been improved; this however required changing the meaning of the ``namespace`` argument to the functions: if passed, None is no longer a valid value; pass an empty string if (due to the structure of your program) you have to pass this argument but want to specify no namespace. Also, the project home page has changed from SourceForge to GitHub, and the documentation has been converted from epydoc-based to sphinx. ## Version 0.5 *released Sun, 27 Dec 2009* Implemented support for Python 3. This required a significant change to the C module, hence the new version number. ## Version 0.4 *released Mon, 30 Jun 2008* ### API The old functions ({get,set,list,remove}xattr) are deprecated and replaced with a new API that is namespace-aware and hopefully will allow other OSes (e.g. FreeBSD) to be supported more naturally. Both the old and the new API are supported in the 0.4 versions, however users are encouraged to migrate to the new API. ### New features A new bulk get function called get_all() has been added that should be somewhat faster in case of querying files which have many attributes. ### License Since LGPLv3 is not compatible with GPLv2 (which unfortunately I didn't realize before), the license was changed to LGPLv2.1 or later. ### Internals Unittest coverage was improved. ## Version 0.3 *released Sun, 09 Mar 2008* * changed licence from GPL to LGPL (3 or later) * changed listxattr return type from tuple to a list * developer-related: added unittests ## Version 0.2.2 *released Sun, 01 Jul 2007* * fixed listing symlink xattrs ## Version 0.2.1 *released Sat, 11 Feb 2006* * fixed a bug when reading symlink EAs (you weren't able to do it, actually) * fixed a possible memory leak when the actual read of the EA failed but the call to get the length of the EA didn't ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681767256.0 pyxattr-0.8.1/doc/readme.md0000644000000000000000000000760414417335530014331 0ustar00rootroot# pyxattr This is the pyxattr module, a Python extension module which gives access to the extended attributes for filesystem objects available in some operating systems. [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/iustin/pyxattr/ci.yml?branch=main)](https://github.com/iustin/pyxattr/actions/workflows/ci.yml) [![Codecov](https://img.shields.io/codecov/c/github/iustin/pyxattr)](https://codecov.io/gh/iustin/pyxattr) [![Read the Docs](https://img.shields.io/readthedocs/pyxattr)](https://pyxattr.readthedocs.io/en/latest/?badge=latest) [![GitHub issues](https://img.shields.io/github/issues/iustin/pyxattr)](https://github.com/iustin/pyxattr/issues) ![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/iustin/pyxattr) [![GitHub release (latest by date)](https://img.shields.io/github/v/release/iustin/pyxattr)](https://github.com/iustin/pyxattr/releases) [![PyPI](https://img.shields.io/pypi/v/pyxattr)](https://pypi.org/project/pyxattr/) ![Debian package](https://img.shields.io/debian/v/python-pyxattr) ![Ubuntu package](https://img.shields.io/ubuntu/v/python-pyxattr) ![GitHub Release Date](https://img.shields.io/github/release-date/iustin/pyxattr) ![GitHub commits since latest release](https://img.shields.io/github/commits-since/iustin/pyxattr/latest) ![GitHub last commit](https://img.shields.io/github/last-commit/iustin/pyxattr) [![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/7236/badge)](https://bestpractices.coreinfrastructure.org/projects/7236) Downloads: go to . The source repository is either at or at . See the `CONTRIBUTING.md` file for details on how to contribute. ## Requirements The current supported Python versions are 3.7+ (tested up to 3.10), or PyPy versions 3.7+ (tested up to 3.9). The code should currently be compatible down to Python 3.4, but such versions are no longer tested. The library has been written and tested on Linux, kernel v2.4 or later, with XFS and ext2/ext3/ext4 file systems, and MacOS recent versions. If any other platform implements the same behaviour, pyxattr could be used. To build the module from source, you will need both a Python development environment/libraries and the C compiler, plus the setuptools tool installed, and for building the documentation you need to have Sphinx installed. The exact list of dependencies depends on the operating system/distribution, but should be something along the lines of `python3-devel` (RedHat), `python3-all-dev` (Debian), etc. Alternatively, you can install directly from pip after installing the above depedencies (C compiler, Python development libraries): pip install pyxattr Or you can install already compiled versions from your distribution, e.g. in Debian: sudo apt install python3-pyxattr ## Security For reporting security vulnerabilities, please see `SECURITY.md`. ## Basic example >>> import xattr >>> xattr.listxattr("file.txt") ['user.mime_type'] >>> xattr.getxattr("file.txt", "user.mime_type") 'text/plain' >>> xattr.setxattr("file.txt", "user.comment", "Simple text file") >>> xattr.listxattr("file.txt") ['user.mime_type', 'user.comment'] >>> xattr.removexattr ("file.txt", "user.comment") ## License pyxattr is Copyright 2002-2008, 2012-2015 Iustin Pop. pyxattr is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See the COPYING file for the full license terms. Note that previous versions had different licenses: version 0.3 was licensed under LGPL version 3 (which, I realized later, is not compatible with GPLv2, hence the change to LGPL 2.1), and even older versions were licensed under GPL v2 or later. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681659530.0 pyxattr-0.8.1/doc/security.md0000644000000000000000000000121014417013212014714 0ustar00rootroot# Security Policy To report a (potential or confirmed) security issue, please email with a description of the issue, steps to reproduce it, affected versions, and if known, mitigations for the issue. Since this is a small project, there's no list of supported versions. I will attempt to reply to reports within a working week, and to fix and disclose vulnerabilities within 90 days, but this is not a guarantee. Optionally, you can encrypt the email with my GPG key, see for details . Alternatively, you can use the GitHub "Private vulnerability reporting" functionality (but note this is beta). ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681768758.1281602 pyxattr-0.8.1/pyxattr.egg-info/0000755000000000000000000000000014417340466015207 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768758.0 pyxattr-0.8.1/pyxattr.egg-info/PKG-INFO0000644000000000000000000000216314417340466016306 0ustar00rootrootMetadata-Version: 2.1 Name: pyxattr Version: 0.8.1 Summary: Filesystem extended attributes for python Home-page: https://pyxattr.k1024.org/ Download-URL: https://pyxattr.k1024.org/downloads/ Author: Iustin Pop Author-email: iustin@k1024.org License: LGPL Project-URL: Bug Tracker, https://github.com/iustin/pyxattr/issues Platform: Linux Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+) Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: POSIX :: Linux Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Filesystems Requires-Python: >=3.7 License-File: COPYING This is a C extension module for Python which implements extended attributes manipulation. It is a wrapper on top of the attr C library - see attr(5). ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768758.0 pyxattr-0.8.1/pyxattr.egg-info/SOURCES.txt0000644000000000000000000000052214417340466017072 0ustar00rootrootCOPYING MANIFEST.in Makefile NEWS.md README.md setup.cfg setup.py xattr.c doc/conf.py doc/contributing.md doc/index.rst doc/module.rst doc/news.md doc/readme.md doc/security.md pyxattr.egg-info/PKG-INFO pyxattr.egg-info/SOURCES.txt pyxattr.egg-info/dependency_links.txt pyxattr.egg-info/top_level.txt tests/__init__.py tests/test_xattr.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768758.0 pyxattr-0.8.1/pyxattr.egg-info/dependency_links.txt0000644000000000000000000000000114417340466021255 0ustar00rootroot ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768758.0 pyxattr-0.8.1/pyxattr.egg-info/top_level.txt0000644000000000000000000000000614417340466017735 0ustar00rootrootxattr ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681768758.1281602 pyxattr-0.8.1/setup.cfg0000644000000000000000000000012214417340466013616 0ustar00rootroot[bdist_rpm] release = 1 requires = libattr [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681768577.0 pyxattr-0.8.1/setup.py0000755000000000000000000000365514417340201013513 0ustar00rootroot#!/usr/bin/env python3 import platform try: from setuptools import setup, Extension except ImportError: from distutils.core import setup, Extension long_desc = """This is a C extension module for Python which implements extended attributes manipulation. It is a wrapper on top of the attr C library - see attr(5).""" version = "0.8.1" author = "Iustin Pop" author_email = "iustin@k1024.org" libraries = [] macros = [ ("_XATTR_VERSION", '"%s"' % version), ("_XATTR_AUTHOR", '"%s"' % author), ("_XATTR_EMAIL", '"%s"' % author_email), ] setup(name = "pyxattr", version = version, description = "Filesystem extended attributes for python", long_description = long_desc, author = author, author_email = author_email, url = "https://pyxattr.k1024.org/", download_url = "https://pyxattr.k1024.org/downloads/", license = "LGPL", ext_modules = [Extension("xattr", ["xattr.c"], libraries=libraries, define_macros=macros, extra_compile_args=["-Wall", "-Werror", "-Wsign-compare"], )], platforms = ["Linux"], python_requires = ">=3.7", project_urls={ "Bug Tracker": "https://github.com/iustin/pyxattr/issues", }, classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: Linux", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Filesystems", ] ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681768758.1281602 pyxattr-0.8.1/tests/0000755000000000000000000000000014417340466013144 5ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1337031917.0 pyxattr-0.8.1/tests/__init__.py0000644000000000000000000000000011754276355015251 0ustar00rootroot././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1622914245.0 pyxattr-0.8.1/tests/test_xattr.py0000644000000000000000000003775614056732305015735 0ustar00rootroot# # import sys import tempfile import os import errno import pytest import pathlib import platform import io import contextlib import xattr from xattr import NS_USER, XATTR_CREATE, XATTR_REPLACE NAMESPACE = os.environ.get("NAMESPACE", NS_USER) EMPTY_NS = bytes() TEST_DIR = os.environ.get("TEST_DIR", ".") TEST_IGNORE_XATTRS = os.environ.get("TEST_IGNORE_XATTRS", "") if TEST_IGNORE_XATTRS == "": TEST_IGNORE_XATTRS = [] else: TEST_IGNORE_XATTRS = TEST_IGNORE_XATTRS.split(",") # The following has to be a list comprehension, not a generator, to # avoid weird consequences of lazy evaluation. TEST_IGNORE_XATTRS.extend([a.encode() for a in TEST_IGNORE_XATTRS]) USER_NN = "test" USER_ATTR = NAMESPACE.decode() + "." + USER_NN USER_VAL = "abc" EMPTY_VAL = "" LARGE_VAL = "x" * 2048 MANYOPS_COUNT = 16384 USER_NN = USER_NN.encode() USER_VAL = USER_VAL.encode() USER_ATTR = USER_ATTR.encode() EMPTY_VAL = EMPTY_VAL.encode() LARGE_VAL = LARGE_VAL.encode() # Helper functions def ignore_tuples(attrs): """Remove ignored attributes from the output of xattr.get_all.""" return [attr for attr in attrs if attr[0] not in TEST_IGNORE_XATTRS] def ignore(attrs): """Remove ignored attributes from the output of xattr.list""" return [attr for attr in attrs if attr not in TEST_IGNORE_XATTRS] def lists_equal(attrs, value): """Helper to check list equivalence, skipping TEST_IGNORE_XATTRS.""" assert ignore(attrs) == value def tuples_equal(attrs, value): """Helper to check list equivalence, skipping TEST_IGNORE_XATTRS.""" assert ignore_tuples(attrs) == value # Fixtures and helpers @pytest.fixture def testdir(): """per-test temp dir based in TEST_DIR""" with tempfile.TemporaryDirectory(dir=TEST_DIR) as dname: yield dname def get_file(path): fh, fname = tempfile.mkstemp(".test", "xattr-", path) return fh, fname @contextlib.contextmanager def get_file_name(path): fh, fname = get_file(path) os.close(fh) yield fname @contextlib.contextmanager def get_file_fd(path): fd = get_file(path)[0] yield fd os.close(fd) @contextlib.contextmanager def get_file_object(path): fd = get_file(path)[0] with os.fdopen(fd) as f: yield f @contextlib.contextmanager def get_dir(path): yield tempfile.mkdtemp(".test", "xattr-", path) def get_symlink(path, dangling=True): """create a symlink""" fh, fname = get_file(path) os.close(fh) if dangling: os.unlink(fname) sname = fname + ".symlink" os.symlink(fname, sname) return fname, sname @contextlib.contextmanager def get_valid_symlink(path): yield get_symlink(path, dangling=False)[1] @contextlib.contextmanager def get_dangling_symlink(path): yield get_symlink(path, dangling=True)[1] @contextlib.contextmanager def get_file_and_symlink(path): yield get_symlink(path, dangling=False) @contextlib.contextmanager def get_file_and_fobject(path): fh, fname = get_file(path) with os.fdopen(fh) as fo: yield fname, fo # Wrappers that build upon existing values def as_wrapper(call, fn, closer=None): @contextlib.contextmanager def f(path): with call(path) as r: val = fn(r) yield val if closer is not None: closer(val) return f def as_bytes(call): return as_wrapper(call, lambda r: r.encode()) def as_fspath(call): return as_wrapper(call, pathlib.PurePath) def as_iostream(call): opener = lambda f: io.open(f, "r") closer = lambda r: r.close() return as_wrapper(call, opener, closer) NOT_BEFORE_36 = pytest.mark.xfail(condition="sys.version_info < (3,6)", strict=True) NOT_PYPY = pytest.mark.xfail(condition="platform.python_implementation() == 'PyPy'", strict=False) NOT_MACOSX = pytest.mark.xfail(condition="sys.platform.startswith('darwin')", reason="Test not supported on MacOS", strict=True) # Note: user attributes are only allowed on files and directories, so # we have to skip the symlinks here. See xattr(7). ITEMS_P = [ (get_file_name, False), (as_bytes(get_file_name), False), pytest.param((as_fspath(get_file_name), False), marks=[NOT_BEFORE_36, NOT_PYPY]), (get_file_fd, False), (get_file_object, False), (as_iostream(get_file_name), False), (get_dir, False), (as_bytes(get_dir), False), pytest.param((as_fspath(get_dir), False), marks=[NOT_BEFORE_36, NOT_PYPY]), (get_valid_symlink, False), (as_bytes(get_valid_symlink), False), pytest.param((as_fspath(get_valid_symlink), False), marks=[NOT_BEFORE_36, NOT_PYPY]), ] ITEMS_D = [ "file name", "file name (bytes)", "file name (path)", "file FD", "file object", "file io stream", "directory", "directory (bytes)", "directory (path)", "file via symlink", "file via symlink (bytes)", "file via symlink (path)", ] ALL_ITEMS_P = ITEMS_P + [ (get_valid_symlink, True), (as_bytes(get_valid_symlink), True), (get_dangling_symlink, True), (as_bytes(get_dangling_symlink), True), ] ALL_ITEMS_D = ITEMS_D + [ "valid symlink", "valid symlink (bytes)", "dangling symlink", "dangling symlink (bytes)" ] @pytest.fixture(params=ITEMS_P, ids=ITEMS_D) def subject(testdir, request): with request.param[0](testdir) as value: yield value, request.param[1] @pytest.fixture(params=ALL_ITEMS_P, ids=ALL_ITEMS_D) def any_subject(testdir, request): with request.param[0](testdir) as value: yield value, request.param[1] @pytest.fixture(params=[True, False], ids=["with namespace", "no namespace"]) def use_ns(request): return request.param @pytest.fixture(params=[True, False], ids=["dangling", "valid"]) def use_dangling(request): return request.param ### Test functions def test_empty_value(subject): item, nofollow = subject xattr.set(item, USER_ATTR, EMPTY_VAL, nofollow=nofollow) assert xattr.get(item, USER_ATTR, nofollow=nofollow) == EMPTY_VAL def test_large_value(subject): item, nofollow = subject xattr.set(item, USER_ATTR, LARGE_VAL) assert xattr.get(item, USER_ATTR, nofollow=nofollow) == LARGE_VAL @pytest.mark.parametrize( "gen", [ get_file_and_symlink, get_file_and_fobject ]) def test_mixed_access(testdir, gen): """test mixed access to file""" with gen(testdir) as (a, b): # Check empty lists_equal(xattr.list(a), []) lists_equal(xattr.listxattr(b), []) # Check value xattr.set(a, USER_ATTR, USER_VAL) for i in [a, b]: # Deprecated functions lists_equal(xattr.listxattr(i), [USER_ATTR]) assert xattr.getxattr(i, USER_ATTR) == USER_VAL tuples_equal(xattr.get_all(i), [(USER_ATTR, USER_VAL)]) # Current functions lists_equal(xattr.list(i), [USER_ATTR]) assert xattr.list(i, namespace=NAMESPACE) == [USER_NN] assert xattr.get(i, USER_ATTR) == USER_VAL assert xattr.get(i, USER_NN, namespace=NAMESPACE) == USER_VAL tuples_equal(xattr.get_all(i), [(USER_ATTR, USER_VAL)]) assert xattr.get_all(i, namespace=NAMESPACE) == \ [(USER_NN, USER_VAL)] # Overwrite xattr.set(b, USER_ATTR, LARGE_VAL, flags=xattr.XATTR_REPLACE) assert xattr.get(a, USER_ATTR) == LARGE_VAL assert xattr.getxattr(a, USER_ATTR) == LARGE_VAL xattr.removexattr(b, USER_ATTR) assert xattr.get_all(a, namespace=NAMESPACE) == [] assert xattr.get_all(b, namespace=NAMESPACE) == [] def test_replace_on_missing(subject, use_ns): item = subject[0] lists_equal(xattr.list(item), []) with pytest.raises(EnvironmentError): if use_ns: xattr.set(item, USER_NN, USER_VAL, flags=XATTR_REPLACE, namespace=NAMESPACE) else: xattr.set(item, USER_ATTR, USER_VAL, flags=XATTR_REPLACE) def test_create_on_existing(subject, use_ns): item = subject[0] lists_equal(xattr.list(item), []) if use_ns: xattr.set(item, USER_NN, USER_VAL, namespace=NAMESPACE) else: xattr.set(item, USER_ATTR, USER_VAL) with pytest.raises(EnvironmentError): if use_ns: xattr.set(item, USER_NN, USER_VAL, flags=XATTR_CREATE, namespace=NAMESPACE) else: xattr.set(item, USER_ATTR, USER_VAL, flags=XATTR_CREATE) def test_remove_on_missing(any_subject, use_ns): item, nofollow = any_subject lists_equal(xattr.list(item, nofollow=nofollow), []) with pytest.raises(EnvironmentError): if use_ns: xattr.remove(item, USER_NN, namespace=NAMESPACE, nofollow=nofollow) else: xattr.remove(item, USER_ATTR, nofollow=nofollow) def test_set_get_remove(subject, use_ns): item = subject[0] lists_equal(xattr.list(item), []) if use_ns: xattr.set(item, USER_NN, USER_VAL, namespace=NAMESPACE) else: xattr.set(item, USER_ATTR, USER_VAL) if use_ns: assert xattr.list(item, namespace=NAMESPACE) == [USER_NN] else: lists_equal(xattr.list(item), [USER_ATTR]) lists_equal(xattr.list(item, namespace=EMPTY_NS), [USER_ATTR]) if use_ns: assert xattr.get(item, USER_NN, namespace=NAMESPACE) == USER_VAL else: assert xattr.get(item, USER_ATTR) == USER_VAL if use_ns: assert xattr.get_all(item, namespace=NAMESPACE) == \ [(USER_NN, USER_VAL)] else: tuples_equal(xattr.get_all(item), [(USER_ATTR, USER_VAL)]) if use_ns: xattr.remove(item, USER_NN, namespace=NAMESPACE) else: xattr.remove(item, USER_ATTR) lists_equal(xattr.list(item), []) tuples_equal(xattr.get_all(item), []) def test_replace_on_missing_deprecated(subject): item = subject[0] lists_equal(xattr.listxattr(item), []) with pytest.raises(EnvironmentError): xattr.setxattr(item, USER_ATTR, USER_VAL, XATTR_REPLACE) def test_create_on_existing_deprecated(subject): item = subject[0] lists_equal(xattr.listxattr(item), []) xattr.setxattr(item, USER_ATTR, USER_VAL, 0) with pytest.raises(EnvironmentError): xattr.setxattr(item, USER_ATTR, USER_VAL, XATTR_CREATE) def test_remove_on_missing_deprecated(any_subject): """check deprecated list, set, get operations against an item""" item, nofollow = any_subject lists_equal(xattr.listxattr(item, nofollow), []) with pytest.raises(EnvironmentError): xattr.removexattr(item, USER_ATTR) def test_set_get_remove_deprecated(subject): """check deprecated list, set, get operations against an item""" item = subject[0] lists_equal(xattr.listxattr(item), []) xattr.setxattr(item, USER_ATTR, USER_VAL, 0) lists_equal(xattr.listxattr(item), [USER_ATTR]) assert xattr.getxattr(item, USER_ATTR) == USER_VAL tuples_equal(xattr.get_all(item), [(USER_ATTR, USER_VAL)]) xattr.removexattr(item, USER_ATTR) lists_equal(xattr.listxattr(item), []) tuples_equal(xattr.get_all(item), []) def test_many_ops(subject): """test many ops""" item = subject[0] xattr.set(item, USER_ATTR, USER_VAL) VL = [USER_ATTR] VN = [USER_NN] for i in range(MANYOPS_COUNT): lists_equal(xattr.list(item), VL) lists_equal(xattr.list(item, namespace=EMPTY_NS), VL) assert xattr.list(item, namespace=NAMESPACE) == VN for i in range(MANYOPS_COUNT): assert xattr.get(item, USER_ATTR) == USER_VAL assert xattr.get(item, USER_NN, namespace=NAMESPACE) == USER_VAL for i in range(MANYOPS_COUNT): tuples_equal(xattr.get_all(item), [(USER_ATTR, USER_VAL)]) assert xattr.get_all(item, namespace=NAMESPACE) == \ [(USER_NN, USER_VAL)] def test_many_ops_deprecated(subject): """test many ops (deprecated functions)""" item = subject[0] xattr.setxattr(item, USER_ATTR, USER_VAL) VL = [USER_ATTR] for i in range(MANYOPS_COUNT): lists_equal(xattr.listxattr(item), VL) for i in range(MANYOPS_COUNT): assert xattr.getxattr(item, USER_ATTR) == USER_VAL for i in range(MANYOPS_COUNT): tuples_equal(xattr.get_all(item), [(USER_ATTR, USER_VAL)]) def test_no_attributes_deprecated(any_subject): """test no attributes (deprecated functions)""" item, nofollow = any_subject lists_equal(xattr.listxattr(item, True), []) tuples_equal(xattr.get_all(item, True), []) with pytest.raises(EnvironmentError): xattr.getxattr(item, USER_ATTR, True) def test_no_attributes(any_subject): """test no attributes""" item, nofollow = any_subject lists_equal(xattr.list(item, nofollow=nofollow), []) assert xattr.list(item, nofollow=nofollow, namespace=NAMESPACE) == [] tuples_equal(xattr.get_all(item, nofollow=nofollow), []) assert xattr.get_all(item, nofollow=nofollow, namespace=NAMESPACE) == [] with pytest.raises(EnvironmentError): xattr.get(item, USER_NN, nofollow=nofollow, namespace=NAMESPACE) def test_binary_payload_deprecated(subject): """test binary values (deprecated functions)""" item = subject[0] BINVAL = b"abc\0def" xattr.setxattr(item, USER_ATTR, BINVAL) lists_equal(xattr.listxattr(item), [USER_ATTR]) assert xattr.getxattr(item, USER_ATTR) == BINVAL tuples_equal(xattr.get_all(item), [(USER_ATTR, BINVAL)]) xattr.removexattr(item, USER_ATTR) def test_binary_payload(subject): """test binary values""" item = subject[0] BINVAL = b"abc\0def" xattr.set(item, USER_ATTR, BINVAL) lists_equal(xattr.list(item), [USER_ATTR]) assert xattr.list(item, namespace=NAMESPACE) == [USER_NN] assert xattr.get(item, USER_ATTR) == BINVAL assert xattr.get(item, USER_NN, namespace=NAMESPACE) == BINVAL tuples_equal(xattr.get_all(item), [(USER_ATTR, BINVAL)]) assert xattr.get_all(item, namespace=NAMESPACE) == [(USER_NN, BINVAL)] xattr.remove(item, USER_ATTR) @NOT_MACOSX def test_symlinks_user_fail(testdir, use_dangling): _, sname = get_symlink(testdir, dangling=use_dangling) with pytest.raises(IOError): xattr.set(sname, USER_ATTR, USER_VAL, nofollow=True) with pytest.raises(IOError): xattr.set(sname, USER_NN, USER_VAL, namespace=NAMESPACE, nofollow=True) with pytest.raises(IOError): xattr.setxattr(sname, USER_ATTR, USER_VAL, XATTR_CREATE, True) @pytest.mark.parametrize( "call, args", [(xattr.get, [USER_ATTR]), (xattr.list, []), (xattr.remove, [USER_ATTR]), (xattr.get, [USER_ATTR]), (xattr.set, [USER_ATTR, USER_VAL])]) def test_none_namespace(testdir, call, args): # Don't want to use subject, since that would prevent xfail test # on path objects (due to hiding the exception here). f = get_file_name(testdir) with pytest.raises(TypeError): call(f, *args, namespace=None) fd = get_file_fd(testdir) with pytest.raises(TypeError): call(fd, *args, namespace=None) @pytest.mark.parametrize( "call", [xattr.get, xattr.list, xattr.listxattr, xattr.remove, xattr.removexattr, xattr.set, xattr.setxattr, xattr.get, xattr.getxattr]) def test_wrong_call(call): with pytest.raises(TypeError): call() @pytest.mark.parametrize( "call, args", [(xattr.get, [USER_ATTR]), (xattr.listxattr, []), (xattr.list, []), (xattr.remove, [USER_ATTR]), (xattr.removexattr, [USER_ATTR]), (xattr.get, [USER_ATTR]), (xattr.getxattr, [USER_ATTR]), (xattr.set, [USER_ATTR, USER_VAL]), (xattr.setxattr, [USER_ATTR, USER_VAL])]) def test_wrong_argument_type(call, args): with pytest.raises(TypeError): call(object(), *args) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1665696931.0 pyxattr-0.8.1/xattr.c0000644000000000000000000011130614322102243013272 0ustar00rootroot/* xattr - a python module for manipulating filesystem extended attributes Copyright (C) 2002, 2003, 2006, 2008, 2012, 2013, 2015 Iustin Pop This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define PY_SSIZE_T_CLEAN #include #if defined(__APPLE__) || defined(__linux__) #include #endif #include #define ITEM_DOC \ ":param item: a string representing a file-name, a file-like\n" \ " object, a file descriptor, or (in Python 3.6+) a path-like\n" \ " object; this represents the file on which to act\n" #define NOFOLLOW_DOC \ ":param nofollow: if true and if\n" \ " the file name given is a symbolic link, the\n" \ " function will operate on the symbolic link itself instead\n" \ " of its target; defaults to false\n" \ ":type nofollow: boolean, optional\n" \ #define NS_DOC \ ":param namespace: if given, the attribute must not contain the\n" \ " namespace, but instead it will be taken from this parameter\n" \ ":type namespace: bytes\n" #define NAME_GET_DOC \ ":param string name: the attribute whose value to retrieve;\n" \ " usually in the form of ``system.posix_acl`` or ``user.mime_type``\n" #define NAME_SET_DOC \ ":param string name: the attribute whose value to set;\n" \ " usually in the form of ``system.posix_acl`` or ``user.mime_type``\n" #define NAME_REMOVE_DOC \ ":param string name: the attribute to remove;\n" \ " usually in the form of ``system.posix_acl`` or \n" \ " ``user.mime_type``\n" #define VALUE_DOC \ ":param string value: possibly with embedded NULLs; note that there\n" \ " are restrictions regarding the size of the value, for\n" \ " example, for ext2/ext3, maximum size is the block size\n" \ #define FLAGS_DOC \ ":param flags: if 0 or omitted the attribute will be\n" \ " created or replaced; if :const:`XATTR_CREATE`, the attribute\n" \ " will be created, giving an error if it already exists;\n" \ " if :const:`XATTR_REPLACE`, the attribute will be replaced,\n" \ " giving an error if it doesn't exist;\n" \ ":type flags: integer\n" #define NS_CHANGED_DOC \ ".. versionchanged:: 0.5.1\n" \ " The namespace argument, if passed, cannot be None anymore; to\n" \ " explicitly specify an empty namespace, pass an empty\n" \ " string (byte string under Python 3)." /* The initial I/O buffer size for list and get operations; if the * actual values will be smaller than this, we save a syscall out of * two and allocate more memory upfront than needed, otherwise we * incur three syscalls (get with ENORANGE, get with 0 to compute * actual size, final get). The test suite is marginally faster (5%) * with this, so it seems worth doing. */ #define ESTIMATE_ATTR_SIZE 1024 typedef enum {T_FD, T_PATH, T_LINK} target_e; typedef struct { target_e type; union { const char *name; int fd; }; PyObject *tmp; } target_t; /* Cleans up a tgt structure */ static void free_tgt(target_t *tgt) { if (tgt->tmp != NULL) { Py_DECREF(tgt->tmp); } } /* Used for cpychecker: */ /* The checker automatically defines this preprocessor name when creating the custom attribute: */ #if defined(WITH_CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION_ATTRIBUTE) #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION \ __attribute__((cpychecker_negative_result_sets_exception)) #else #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION #endif static int convert_obj(PyObject *myobj, target_t *tgt, int nofollow) CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION; static int merge_ns(const char *ns, const char *name, const char **result, char **buf) CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION; /** Converts from a string, file or int argument to what we need. * * Returns -1 on failure, 0 on success. */ static int convert_obj(PyObject *myobj, target_t *tgt, int nofollow) { int fd; tgt->tmp = NULL; if((fd = PyObject_AsFileDescriptor(myobj)) != -1) { tgt->type = T_FD; tgt->fd = fd; return 0; } // PyObject_AsFileDescriptor sets an error when failing, so clear // it such that further code works; some method lookups fail if an // error already occured when called, which breaks at least // PyOS_FSPath (called by FSConverter). PyErr_Clear(); if(PyUnicode_FSConverter(myobj, &(tgt->tmp))) { tgt->type = nofollow ? T_LINK : T_PATH; tgt->name = PyBytes_AS_STRING(tgt->tmp); return 0; } else { // Don't set our own exception type, since we'd ignore the // FSConverter-generated one. tgt->type = T_PATH; tgt->name = NULL; return -1; } } /* Combine a namespace string and an attribute name into a fully-qualified name */ static int merge_ns(const char *ns, const char *name, const char **result, char **buf) { if(ns != NULL && *ns != '\0') { int cnt; /* The value of new_size is related to/must be kept in-sync with the format string below */ size_t new_size = strlen(ns) + 1 + strlen(name) + 1; if((*buf = PyMem_Malloc(new_size)) == NULL) { PyErr_NoMemory(); return -1; } cnt = snprintf(*buf, new_size, "%s.%s", ns, name); if((size_t) cnt >= new_size || cnt < 0) { PyErr_SetString(PyExc_ValueError, "unexpected: can't format the attribute name"); PyMem_Free(*buf); return -1; } *result = *buf; } else { *buf = NULL; *result = name; } return 0; } #if defined(__APPLE__) static inline ssize_t _listxattr(const char *path, char *namebuf, size_t size) { return listxattr(path, namebuf, size, 0); } static inline ssize_t _llistxattr(const char *path, char *namebuf, size_t size) { return listxattr(path, namebuf, size, XATTR_NOFOLLOW); } static inline ssize_t _flistxattr(int fd, char *namebuf, size_t size) { return flistxattr(fd, namebuf, size, 0); } static inline ssize_t _getxattr (const char *path, const char *name, void *value, size_t size) { return getxattr(path, name, value, size, 0, 0); } static inline ssize_t _lgetxattr (const char *path, const char *name, void *value, size_t size) { return getxattr(path, name, value, size, 0, XATTR_NOFOLLOW); } static inline ssize_t _fgetxattr (int filedes, const char *name, void *value, size_t size) { return fgetxattr(filedes, name, value, size, 0, 0); } // [fl]setxattr: Both OS X and Linux define XATTR_CREATE and XATTR_REPLACE for the last option. static inline int _setxattr(const char *path, const char *name, const void *value, size_t size, int flags) { return setxattr(path, name, value, size, 0, flags); } static inline int _lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags) { return setxattr(path, name, value, size, 0, flags | XATTR_NOFOLLOW); } static inline int _fsetxattr(int filedes, const char *name, const void *value, size_t size, int flags) { return fsetxattr(filedes, name, value, size, 0, flags); } static inline int _removexattr(const char *path, const char *name) { return removexattr(path, name, 0); } static inline int _lremovexattr(const char *path, const char *name) { return removexattr(path, name, XATTR_NOFOLLOW); } static inline int _fremovexattr(int filedes, const char *name) { return fremovexattr(filedes, name, 0); } #elif defined(__linux__) #define _listxattr(path, list, size) listxattr(path, list, size) #define _llistxattr(path, list, size) llistxattr(path, list, size) #define _flistxattr(fd, list, size) flistxattr(fd, list, size) #define _getxattr(path, name, value, size) getxattr(path, name, value, size) #define _lgetxattr(path, name, value, size) lgetxattr(path, name, value, size) #define _fgetxattr(fd, name, value, size) fgetxattr(fd, name, value, size) #define _setxattr(path, name, value, size, flags) setxattr(path, name, value, size, flags) #define _lsetxattr(path, name, value, size, flags) lsetxattr(path, name, value, size, flags) #define _fsetxattr(fd, name, value, size, flags) fsetxattr(fd, name, value, size, flags) #define _removexattr(path, name) removexattr(path, name) #define _lremovexattr(path, name) lremovexattr(path, name) #define _fremovexattr(fd, name) fremovexattr(fd, name) #endif typedef ssize_t (*buf_getter)(target_t *tgt, const char *name, void *output, size_t size); static ssize_t _list_obj(target_t *tgt, const char *unused, void *list, size_t size) { ssize_t ret; Py_BEGIN_ALLOW_THREADS; if(tgt->type == T_FD) ret = _flistxattr(tgt->fd, list, size); else if (tgt->type == T_LINK) ret = _llistxattr(tgt->name, list, size); else ret = _listxattr(tgt->name, list, size); Py_END_ALLOW_THREADS; return ret; } static ssize_t _get_obj(target_t *tgt, const char *name, void *value, size_t size) { ssize_t ret; Py_BEGIN_ALLOW_THREADS; if(tgt->type == T_FD) ret = _fgetxattr(tgt->fd, name, value, size); else if (tgt->type == T_LINK) ret = _lgetxattr(tgt->name, name, value, size); else ret = _getxattr(tgt->name, name, value, size); Py_END_ALLOW_THREADS; return ret; } static int _set_obj(target_t *tgt, const char *name, const void *value, size_t size, int flags) { int ret; Py_BEGIN_ALLOW_THREADS; if(tgt->type == T_FD) ret = _fsetxattr(tgt->fd, name, value, size, flags); else if (tgt->type == T_LINK) ret = _lsetxattr(tgt->name, name, value, size, flags); else ret = _setxattr(tgt->name, name, value, size, flags); Py_END_ALLOW_THREADS; return ret; } static int _remove_obj(target_t *tgt, const char *name) { int ret; Py_BEGIN_ALLOW_THREADS; if(tgt->type == T_FD) ret = _fremovexattr(tgt->fd, name); else if (tgt->type == T_LINK) ret = _lremovexattr(tgt->name, name); else ret = _removexattr(tgt->name, name); Py_END_ALLOW_THREADS; return ret; } /* Perform a get/list operation with appropriate buffer size, * determined dynamically. * * Arguments: * - getter: the function that actually does the I/O. * - tgt, name: passed to the getter. * - buffer: pointer to either an already allocated memory area (in * which case size contains its current size), or NULL to * allocate. In all cases (success or failure), the caller should * deallocate the buffer, using PyMem_Free(). * - size: either size of current buffer (if non-NULL), or size for * initial allocation; zero means use a hardcoded initial buffer * size (ESTIMATE_ATTR_SIZE). The value will be updated upon return * with the current buffer size. * - io_errno: if non-NULL, the actual errno will be recorded here; if * zero, the call was successful and the output/size/nval are valid. * * Return value: if positive or zero, buffer will contain the read * value. Otherwise, io_errno will contain the I/O errno, or zero * to signify a Python-level error. In all cases, the Python-level * error is set to the appropriate value. */ static ssize_t _generic_get(buf_getter getter, target_t *tgt, const char *name, char **buffer, size_t *size, int *io_errno) CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION; static ssize_t _generic_get(buf_getter getter, target_t *tgt, const char *name, char **buffer, size_t *size, int *io_errno) { ssize_t res; /* Clear errno for now, will only set it when it fails in I/O. */ if (io_errno != NULL) { *io_errno = 0; } #define EXIT_IOERROR() \ { \ if (io_errno != NULL) { \ *io_errno = errno; \ } \ PyErr_SetFromErrno(PyExc_IOError); \ return -1; \ } /* Initialize the buffer, if needed. */ if (*buffer == NULL) { if (*size == 0) *size = ESTIMATE_ATTR_SIZE; if((*buffer = PyMem_Malloc(*size)) == NULL) { PyErr_NoMemory(); return -1; } } // Try to get the value, while increasing the buffer if too small. while((res = getter(tgt, name, *buffer, *size)) == -1) { if(errno == ERANGE) { ssize_t realloc_size_s = getter(tgt, name, NULL, 0); /* ERANGE + proper size _should_ not fail, but... */ if(realloc_size_s == -1) { EXIT_IOERROR(); } size_t realloc_size = (size_t) realloc_size_s; char *tmp_buf; if((tmp_buf = PyMem_Realloc(*buffer, realloc_size)) == NULL) { PyErr_NoMemory(); return -1; } *buffer = tmp_buf; *size = realloc_size; continue; } else { /* else we're dealing with a different error, which we don't know how to handle nicely, so we return */ EXIT_IOERROR(); } } return res; #undef EXIT_IOERROR } /* Checks if an attribute name matches an optional namespace. If the namespace is NULL or an empty string, it will return the name itself. If the namespace is non-NULL and the name matches, it will return a pointer to the offset in the name after the namespace and the separator. If however the name doesn't match the namespace, it will return NULL. */ const char *matches_ns(const char *ns, const char *name) { size_t ns_size; if (ns == NULL || *ns == '\0') return name; ns_size = strlen(ns); if (strlen(name) > (ns_size+1) && !strncmp(name, ns, ns_size) && name[ns_size] == '.') return name + ns_size + 1; return NULL; } /* Wrapper for getxattr */ static char __pygetxattr_doc__[] = "getxattr(item, attribute[, nofollow=False])\n" "Get the value of a given extended attribute (deprecated).\n" "\n" ITEM_DOC NAME_GET_DOC NOFOLLOW_DOC "\n" ".. deprecated:: 0.4\n" " this function has been deprecated\n" " by the :func:`get` function.\n" ; static PyObject * pygetxattr(PyObject *self, PyObject *args) { PyObject *myarg; target_t tgt; int nofollow = 0; char *attrname = NULL; char *buf = NULL; ssize_t nret; size_t nalloc = 0; PyObject *res; /* Parse the arguments */ if (!PyArg_ParseTuple(args, "Oet|i", &myarg, NULL, &attrname, &nofollow)) return NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) { res = NULL; goto free_arg; } nret = _generic_get(_get_obj, &tgt, attrname, &buf, &nalloc, NULL); if (nret == -1) { res = NULL; goto free_buf; } /* Create the string which will hold the result */ res = PyBytes_FromStringAndSize(buf, nret); free_buf: /* Free the buffer, now it is no longer needed */ PyMem_Free(buf); free_tgt(&tgt); free_arg: PyMem_Free(attrname); /* Return the result */ return res; } /* Wrapper for getxattr */ static char __get_doc__[] = "get(item, name[, nofollow=False, namespace=None])\n" "Get the value of a given extended attribute.\n" "\n" "Example:\n" " >>> xattr.get('/path/to/file', 'user.comment')\n" " 'test'\n" " >>> xattr.get('/path/to/file', 'comment', namespace=xattr.NS_USER)\n" " 'test'\n" "\n" ITEM_DOC NAME_GET_DOC NOFOLLOW_DOC NS_DOC ":return: the value of the extended attribute (can contain NULLs)\n" ":rtype: string\n" ":raises EnvironmentError: caused by any system errors\n" "\n" ".. versionadded:: 0.4\n" NS_CHANGED_DOC ; static PyObject * xattr_get(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *myarg; target_t tgt; int nofollow = 0; char *attrname = NULL, *namebuf; const char *fullname; char *buf = NULL; const char *ns = NULL; ssize_t nret; size_t nalloc = 0; PyObject *res = NULL; static char *kwlist[] = {"item", "name", "nofollow", "namespace", NULL}; /* Parse the arguments */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oet|iy", kwlist, &myarg, NULL, &attrname, &nofollow, &ns)) return NULL; res = NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) { goto free_arg; } if(merge_ns(ns, attrname, &fullname, &namebuf) < 0) { goto free_tgt; } nret = _generic_get(_get_obj, &tgt, fullname, &buf, &nalloc, NULL); if(nret == -1) { goto free_buf; } /* Create the string which will hold the result */ res = PyBytes_FromStringAndSize(buf, nret); /* Free the buffers, they are no longer needed */ free_buf: PyMem_Free(buf); PyMem_Free(namebuf); free_tgt: free_tgt(&tgt); free_arg: PyMem_Free(attrname); /* Return the result */ return res; } /* Wrapper for getxattr */ static char __get_all_doc__[] = "get_all(item[, nofollow=False, namespace=None])\n" "Get all the extended attributes of an item.\n" "\n" "This function performs a bulk-get of all extended attribute names\n" "and the corresponding value.\n" "Example:\n" "\n" " >>> xattr.get_all('/path/to/file')\n" " [('user.mime-type', 'plain/text'), ('user.comment', 'test'),\n" " ('system.posix_acl_access', '\\x02\\x00...')]\n" " >>> xattr.get_all('/path/to/file', namespace=xattr.NS_USER)\n" " [('mime-type', 'plain/text'), ('comment', 'test')]\n" "\n" ITEM_DOC ":keyword namespace: an optional namespace for filtering the\n" " attributes; for example, querying all user attributes can be\n" " accomplished by passing namespace=:const:`NS_USER`\n" ":type namespace: string\n" NOFOLLOW_DOC ":return: list of tuples (name, value); note that if a namespace\n" " argument was passed, it (and the separator) will be stripped from\n" " the names returned\n" ":rtype: list\n" ":raises EnvironmentError: caused by any system errors\n" "\n" ".. note:: Since reading the whole attribute list is not an atomic\n" " operation, it might be possible that attributes are added\n" " or removed between the initial query and the actual reading\n" " of the attributes; the returned list will contain only the\n" " attributes that were present at the initial listing of the\n" " attribute names and that were still present when the read\n" " attempt for the value is made.\n" ".. versionadded:: 0.4\n" NS_CHANGED_DOC ; static PyObject * get_all(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *myarg, *res; int nofollow=0; const char *ns = NULL; char *buf_list = NULL, *buf_val = NULL; const char *s; size_t nalloc = 0; ssize_t nlist, nval; PyObject *mylist; target_t tgt; static char *kwlist[] = {"item", "nofollow", "namespace", NULL}; int io_errno; /* Parse the arguments */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|iy", kwlist, &myarg, &nofollow, &ns)) return NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) return NULL; res = NULL; /* Compute first the list of attributes */ nlist = _generic_get(_list_obj, &tgt, NULL, &buf_list, &nalloc, &io_errno); if (nlist == -1) { /* We can't handle any errors, and the Python error is already set, just bail out. */ goto free_tgt; } /* Create the list which will hold the result. */ mylist = PyList_New(0); if(mylist == NULL) { goto free_buf_list; } nalloc = 0; /* Create and insert the attributes as strings in the list */ for(s = buf_list; s - buf_list < nlist; s += strlen(s) + 1) { PyObject *my_tuple; const char *name; if((name = matches_ns(ns, s)) == NULL) continue; /* Now retrieve the attribute value */ nval = _generic_get(_get_obj, &tgt, s, &buf_val, &nalloc, &io_errno); if (nval == -1) { if (io_errno == ENODATA) { PyErr_Clear(); continue; } else { Py_DECREF(mylist); goto free_buf_val; } } my_tuple = Py_BuildValue("yy#", name, buf_val, nval); if (my_tuple == NULL) { Py_DECREF(mylist); goto free_buf_val; } int lappend_ret = PyList_Append(mylist, my_tuple); Py_DECREF(my_tuple); if(lappend_ret < 0) { Py_DECREF(mylist); goto free_buf_val; } } /* Successful exit */ res = mylist; free_buf_val: PyMem_Free(buf_val); free_buf_list: PyMem_Free(buf_list); free_tgt: free_tgt(&tgt); /* Return the result */ return res; } static char __pysetxattr_doc__[] = "setxattr(item, name, value[, flags=0, nofollow=False])\n" "Set the value of a given extended attribute (deprecated).\n" "\n" "Be careful in case you want to set attributes on symbolic\n" "links, you have to use all the 5 parameters; use 0 for the \n" "flags value if you want the default behaviour (create or " "replace)\n" "\n" ITEM_DOC NAME_SET_DOC VALUE_DOC FLAGS_DOC NOFOLLOW_DOC "\n" ".. deprecated:: 0.4\n" " this function has been deprecated\n" " by the :func:`set` function.\n" ; /* Wrapper for setxattr */ static PyObject * pysetxattr(PyObject *self, PyObject *args) { PyObject *myarg, *res; int nofollow = 0; char *attrname = NULL; char *buf = NULL; Py_ssize_t bufsize_s; size_t bufsize; int nret; int flags = 0; target_t tgt; /* Parse the arguments */ if (!PyArg_ParseTuple(args, "Oetet#|ii", &myarg, NULL, &attrname, NULL, &buf, &bufsize_s, &flags, &nofollow)) return NULL; if (bufsize_s < 0) { PyErr_SetString(PyExc_ValueError, "negative value size?!"); res = NULL; goto free_arg; } bufsize = (size_t) bufsize_s; if(convert_obj(myarg, &tgt, nofollow) < 0) { res = NULL; goto free_arg; } /* Set the attribute's value */ nret = _set_obj(&tgt, attrname, buf, bufsize, flags); free_tgt(&tgt); if(nret == -1) { res = PyErr_SetFromErrno(PyExc_IOError); goto free_arg; } Py_INCREF(Py_None); res = Py_None; free_arg: PyMem_Free(attrname); PyMem_Free(buf); /* Return the result */ return res; } static char __set_doc__[] = "set(item, name, value[, flags=0, namespace=None])\n" "Set the value of a given extended attribute.\n" "\n" "Example:\n" "\n" " >>> xattr.set('/path/to/file', 'user.comment', 'test')\n" " >>> xattr.set('/path/to/file', 'comment', 'test'," " namespace=xattr.NS_USER)\n" "\n" ITEM_DOC NAME_SET_DOC VALUE_DOC FLAGS_DOC NOFOLLOW_DOC NS_DOC ":returns: None\n" ":raises EnvironmentError: caused by any system errors\n" "\n" ".. versionadded:: 0.4\n" NS_CHANGED_DOC ; /* Wrapper for setxattr */ static PyObject * xattr_set(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *myarg, *res; int nofollow = 0; char *attrname = NULL; char *buf = NULL; Py_ssize_t bufsize_s; size_t bufsize; int nret; int flags = 0; target_t tgt; const char *ns = NULL; char *newname; const char *full_name; static char *kwlist[] = {"item", "name", "value", "flags", "nofollow", "namespace", NULL}; /* Parse the arguments */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oetet#|iiy", kwlist, &myarg, NULL, &attrname, NULL, &buf, &bufsize_s, &flags, &nofollow, &ns)) return NULL; if (bufsize_s < 0) { PyErr_SetString(PyExc_ValueError, "negative value size?!"); res = NULL; goto free_arg; } bufsize = (size_t) bufsize_s; if(convert_obj(myarg, &tgt, nofollow) < 0) { res = NULL; goto free_arg; } if(merge_ns(ns, attrname, &full_name, &newname) < 0) { res = NULL; goto free_arg; } /* Set the attribute's value */ nret = _set_obj(&tgt, full_name, buf, bufsize, flags); PyMem_Free(newname); free_tgt(&tgt); if(nret == -1) { res = PyErr_SetFromErrno(PyExc_IOError); goto free_arg; } Py_INCREF(Py_None); res = Py_None; free_arg: PyMem_Free(attrname); PyMem_Free(buf); /* Return the result */ return res; } static char __pyremovexattr_doc__[] = "removexattr(item, name[, nofollow])\n" "Remove an attribute from a file (deprecated).\n" "\n" ITEM_DOC NAME_REMOVE_DOC NOFOLLOW_DOC "\n" ".. deprecated:: 0.4\n" " this function has been deprecated by the :func:`remove` function.\n" ; /* Wrapper for removexattr */ static PyObject * pyremovexattr(PyObject *self, PyObject *args) { PyObject *myarg, *res; int nofollow = 0; char *attrname = NULL; int nret; target_t tgt; /* Parse the arguments */ if (!PyArg_ParseTuple(args, "Oet|i", &myarg, NULL, &attrname, &nofollow)) return NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) { res = NULL; goto free_arg; } /* Remove the attribute */ nret = _remove_obj(&tgt, attrname); free_tgt(&tgt); if(nret == -1) { res = PyErr_SetFromErrno(PyExc_IOError); goto free_arg; } Py_INCREF(Py_None); res = Py_None; free_arg: PyMem_Free(attrname); /* Return the result */ return res; } static char __remove_doc__[] = "remove(item, name[, nofollow=False, namespace=None])\n" "Remove an attribute from a file.\n" "\n" "Example:\n" "\n" " >>> xattr.remove('/path/to/file', 'user.comment')\n" "\n" ITEM_DOC NAME_REMOVE_DOC NOFOLLOW_DOC NS_DOC ":returns: None\n" ":raises EnvironmentError: caused by any system errors\n" "\n" ".. versionadded:: 0.4\n" NS_CHANGED_DOC ; /* Wrapper for removexattr */ static PyObject * xattr_remove(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *myarg, *res; int nofollow = 0; char *attrname = NULL, *name_buf; const char *ns = NULL; const char *full_name; int nret; target_t tgt; static char *kwlist[] = {"item", "name", "nofollow", "namespace", NULL}; /* Parse the arguments */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oet|iy", kwlist, &myarg, NULL, &attrname, &nofollow, &ns)) return NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) { res = NULL; goto free_arg; } if(merge_ns(ns, attrname, &full_name, &name_buf) < 0) { res = NULL; goto free_arg; } /* Remove the attribute */ nret = _remove_obj(&tgt, full_name); PyMem_Free(name_buf); free_tgt(&tgt); if(nret == -1) { res = PyErr_SetFromErrno(PyExc_IOError); goto free_arg; } Py_INCREF(Py_None); res = Py_None; free_arg: PyMem_Free(attrname); /* Return the result */ return res; } static char __pylistxattr_doc__[] = "listxattr(item[, nofollow=False])\n" "Return the list of attribute names for a file (deprecated).\n" "\n" ITEM_DOC NOFOLLOW_DOC "\n" ".. deprecated:: 0.4\n" " this function has been deprecated by the :func:`list` function.\n" ; /* Wrapper for listxattr */ static PyObject * pylistxattr(PyObject *self, PyObject *args) { char *buf = NULL; int nofollow = 0; ssize_t nret; size_t nalloc = 0; PyObject *myarg; PyObject *mylist; Py_ssize_t nattrs; char *s; target_t tgt; /* Parse the arguments */ if (!PyArg_ParseTuple(args, "O|i", &myarg, &nofollow)) return NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) return NULL; nret = _generic_get(_list_obj, &tgt, NULL, &buf, &nalloc, NULL); if (nret == -1) { mylist = NULL; goto free_buf; } /* Compute the number of attributes in the list */ for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) { nattrs++; } /* Create the list which will hold the result */ mylist = PyList_New(nattrs); if(mylist == NULL) { goto free_buf; } /* Create and insert the attributes as strings in the list */ for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) { PyObject *item = PyBytes_FromString(s); if(item == NULL) { Py_DECREF(mylist); mylist = NULL; goto free_buf; } PyList_SET_ITEM(mylist, nattrs, item); nattrs++; } free_buf: /* Free the buffer, now it is no longer needed */ PyMem_Free(buf); free_tgt(&tgt); /* Return the result */ return mylist; } static char __list_doc__[] = "list(item[, nofollow=False, namespace=None])\n" "Return the list of attribute names for a file.\n" "\n" "Example:\n" "\n" " >>> xattr.list('/path/to/file')\n" " ['user.test', 'user.comment', 'system.posix_acl_access']\n" " >>> xattr.list('/path/to/file', namespace=xattr.NS_USER)\n" " ['test', 'comment']\n" "\n" ITEM_DOC NOFOLLOW_DOC NS_DOC ":returns: the list of attributes; note that if a namespace \n" " argument was passed, it (and the separator) will be stripped\n" " from the names\n" " returned\n" ":rtype: list\n" ":raises EnvironmentError: caused by any system errors\n" "\n" ".. versionadded:: 0.4\n" NS_CHANGED_DOC ; /* Wrapper for listxattr */ static PyObject * xattr_list(PyObject *self, PyObject *args, PyObject *keywds) { char *buf = NULL; int nofollow = 0; ssize_t nret; size_t nalloc = 0; PyObject *myarg; PyObject *res; const char *ns = NULL; Py_ssize_t nattrs; char *s; target_t tgt; static char *kwlist[] = {"item", "nofollow", "namespace", NULL}; /* Parse the arguments */ if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|iy", kwlist, &myarg, &nofollow, &ns)) return NULL; res = NULL; if(convert_obj(myarg, &tgt, nofollow) < 0) { goto free_arg; } nret = _generic_get(_list_obj, &tgt, NULL, &buf, &nalloc, NULL); if (nret == -1) { goto free_tgt; } /* Compute the number of attributes in the list */ for(s = buf, nattrs = 0; (s - buf) < nret; s += strlen(s) + 1) { if(matches_ns(ns, s) != NULL) nattrs++; } /* Create the list which will hold the result */ if((res = PyList_New(nattrs)) == NULL) { goto free_buf; } /* Create and insert the attributes as strings in the list */ for(s = buf, nattrs = 0; s - buf < nret; s += strlen(s) + 1) { const char *name = matches_ns(ns, s); if(name != NULL) { PyObject *item = PyBytes_FromString(name); if(item == NULL) { Py_DECREF(res); res = NULL; goto free_buf; } PyList_SET_ITEM(res, nattrs, item); nattrs++; } } free_buf: /* Free the buffer, now it is no longer needed */ PyMem_Free(buf); free_tgt: free_tgt(&tgt); free_arg: /* Return the result */ return res; } static PyMethodDef xattr_methods[] = { {"getxattr", pygetxattr, METH_VARARGS, __pygetxattr_doc__ }, {"get", (PyCFunction) xattr_get, METH_VARARGS | METH_KEYWORDS, __get_doc__ }, {"get_all", (PyCFunction) get_all, METH_VARARGS | METH_KEYWORDS, __get_all_doc__ }, {"setxattr", pysetxattr, METH_VARARGS, __pysetxattr_doc__ }, {"set", (PyCFunction) xattr_set, METH_VARARGS | METH_KEYWORDS, __set_doc__ }, {"removexattr", pyremovexattr, METH_VARARGS, __pyremovexattr_doc__ }, {"remove", (PyCFunction) xattr_remove, METH_VARARGS | METH_KEYWORDS, __remove_doc__ }, {"listxattr", pylistxattr, METH_VARARGS, __pylistxattr_doc__ }, {"list", (PyCFunction) xattr_list, METH_VARARGS | METH_KEYWORDS, __list_doc__ }, {NULL, NULL, 0, NULL} /* Sentinel */ }; static char __xattr_doc__[] = \ "This module gives access to the extended attributes present\n" "in some operating systems/filesystems. You can list attributes,\n" "get, set and remove them.\n" "\n" "The module exposes two sets of functions:\n" " - the 'old' :func:`listxattr`, :func:`getxattr`, :func:`setxattr`,\n" " :func:`removexattr`\n" " functions which are deprecated since version 0.4\n" " - the new :func:`list`, :func:`get`, :func:`get_all`, :func:`set`,\n" " :func:`remove` functions\n" " which expose a namespace-aware API and simplify a bit the calling\n" " model by using keyword arguments\n" "\n" "Example: \n\n" " >>> import xattr\n" " >>> xattr.listxattr(\"file.txt\")\n" " ['user.mime_type']\n" " >>> xattr.getxattr(\"file.txt\", \"user.mime_type\")\n" " 'text/plain'\n" " >>> xattr.setxattr(\"file.txt\", \"user.comment\", " "\"Simple text file\")\n" " >>> xattr.listxattr(\"file.txt\")\n" " ['user.mime_type', 'user.comment']\n" " >>> xattr.removexattr (\"file.txt\", \"user.comment\")\n" "\n" ".. note:: Most or all errors reported by the system while using\n" " the ``xattr`` library will be reported by raising\n" " a :exc:`EnvironmentError`; under\n" " Linux, the following ``errno`` values are used:\n" "\n" " - ``ENODATA`` means that the attribute name is invalid\n" " - ``ENOTSUP`` and ``EOPNOTSUPP`` mean that the filesystem does not\n" " support extended attributes, or that the namespace is invalid\n" " - ``E2BIG`` mean that the attribute value is too big\n" " - ``ERANGE`` mean that the attribute name is too big (it might also\n" " mean an error in the xattr module itself)\n" " - ``ENOSPC`` and ``EDQUOT`` are documented as meaning out of disk\n" " space or out of disk space because of quota limits\n" ".. note:: Under Python 3, the namespace argument is a byte string,\n" " not a unicode string.\n" "\n" ; static struct PyModuleDef xattrmodule = { PyModuleDef_HEAD_INIT, "xattr", __xattr_doc__, 0, xattr_methods, }; #define INITERROR return NULL PyMODINIT_FUNC PyInit_xattr(void) { PyObject *ns_security = NULL; PyObject *ns_system = NULL; PyObject *ns_trusted = NULL; PyObject *ns_user = NULL; PyObject *m = PyModule_Create(&xattrmodule); if (m==NULL) return NULL; PyModule_AddStringConstant(m, "__author__", _XATTR_AUTHOR); PyModule_AddStringConstant(m, "__contact__", _XATTR_EMAIL); PyModule_AddStringConstant(m, "__version__", _XATTR_VERSION); PyModule_AddStringConstant(m, "__license__", "GNU Lesser General Public License (LGPL)"); PyModule_AddStringConstant(m, "__docformat__", "restructuredtext en"); PyModule_AddIntConstant(m, "XATTR_CREATE", XATTR_CREATE); PyModule_AddIntConstant(m, "XATTR_REPLACE", XATTR_REPLACE); /* namespace constants */ if((ns_security = PyBytes_FromString("security")) == NULL) goto err_out; if((ns_system = PyBytes_FromString("system")) == NULL) goto err_out; if((ns_trusted = PyBytes_FromString("trusted")) == NULL) goto err_out; if((ns_user = PyBytes_FromString("user")) == NULL) goto err_out; /* Add the new objects to the module */ /* TODO: after switching to min 3.10, use the *Ref version, and simplify the error handling. */ if(PyModule_AddObject(m, "NS_SECURITY", ns_security) < 0) goto err_out; ns_security = NULL; if(PyModule_AddObject(m, "NS_SYSTEM", ns_system) < 0) goto err_out; ns_system = NULL; if(PyModule_AddObject(m, "NS_TRUSTED", ns_trusted) < 0) goto err_out; ns_trusted = NULL; if(PyModule_AddObject(m, "NS_USER", ns_user) < 0) goto err_out; ns_user = NULL; return m; err_out: Py_XDECREF(ns_user); Py_XDECREF(ns_trusted); Py_XDECREF(ns_system); Py_XDECREF(ns_security); Py_DECREF(m); INITERROR; }