pax_global_header00006660000000000000000000000064146101355520014514gustar00rootroot0000000000000052 comment=b323570087a10bf4ac399007d9e01e824fdafd80 pycups-2.0.4/000077500000000000000000000000001461013555200130425ustar00rootroot00000000000000pycups-2.0.4/.github/000077500000000000000000000000001461013555200144025ustar00rootroot00000000000000pycups-2.0.4/.github/workflows/000077500000000000000000000000001461013555200164375ustar00rootroot00000000000000pycups-2.0.4/.github/workflows/github-actions.yml000066400000000000000000000020651461013555200221050ustar00rootroot00000000000000name: C/C++ CI on: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: update build env run: sudo apt-get update --fix-missing -y - name: install prerequisities run: sudo apt-get install libcups2-dev python3-dev gcc python3-setuptools - name: make run: make - name: sudo make install run: sudo make install - name: make dist run: make dist - name: install cups and ippeveprinter for testing run: sudo apt-get install cups cups-ipp-utils - name: start cupsd - needed for testing run: sudo systemctl start cups - name: start ippeveprinter to simulate a driverless printer run: mkdir -p /tmp/ippeve/spool/ && ippeveprinter -vvvv -s 10,0 -d "/tmp/ippeve/spool/" -k "test-ippeve" & - name: install a permanent queue run: sudo lpadmin -p test-permanent -v ipp://localhost:8000/ipp/print -m everywhere -E && sleep 5 - name: python3 test.py run: python3 test.py pycups-2.0.4/.gitignore000066400000000000000000000000531461013555200150300ustar00rootroot00000000000000*.pyc *~ __pycache__/ build/ cups.so html/ pycups-2.0.4/COPYING000066400000000000000000000432541461013555200141050ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, 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. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. 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 Program or any portion of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, 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 Program, 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 Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) 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; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, 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 executable. However, as a special exception, the source code 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. If distribution of executable or 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 counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program 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. 5. 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 Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program 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 to this License. 7. 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 Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program 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 Program. 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. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program 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. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies 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 Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, 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 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. 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 PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively 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 program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. pycups-2.0.4/MANIFEST.in000066400000000000000000000004001461013555200145720ustar00rootroot00000000000000include COPYING README NEWS TODO include Makefile include cupsconnection.[ch] include cupsipp.[ch] include cupsmodule.[ch] include cupsppd.[ch] include setup.py include test.py examples/cupstree.py # RPM bits include postscriptdriver.prov psdriver.attr pycups-2.0.4/Makefile000066400000000000000000000023061461013555200145030ustar00rootroot00000000000000PYTHON=python3 NAME=pycups VERSION:=$(shell $(PYTHON) setup.py --version) SDIST_ARGS=--formats=gztar -d. RPMCONFIGDIR:=$(shell rpm -E "%{_rpmconfigdir}" 2>/dev/null || :) SOURCES=cupsmodule.c cupsconnection.c cupsppd.c cupsipp.c setup.py \ cupsppd.h cupsipp.h cupsconnection.h cupsmodule.h \ psdriver.attr postscriptdriver.prov DIST=Makefile test.py \ examples \ COPYING NEWS README TODO cups.so: force $(PYTHON) setup.py build ln -sf build/lib*/$@ . doc: cups.so rm -rf html $(PYTHON) -m pydoc -w cups mkdir html mv cups.html html doczip: doc cd html && zip ../cups-html.zip * clean: -rm -rf build cups.so html *.pyc *~ __pycache__ dist: $(PYTHON) setup.py sdist $(SDIST_ARGS) upload: $(PYTHON) setup.py sdist $(SDIST_ARGS) upload -s install: install-rpmhook ROOT= ; \ if [ -n "$$DESTDIR" ]; then ROOT="--root $$DESTDIR"; fi; \ $(PYTHON) setup.py install --skip-build $$ROOT install-rpmhook: if [ -n "$(RPMCONFIGDIR)" ]; then \ RPMCONFIG="$$DESTDIR$(RPMCONFIGDIR)" ; \ mkdir -p "$$RPMCONFIG"/fileattrs ; \ install -m0644 psdriver.attr "$$RPMCONFIG"/fileattrs/ ; \ install -m0755 postscriptdriver.prov "$$RPMCONFIG"/ ; \ fi .PHONY: doc doczip clean dist install install-rpmhook force pycups-2.0.4/NEWS000066400000000000000000000267101461013555200135470ustar00rootroot00000000000000NEWS ---- New in 2.0.4: - remove the install_requires from setup.py New in 2.0.2a0, 2.0.3: - attempts to fix installation in PyPi New in 2.0.2: - removed shebang from example/cupstree.py - ignore driverless utilities for postscriptdriver tags creation (Fedora bug #1873385) - remove epydoc from Makefile (#27) - fix invalid delete of pointer (#11) - Makefile uses wrong Python (#32) - define PY_SSIZE_T_CLEAN in cupsipp.h - fixes traceback during IPPRequest.writeIO with Python 3.10 - fix the test.py when there is no printer installed (#46) - Use PyObject_Call() instead of deprecated PyEval New in 2.0.1: * pypi required .tar.gz * cups.require couldn't handle version bigger than 1 New in 2.0.0: * dropped macros for older CUPS < 2.0.0 * dropped Python 2 support and its related macros * update license headers * thread did not hold GIL when called Py_XDECREF() from destroy_TLS(), causing SIGSEGV(Fedora bug #1816107) * fixed several compiler warnings * fix silent error on Connection.printFiles() (patch by Wilbert Berendsen) New in 1.9.74: * fix Connection_writeRequestData with binary data (https://github.com/zdohnal/pycups/pull/1) * misspelling (patch by Edward Betts) * fixed print function in example/cupstree.py (patch by Jiri Popelka) New in 1.9.73: * Fixed build for CUPS 1.6.3 by making several constants conditional on CUPS >= 1.7. New in 1.9.72: * Removed private CANCEL_DOCUMENT, GET_DOCUMENT_ATTRIBUTES, GET_DOCUMENTS, DELETE_DOCUMENT, SET_DOCUMENT_ATTRIBUTES IPP operation constants. * Fixed build for CUPS 1.4 by making several constants conditional on CUPS >= 1.5. New in 1.9.71: * Fixes for cups.IPP_JOB_CANCELED, cups.IPP_ERROR_JOB_CANCELED, cups.IPP_STATUS_ERROR_CUPS_AUTHENTICATION_CANCELED, cups.IPP_AUTHENTICATION_CANCELED, cups.IPP_STATUS_ERROR_CUPS_UPGRADE_REQUIRED, and cups.IPP_UPGRADE_REQUIRED. New in 1.9.70: * cups.ippErrorString(). Fixed build with CUPS 1.5. New-style (CUPS 1.6) naming for HTTP status (cups.HTTP_STATUS_*), IPP orientation (cups.IPP_ORIENT_*), IPP status (cups.IPP_STATUS_*), and IPP I/O (cups.IPP_STATE_*) constants. New in 1.9.69: * cups.IPPRequest.operation, cups.IPPRequest.state, cups.IPPRequest.statuscode, cups.ippOpString(), cups.IPP_OP_*, cups.IPPRequest.addSeparator(), cups.IPPRequest.add(), cups.IPPRequest.writeIO(). New in 1.9.68: * Now builds against CUPS 2.0. * The rpm provider script is now Python3. New in 1.9.67: * Bindings for streaming API: cups.CUPS_FORMAT_* constants, cups.createJob(), cups.startDocument(), cups.writeRequestData(), cups.finishDocument(). New in 1.9.66: * Python 3 support. New in 1.9.65: * cups.connectDest() API fix: now returns a tuple. * cups.enumDests(), cups.connectDest(), and cups.CUPS_DEST_FLAGS_* constants (requires CUPS 1.6). New in 1.9.63: * cups.IPPError tuple now contains the specific error string, if one is available. New in 1.9.62: * Define all constants regardless of which version of CUPS is built against. New in 1.9.60: * New constants from 1.5: - IPP_AUTHENTICATION_CANCELED - IPP_PKI_ERROR - HTTP_NOT_IMPLEMENTED - HTTP_BAD_GATEWAY - HTTP_SERVICE_UNAVAILABLE - HTTP_GATEWAY_TIMEOUT - HTTP_NOT_SUPPORTED - HTTP_AUTHORIZATION_CANCELED - HTTP_PKI_ERROR New in 1.9.59: * Password callbacks can now return None to indicate they want to abort the current operation. New in 1.9.58: * cups.Connection.adminExportSamba New in 1.9.57: * Fixed rpm provides script for newer versions of rpm. New in 1.9.56: * Builds against older versions of CUPS again. New in 1.9.55: * cups.IPP_QUALITY_DRAFT, cups.IPP_QUALITY_NORMAL, cups.IPP_QUALITY_HIGH * cups.IPP_PORTRAIT, cups.IPP_LANDSCAPE, cups.IPP_REVERSE_PORTRAIT, cups.IPP_REVERSE_LANDSCAPE * cups.IPP_RES_UNITS_CM, cups.IPP_RES_UNITS_INCH * Support for IPP_TAG_RESOLUTION as triplet (xres, yres, units). New in 1.9.52: * cups.Connection.getPPDs2(): New method, identical to getPPDs() but returning all attribute values as lists. New in 1.9.50: * cups.Connection.getPPD3() * cups.Connection.getJobs() now takes optional requested_attributes argument. * cups.Connection.getPrinterAttributes(): member-names is now always a list. * cups.HTTP_NOT_MODIFIED constant. * cups.PPD_ORDER_ANY constant. * cups.PPD_ORDER_DOCUMENT constant. * cups.PPD_ORDER_EXIT constant. * cups.PPD_ORDER_JCL constant. * cups.PPD_ORDER_PAGE constant. * cups.PPD_ORDER_PROLOG constant. * cups.PPD.emitString() method. * cups.PPD.emit() method. * cups.PPD.emitAfterOrder() method. * cups.PPD.emitFd() method. * cups.PPD.emitJCL() method. * cups.PPD.emitJCLEnd() method. New in 1.9.48: * cups.Connection.cancelJob()'s optional second argument is now a keyword. New in 1.9.47: * cups.Connection.restartJob() now takes optional job_hold_until argument. * cups.Connection.cancelJob() now takes optional purge_job argument. * cups.setPasswordCB2() method. * cups.Connection.moveJob() method. * cups.IPPAttribute and cups.IPPRequest types. * IPP state constants. * cups.Connection.getDevices() now takes optional timeout argument. New in 1.9.46: * cups.Connection.getDevices() now takes optional limit, exclude_schemes and include_schemes arguments. * cups.Connection.getPPDs() now takes optional limit, exclude_schemes, include_schemes, ppd_device_id, ppd_make, ppd_make_and_model, ppd_model_number, ppd_product, ppd_psversion, ppd_type and ppd_natural_language arguments. * cups.ppdSetConformance() method. * cups.PPD_CONFORM_RELAXED constant. * cups.PPD_CONFORM_STRICT constant. * cups.modelSort() now accepts Unicode strings. New in 1.9.45: * cups.PPD.localizeIPPReason() * cups.PPD.localizeMarkerName() New in 1.9.42: * cups.Connection.getJobAttributes() now takes optional requested_attributes argument. * cups.Connection.getJobs() now takes optional limit and first_job_id arguments. New in 1.9.41: * cups.Connection.putFile() now accepts a file descriptor or a Python file object as the destination. New in 1.9.40: * cups.Connection() now takes optional arguments host, port, and encryption. * cups.Connection.getPrinterAttributes() now takes an optional requested_attributes argument New in 1.9.39: * cups.Connection.authenticateJob() auth parameter is now optional * cups.Connection.printFile() * cups.Connection.printFiles() New in 1.9.38: * cups.Connection.getFile() now accepts a file descriptor or a Python file object as the destination. New in 1.9.37: * cups.Connection.authenticateJob() * cups.CUPS_PRINTER_DISCOVERED New in 1.9.36: * cups.Connection.renewSubscription() now takes an optional parameter lease_duration. * cups.Connection.getJobAttributes() and cups.Connection.getNotifications(): State reasons are now lists as they ought to be. New in 1.9.35: * cups.Connection.getJobAttributes() * cups.Connection.cancelAllJobs() New in 1.9.32: * cups.Connection.getPrinterAttributes() now takes a uri keyword argument for fetching attributes from non-CUPS IPP servers. New in 1.9.31: * cups.Connection.getDocument() * cups.Connection.getDefault() New in 1.9.29: * IPP attribute strings are now represented as Unicode objects. New in 1.9.28: * cups.Connection.getDests() now includes a (None,None) key in its result for identifying the default printer. This is intended to be equivalent to cupsGetDest(NULL, NULL, ...). New in 1.9.27: * IPP attributes with type IPP_TAG_NOVALUE now take Python value None. New in 1.9.25: * cups.CUPS_SERVER_REMOTE_ANY (for CUPS 1.3) * cups.Connection.getServerPPD() New in 1.9.23: * cups.require() New in 1.9.22: * cups.Connection.getPPDs() and cups.Connection.getDevices() now allow threads during the IO request * cups.Connection.printTestPage() now optionally takes more parameters than just the printer name New in 1.9.21: * cups.Connection.getSubscriptions() * cups.Connection.createSubscription() * cups.Connection.getNotifications() * cups.Connection.renewSubscription() * cups.Connection.cancelSubscription() * cups.CUPS_PRINTER_COMMANDS New in 1.9.20: * cups.Connection.getPrinters() 'printer-state-reasons' attribute is now a list (as it ought to have been originally). New in 1.9.19: * cups.IPP_JOB_* job states New in 1.9.18: * cups.Connection.getJobs() now includes job-state, job-preserved, time-at-creation, time-at-processing, time-at-completed, job-media-sheets, and job-media-sheets-completed attributes. * cups.Connection.getJobs() has new optional parameters which_jobs and my_jobs. * cups.Connection.setJobHoldUntil() * cups.Connection.restartJob() New in 1.9.17: * cups.PPD.localize() New in 1.9.16: * cups.Connection.getPrinters() now includes printer-state-message and printer-state-reasons attributes * cups.Connection.disablePrinter() and cups.Connection.rejectJobs() now take an optional 'reason' keyword argument and use it to set printer-state-message * cups.Connection.getJobs() now includes job-priority attribute New in 1.9.15: * cups.Connection.getJobs() * cups.Connection.cancelJob() New in 1.9.13: * cups.HTTP_FORBIDDEN New since 1.9.10: * cups.HTTP_* status codes New since 1.9.9: * cups.Connection getClasses() handles IPP_NOT_FOUND * PYCUPS_DEBUG environment variable controls debugging output New since 1.9.8: * cups.Connection.addPrinterOptionDefault() now supports lists and tuples * cups.Connection.getPrinterAttributes() now handles multi-valued default options as lists * cups.IPP_FINISHINGS_* constants * cups.Connection getPrinters() handles IPP_NOT_FOUND New since 1.9.7: * cups.Connection.adminGetServerSettings() * cups.Connection.adminSetServerSettings() * cups.CUPS_SERVER_* string constants New since 1.9.6: * threading support * cups.Dest type * cups.Connection.addPrinterOptionDefault() * cups.Connection.deletePrinterOptionDefault() * cups.Connection.getDests() New since 1.9.5: * cups.Attribute object * cups.PPD.attributes * cups.PPD.findAttr() * cups.PPD.findNextAttr() New since 1.9.4: * cups.Connection.setPrinterShared() now handles classes * cups.Connection.printTestPage() * cups.Connection.getPPDs() includes ppd-make attribute * cups.IPP_MAX_NAME New since 1.9.3: * cups.Connection.enablePrinter() uses IPP_PAUSE_PRINTER * cups.Connection.disablePrinter() uses IPP_RESUME_PRINTER * cups.Connection.deleteClass() * cups.Connection.setPrinterLocation() and cups.Connection.setPrinterInfo() now handle classes New since 1.9.2: * cups.PPD.* now convert from the PPD character set encoding * cups.Connection.setPrinterPublished() is now renamed to cups.Connection.setPrinterShared() * cups.Connection.setPrinterUsersAllowed() * cups.Connection.setPrinterUsersDenied() New since 1.9.1: * fixed cups.Connection.setPrinterInfo() * fixed cups.Connection.setPrinterLocation() * cups.Connection.getPrinterAttributes() * cups.Connection.setPrinterJobSheets() * cups.Connection.setPrinterErrorPolicy() * cups.Connection.setPrinterOpPolicy() * cups.PPD.nondefaultsMarked() * cups.IPP_* error constants New since 1.9.0: * cups.Constraint type * cups.IPPError now includes the cupsLastErrorString() * cups.IPP_PRINTER_* constants * cups.setPort() * cups.getUser() * cups.getServer() * cups.getPort() * cups.getEncryption() * cups.PPD.constraints attribute * cups.PPD.getOptionGroups() method changed to optionGroups attribute * cups.PPD.Group.options is a list, not a dict * cups.PPD.findOption() * cups.PPD.writeFd() * cups.Connection.addPrinter now allows ppdname="foo.ppd" keyword for installed PPDs; also info, location, device and ppd keywords * cups.Connection.getPPDs() * cups.Connection.getDevices() * cups.Connection.getClasses() * cups.Connection.setPrinterInfo() * cups.Connection.setPrinterLocation() * cups.Connection.setPrinterPublished() pycups-2.0.4/README000066400000000000000000000022451461013555200137250ustar00rootroot00000000000000CUPS bindings for Python ------------------------ These Python bindings are intended to wrap the CUPS API. Python 3 or later is required since Python 2 is unsupported since 2020-01-01. CUPS >= 1.7 is required for the latest pycups version. Build dependencies ------------------ The following packages are needed for compiling PyCUPS. GCC compiler is needed because modules are written in C. CUPS development files are needed for providing CUPS API, which are used in modules and Python3 development files for Python3 functions called in modules. Packages needed for compilation (default package names are from Fedora, Ubuntu names are in the brackets if they differ from Fedora): - gcc - cups-devel (libcups2-dev) - python3-devel (python3-dev) - (since Python 3.12) python3-setuptools Please install them before compiling PyCUPS. Runtime dependencies -------------------- CUPS needs to be installed and running for PyCUPS working correctly. How to compile and install -------------------------- Do the following steps in the PyCUPS directory: $ make $ sudo make install How to import cups module in python3 script ------------------------------------------- >>> import cups pycups-2.0.4/TODO000066400000000000000000000003261461013555200135330ustar00rootroot00000000000000* Add cups.Connection.getNamedDest() wrapper * uploading to pypi does not work by 'make upload' - needed to do after archiving by 'make upload': $ python3 -m twine upload --repository pypi pycups-.tar.gz pycups-2.0.4/cupsconnection.c000066400000000000000000005205031461013555200162450ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Red Hat, Inc * Authors: Tim Waugh * Zdenek Dohnal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "cupsconnection.h" #include "cupsppd.h" #include "cupsmodule.h" #ifndef __SVR4 #include #endif #include #include #include #include #ifndef _PATH_TMP #define _PATH_TMP P_tmpdir #endif #define DICT_POS_TYPE Py_ssize_t PyObject *HTTPError; PyObject *IPPError; static Connection **Connections = NULL; static long unsigned int NumConnections = 0; static void set_http_error (http_status_t status) { PyObject *v = Py_BuildValue ("i", status); debugprintf("set_http_error: %d\n", (int) status); if (v != NULL) { PyErr_SetObject (HTTPError, v); Py_DECREF (v); } } void set_ipp_error (ipp_status_t status, const char *message) { if (!message) message = ippErrorString (status); debugprintf("set_ipp_error: %d, %s\n", (int) status, message); PyObject *v = Py_BuildValue ("(is)", status, message); if (v != NULL) { PyErr_SetObject (IPPError, v); Py_DECREF (v); } } static PyObject * PyObj_from_UTF8 (const char *utf8) { PyObject *val = PyUnicode_Decode (utf8, strlen (utf8), "utf-8", NULL); if (!val) { // CUPS 1.2 always gives us UTF-8. Before CUPS 1.2, the // ppd-* strings come straight from the PPD with no // transcoding, but the attributes-charset is still 'utf-8' // so we've no way of knowing the real encoding. // In that case, detect the error and force it to ASCII. const char *orig = utf8; char *ascii; int i; PyErr_Clear (); ascii = malloc (1 + strlen (orig)); for (i = 0; orig[i]; i++) ascii[i] = orig[i] & 0x7f; ascii[i] = '\0'; val = PyUnicode_FromString (ascii); free (ascii); } return val; } const char * UTF8_from_PyObj (char **const utf8, PyObject *obj) // converts PyUnicode or PyBytes to char * { if (PyUnicode_Check (obj)) { const char *string; PyObject *stringobj = PyUnicode_AsUTF8String (obj); if (stringobj == NULL) return NULL; string = PyBytes_AsString (stringobj); if (string == NULL) { Py_DECREF (stringobj); return NULL; } *utf8 = strdup (string); Py_DECREF (stringobj); return *utf8; } else if (PyBytes_Check (obj)) { const char *ret; PyObject *unicodeobj = PyUnicode_FromEncodedObject (obj, "utf-8", NULL); if (unicodeobj == NULL) return NULL; ret = UTF8_from_PyObj (utf8, unicodeobj); Py_DECREF (unicodeobj); return ret; } PyErr_SetString (PyExc_TypeError, "unicode or bytes object required"); return NULL; } static void construct_uri (char *buffer, size_t buflen, const char *base, const char *value) { char *d = buffer; const unsigned char *s = (const unsigned char *) value; if (strlen (base) < buflen) { strcpy (buffer, base); d += strlen (base); } else { strncpy (buffer, base, buflen); d += buflen; } while (*s && d < buffer + buflen) { if (isalpha (*s) || isdigit (*s) || *s == '-') *d++ = *s++; else if (*s == ' ') { *d++ = '+'; s++; } else { if (d + 2 < buffer + buflen) { *d++ = '%'; *d++ = "0123456789ABCDEF"[((*s) & 0xf0) >> 4]; *d++ = "0123456789ABCDEF"[((*s) & 0x0f)]; s++; } else break; } } if (d < buffer + buflen) *d = '\0'; } //////////////// // Connection // //////////////// static PyObject * Connection_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Connection *self; self = (Connection *) type->tp_alloc (type, 0); if (self != NULL) { self->http = NULL; self->host = NULL; self->tstate = NULL; self->cb_password = NULL; } return (PyObject *) self; } static int Connection_init (Connection *self, PyObject *args, PyObject *kwds) { const char *host = cupsServer (); int port = ippPort (); int encryption = (http_encryption_t) cupsEncryption (); static char *kwlist[] = { "host", "port", "encryption", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|sii", kwlist, &host, &port, &encryption)) return -1; debugprintf ("-> Connection_init(host=%s)\n", host); self->host = strdup (host); if (!self->host) { debugprintf ("<- Connection_init() = -1\n"); return -1; } Connection_begin_allow_threads (self); debugprintf ("httpConnect2(...)\n"); self->http = httpConnect2(host, port, NULL, AF_UNSPEC, cupsEncryption(), 1, 30000, NULL); Connection_end_allow_threads (self); if (!self->http) { PyErr_SetString (PyExc_RuntimeError, "failed to connect to server"); debugprintf ("<- Connection_init() = -1\n"); return -1; } if (NumConnections == 0) { Connections = malloc (sizeof (Connection *)); if (Connections == NULL) { PyErr_SetString (PyExc_RuntimeError, "insufficient memory"); debugprintf ("<- Connection_init() = -1\n"); return -1; } } else { Connection **old_array = Connections; if ((1 + NumConnections) >= UINT_MAX / sizeof (Connection *)) { PyErr_SetString (PyExc_RuntimeError, "too many connections"); debugprintf ("<- Connection_init() == -1\n"); return -1; } Connections = realloc (Connections, (1 + NumConnections) * sizeof (Connection *)); if (Connections == NULL) { Connections = old_array; PyErr_SetString (PyExc_RuntimeError, "insufficient memory"); debugprintf ("<- Connection_init() = -1\n"); return -1; } } Connections[NumConnections++] = self; debugprintf ("<- Connection_init() = 0\n"); return 0; } static void Connection_dealloc (Connection *self) { long unsigned int i, j; for (j = 0; j < NumConnections; j++) if (Connections[j] == self) break; if (j < NumConnections) { if (NumConnections > 1) { Connection **new_array = calloc (NumConnections - 1, sizeof (Connection *)); if (new_array) { int k; for (i = 0, k = 0; i < NumConnections; i++) { if (i == j) continue; new_array[k++] = Connections[i]; } free (Connections); Connections = new_array; NumConnections--; } else /* Failed to allocate memory. Just clear out the reference. */ Connections[j] = NULL; } else { /* The only element is the one we no longer need. */ free (Connections); Connections = NULL; NumConnections = 0; } } if (self->http) { debugprintf ("httpClose()\n"); httpClose (self->http); free (self->host); free (self->cb_password); } ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static PyObject * Connection_repr (Connection *self) { char buffer[256]; snprintf (buffer, 256, "", self->host, self); return PyUnicode_FromString (buffer); } void Connection_begin_allow_threads (void *connection) { Connection *self = (Connection *) connection; debugprintf ("begin allow threads\n"); self->tstate = PyEval_SaveThread (); } void Connection_end_allow_threads (void *connection) { Connection *self = (Connection *) connection; debugprintf ("end allow threads\n"); PyEval_RestoreThread (self->tstate); self->tstate = NULL; } //////////////// // Connection // METHODS //////////////// static const char * password_callback (int newstyle, const char *prompt, http_t *http, const char *method, const char *resource, void *user_data) { struct TLS *tls = get_TLS (); PyObject *cb_context = user_data; Connection *self = NULL; PyObject *args; PyObject *result; long unsigned int i; debugprintf ("-> password_callback for http=%p, newstyle=%d\n", http, newstyle); for (i = 0; i < NumConnections; i++) if (Connections[i]->http == http) { self = Connections[i]; break; } if (!self) { debugprintf ("cannot find self!\n"); return ""; } Connection_end_allow_threads (self); if (newstyle) { /* New-style callback. */ if (cb_context) args = Py_BuildValue ("(sOssO)", prompt, self, method, resource, cb_context); else args = Py_BuildValue ("(sOss)", prompt, self, method, resource); } else args = Py_BuildValue ("(s)", prompt); if (!args) { debugprintf ("Py_BuildValue failed!"); Connection_begin_allow_threads (self); return NULL; } result = PyObject_Call (tls->cups_password_callback, args, NULL); Py_DECREF (args); if (result == NULL) { debugprintf ("<- password_callback (exception)\n"); Connection_begin_allow_threads (self); return NULL; } free (self->cb_password); if (result == Py_None || !UTF8_from_PyObj (&self->cb_password, result)) self->cb_password = NULL; Py_DECREF (result); if (!self->cb_password || !*self->cb_password) { debugprintf ("<- password_callback (empty/null)\n"); Connection_begin_allow_threads (self); return NULL; } Connection_begin_allow_threads (self); debugprintf ("<- password_callback\n"); return self->cb_password; } const char * password_callback_oldstyle (const char *prompt, http_t *http, const char *method, const char *resource, void *user_data) { return password_callback (0, prompt, http, method, resource, user_data); } const char * password_callback_newstyle (const char *prompt, http_t *http, const char *method, const char *resource, void *user_data) { return password_callback (1, prompt, http, method, resource, user_data); } static PyObject * do_printer_request (Connection *self, PyObject *args, PyObject *kwds, ipp_op_t op) { PyObject *nameobj; PyObject *reasonobj = NULL; char *name; char uri[HTTP_MAX_URI]; ipp_t *request, *answer; switch (op) { case IPP_PAUSE_PRINTER: case CUPS_REJECT_JOBS: { static char *kwlist[] = { "name", "reason", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|O", kwlist, &nameobj, &reasonobj)) return NULL; break; } default: if (!PyArg_ParseTuple (args, "O", &nameobj)) return NULL; break; } if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; debugprintf ("-> do_printer_request(op:%d, name:%s)\n", (int) op, name); request = ippNewRequest (op); construct_uri (uri, sizeof (uri), "ipp://localhost/printers/", name); free (name); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); if (reasonobj) { char *reason; if (UTF8_from_PyObj (&reason, reasonobj) == NULL) { ippDelete (request); return NULL; } debugprintf ("reason: %s\n", reason); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "printer-state-message", NULL, reason); free (reason); } debugprintf ("cupsDoRequest(\"/admin/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); debugprintf("<- do_printer_request (error)\n"); return NULL; } if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf("<- do_printer_request (error)\n"); return NULL; } ippDelete (answer); debugprintf("<- do_printer_request (None)\n"); Py_RETURN_NONE; } static int copy_dest (Dest *dst, cups_dest_t *src) { int i; dst->is_default = src->is_default; dst->destname = strdup (src->name); dst->instance = (src->instance ? strdup (src->instance) : NULL ); dst->num_options = src->num_options; dst->name = malloc (src->num_options * sizeof (char *)); dst->value = malloc (src->num_options * sizeof (char *)); for (i = 0; i < src->num_options; i++) { dst->name[i] = strdup (src->options[i].name); dst->value[i] = strdup (src->options[i].value); } return 0; } static PyObject * Connection_getDests (Connection *self) { cups_dest_t *dests; int num_dests; PyObject *pydests = PyDict_New (); int i; debugprintf ("-> Connection_getDests()\n"); debugprintf ("cupsGetDests2()\n"); Connection_begin_allow_threads (self); num_dests = cupsGetDests2 (self->http, &dests); Connection_end_allow_threads (self); // Create a dict indexed by (name,instance) for (i = 0; i <= num_dests; i++) { PyObject *largs = Py_BuildValue ("()"); PyObject *lkwlist = Py_BuildValue ("{}"); Dest *destobj = (Dest *) PyType_GenericNew (&cups_DestType, largs, lkwlist); Py_DECREF (largs); Py_DECREF (lkwlist); cups_dest_t *dest; PyObject *nameinstance; if (i == num_dests) { // Add a (None,None) entry for the default printer. dest = cupsGetDest (NULL, NULL, num_dests, dests); if (dest == NULL) { /* No default printer. */ Py_DECREF ((PyObject *) destobj); break; } nameinstance = Py_BuildValue ("(ss)", NULL, NULL); } else { dest = dests + i; nameinstance = Py_BuildValue ("(ss)", dest->name, dest->instance); } copy_dest (destobj, dest); PyDict_SetItem (pydests, nameinstance, (PyObject *) destobj); Py_DECREF ((PyObject *) destobj); } debugprintf ("cupsFreeDests()\n"); cupsFreeDests (num_dests, dests); debugprintf ("<- Connection_getDests()\n"); return pydests; } int cups_dest_cb (void *user_data, unsigned flags, cups_dest_t *dest) { CallbackContext *context = user_data; PyObject *largs = Py_BuildValue ("()"); PyObject *lkwlist = Py_BuildValue ("{}"); Dest *destobj; PyObject *args; PyObject *result; int ret = 0; debugprintf ("-> cups_dest_cb\n"); destobj = (Dest *) PyType_GenericNew (&cups_DestType, largs, lkwlist); Py_DECREF (largs); Py_DECREF (lkwlist); copy_dest (destobj, dest); args = Py_BuildValue ("(OiO)", context->user_data, flags, destobj); Py_DECREF ((PyObject *) destobj); if (!args) { debugprintf ("Py_BuildValue() failed!\n"); return 0; } result = PyObject_Call (context->cb, args, NULL); Py_DECREF (args); if (result == NULL) { debugprintf ("<- cups_dest_cb (exception from cb func)\n"); ret = 0; } if (result && PyLong_Check (result)) { ret = PyLong_AsLong (result); debugprintf (" cups_dest_cb: cb func returned %d\n", ret); } debugprintf ("<- cups_dest_cb (%d)\n", ret); return ret; } static PyObject * PyObject_from_attr_value (ipp_attribute_t *attr, int i) { PyObject *val = NULL; char unknown[100]; int lower, upper; int xres, yres; ipp_res_t units; switch (ippGetValueTag(attr)) { case IPP_TAG_NAME: case IPP_TAG_TEXT: case IPP_TAG_KEYWORD: case IPP_TAG_URI: case IPP_TAG_CHARSET: case IPP_TAG_MIMETYPE: case IPP_TAG_LANGUAGE: val = PyObj_from_UTF8 (ippGetString (attr, i, NULL)); break; case IPP_TAG_INTEGER: case IPP_TAG_ENUM: val = PyLong_FromLong (ippGetInteger (attr, i)); break; case IPP_TAG_BOOLEAN: val = PyBool_FromLong (ippGetBoolean (attr, i)); break; case IPP_TAG_RANGE: lower = ippGetRange (attr, i, &upper); val = Py_BuildValue ("(ii)", lower, upper); break; case IPP_TAG_NOVALUE: Py_RETURN_NONE; break; // TODO: case IPP_TAG_DATE: val = PyUnicode_FromString ("(IPP_TAG_DATE)"); break; case IPP_TAG_RESOLUTION: xres = ippGetResolution(attr, i, &yres, &units); val = Py_BuildValue ("(iii)", xres, yres, units); break; default: snprintf (unknown, sizeof (unknown), "(unknown IPP value tag 0x%x)", ippGetValueTag(attr)); val = PyUnicode_FromString (unknown); break; } return val; } static PyObject * PyList_from_attr_values (ipp_attribute_t *attr) { PyObject *list = PyList_New (0); int i; debugprintf ("-> PyList_from_attr_values()\n"); for (i = 0; i < ippGetCount (attr); i++) { PyObject *val = PyObject_from_attr_value (attr, i); if (val) { PyList_Append (list, val); Py_DECREF (val); } } debugprintf ("<- PyList_from_attr_values()\n"); return list; } static PyObject * Connection_getPrinters (Connection *self) { PyObject *result; ipp_t *request = ippNewRequest(CUPS_GET_PRINTERS), *answer; ipp_attribute_t *attr; const char *attributes[] = { "printer-name", "printer-type", "printer-location", "printer-info", "printer-make-and-model", "printer-state", "printer-state-message", "printer-state-reasons", "printer-uri-supported", "device-uri", "printer-is-shared", }; debugprintf ("-> Connection_getPrinters()\n"); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", sizeof (attributes) / sizeof (attributes[0]), NULL, attributes); debugprintf ("cupsDoRequest(\"/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { if (answer && ippGetStatusCode (answer) == IPP_NOT_FOUND) { // No printers. debugprintf ("<- Connection_getPrinters() = {} (no printers)\n"); ippDelete (answer); return PyDict_New (); } set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getPrinters() (error)\n"); return NULL; } result = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { PyObject *dict; char *printer = NULL; while (attr && ippGetGroupTag (attr) != IPP_TAG_PRINTER) attr = ippNextAttribute (answer); if (!attr) break; dict = PyDict_New (); for (; attr && ippGetGroupTag (attr) == IPP_TAG_PRINTER; attr = ippNextAttribute (answer)) { PyObject *val = NULL; debugprintf ("Attribute: %s\n", ippGetName (attr)); if (!strcmp (ippGetName (attr), "printer-name") && ippGetValueTag (attr) == IPP_TAG_NAME) printer = (char *) ippGetString (attr, 0, NULL); else if ((!strcmp (ippGetName (attr), "printer-type") || !strcmp (ippGetName (attr), "printer-state")) && ippGetValueTag (attr) == IPP_TAG_ENUM) { int ptype = ippGetInteger (attr, 0); val = PyLong_FromLong (ptype); } else if ((!strcmp (ippGetName (attr), "printer-make-and-model") || !strcmp (ippGetName (attr), "printer-info") || !strcmp (ippGetName (attr), "printer-location") || !strcmp (ippGetName (attr), "printer-state-message")) && ippGetValueTag (attr) == IPP_TAG_TEXT) { val = PyObj_from_UTF8 (ippGetString (attr, 0, NULL)); } else if (!strcmp (ippGetName (attr), "printer-state-reasons") && ippGetValueTag (attr) == IPP_TAG_KEYWORD) { val = PyList_from_attr_values (attr); } else if (!strcmp (ippGetName (attr), "printer-is-accepting-jobs") && ippGetValueTag (attr) == IPP_TAG_BOOLEAN) { int b = ippGetBoolean (attr, 0); val = PyLong_FromLong (b); } else if ((!strcmp (ippGetName (attr), "printer-up-time") || !strcmp (ippGetName (attr), "queued-job-count")) && ippGetValueTag (attr) == IPP_TAG_INTEGER) { int u = ippGetInteger (attr, 0); val = PyLong_FromLong (u); } else if ((!strcmp (ippGetName (attr), "device-uri") || !strcmp (ippGetName (attr), "printer-uri-supported")) && ippGetValueTag (attr) == IPP_TAG_URI) { val = PyObj_from_UTF8 (ippGetString (attr, 0, NULL)); } else if (!strcmp (ippGetName (attr), "printer-is-shared") && ippGetValueTag (attr) == IPP_TAG_BOOLEAN) { val = PyBool_FromLong (ippGetBoolean (attr, 0)); } if (val) { debugprintf ("Added %s to dict\n", ippGetName (attr)); PyDict_SetItemString (dict, ippGetName (attr), val); Py_DECREF (val); } } if (printer) { PyObject *key = PyObj_from_UTF8 (printer); PyDict_SetItem (result, key, dict); Py_DECREF (key); } Py_DECREF (dict); if (!attr) break; } ippDelete (answer); debugprintf ("<- Connection_getPrinters() = dict\n"); return result; } static PyObject * Connection_getClasses (Connection *self) { PyObject *result; ipp_t *request = ippNewRequest(CUPS_GET_CLASSES), *answer; ipp_attribute_t *attr; const char *attributes[] = { "printer-name", "member-names", }; debugprintf ("-> Connection_getClasses()\n"); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", sizeof (attributes) / sizeof (attributes[0]), NULL, attributes); debugprintf ("cupsDoRequest(\"/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { if (answer && ippGetStatusCode (answer) == IPP_NOT_FOUND) { // No classes. debugprintf ("<- Connection_getClasses() = {} (no classes)\n"); ippDelete (answer); return PyDict_New (); } set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getClasses() (error)\n"); return NULL; } result = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { PyObject *members = NULL; char *classname = NULL; char *printer_uri = NULL; while (attr && ippGetGroupTag (attr) != IPP_TAG_PRINTER) attr = ippNextAttribute (answer); if (!attr) break; for (; attr && ippGetGroupTag (attr) == IPP_TAG_PRINTER; attr = ippNextAttribute (answer)) { debugprintf ("Attribute: %s\n", ippGetName (attr)); if (!strcmp (ippGetName (attr), "printer-name") && ippGetValueTag (attr) == IPP_TAG_NAME) classname = (char *) ippGetString (attr, 0, NULL); else if (!strcmp (ippGetName (attr), "printer-uri-supported") && ippGetValueTag (attr) == IPP_TAG_URI) printer_uri = (char *) ippGetString (attr, 0, NULL); else if (!strcmp (ippGetName (attr), "member-names") && ippGetValueTag (attr) == IPP_TAG_NAME) { Py_XDECREF (members); members = PyList_from_attr_values (attr); } } if (printer_uri) { Py_XDECREF (members); members = PyObj_from_UTF8 (printer_uri); } if (!members) members = PyList_New (0); if (classname) { PyObject *key = PyObj_from_UTF8 (classname); debugprintf ("Added class %s\n", classname); PyDict_SetItem (result, key, members); Py_DECREF (key); } Py_DECREF (members); if (!attr) break; } ippDelete (answer); debugprintf ("<- Connection_getClasses() = dict\n"); return result; } static PyObject * do_getPPDs (Connection *self, PyObject *args, PyObject *kwds, int all_lists) { PyObject *result = NULL; ipp_t *request, *answer; ipp_attribute_t *attr; int limit = 0; PyObject *exclude_schemes_obj = NULL; /* string list */ PyObject *include_schemes_obj = NULL; /* string list */ char *ppd_natural_language = NULL; PyObject *ppd_device_id_obj = NULL; /* UTF-8 string */ char *ppd_device_id; PyObject *ppd_make_obj = NULL; /* UTF-8 string */ char *ppd_make; PyObject *ppd_make_and_model_obj = NULL; /* UTF-8 string */ char *ppd_make_and_model; int ppd_model_number = -1; PyObject *ppd_product_obj = NULL; /* UTF-8 string */ char *ppd_product; PyObject *ppd_psversion_obj = NULL; /* UTF-8 string */ char *ppd_psversion; char *ppd_type = NULL; static char *kwlist[] = { "limit", "exclude_schemes", "include_schemes", "ppd_natural_language", "ppd_device_id", "ppd_make", "ppd_make_and_model", "ppd_model_number", "ppd_product", "ppd_psversion", "ppd_type", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|iOOsOOOiOOs", kwlist, &limit, &exclude_schemes_obj, &include_schemes_obj, &ppd_natural_language, &ppd_device_id_obj, &ppd_make_obj, &ppd_make_and_model_obj, &ppd_model_number, &ppd_product_obj, &ppd_psversion_obj, &ppd_type)) return NULL; request = ippNewRequest(CUPS_GET_PPDS); if (limit > 0) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "limit", limit); if (exclude_schemes_obj) { size_t i, n; char **ss; if (!PyList_Check (exclude_schemes_obj)) { PyErr_SetString (PyExc_TypeError, "List required (exclude_schemes)"); ippDelete (request); return NULL; } n = PyList_Size (exclude_schemes_obj); ss = calloc (n + 1, sizeof (char *)); for (i = 0; i < n; i++) { PyObject *val = PyList_GetItem (exclude_schemes_obj, i); // borrowed if (!PyUnicode_Check (val) && !PyBytes_Check (val)) { PyErr_SetString (PyExc_TypeError, "String list required (exclude_schemes)"); ippDelete (request); while (i > 0) free (ss[--i]); free (ss); return NULL; } UTF8_from_PyObj (&ss[i], val); } ss[n] = NULL; ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "exclude-schemes", n, NULL, (const char **) ss); for (i = 0; i < n; i++) free (ss[i]); free (ss); } if (include_schemes_obj) { size_t i, n; char **ss; if (!PyList_Check (include_schemes_obj)) { PyErr_SetString (PyExc_TypeError, "List required (include_schemes)"); ippDelete (request); return NULL; } n = PyList_Size (include_schemes_obj); ss = calloc (n + 1, sizeof (char *)); for (i = 0; i < n; i++) { PyObject *val = PyList_GetItem (include_schemes_obj, i); // borrowed if (!PyUnicode_Check (val) && !PyBytes_Check (val)) { PyErr_SetString (PyExc_TypeError, "String list required (include_schemes)"); ippDelete (request); while (i > 0) free (ss[--i]); free (ss); return NULL; } UTF8_from_PyObj (&ss[i], val); } ss[n] = NULL; ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "include-schemes", n, NULL, (const char **) ss); for (i = 0; i < n; i++) free (ss[i]); free (ss); } if (ppd_device_id_obj) { if (UTF8_from_PyObj (&ppd_device_id, ppd_device_id_obj) == NULL) { ippDelete (request); return NULL; } ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "ppd-device-id", NULL, ppd_device_id); free (ppd_device_id); } if (ppd_make_obj) { if (UTF8_from_PyObj (&ppd_make, ppd_make_obj) == NULL) { ippDelete (request); return NULL; } ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "ppd-make", NULL, ppd_make); free (ppd_make); } if (ppd_make_and_model_obj) { if (UTF8_from_PyObj (&ppd_make_and_model, ppd_make_and_model_obj) == NULL) { ippDelete (request); return NULL; } ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "ppd-make-and-model", NULL, ppd_make_and_model); free (ppd_make_and_model); } if (ppd_model_number >= 0) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "ppd-model-number", ppd_model_number); if (ppd_product_obj) { if (UTF8_from_PyObj (&ppd_product, ppd_product_obj) == NULL) { ippDelete (request); return NULL; } ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "ppd-product", NULL, ppd_product); free (ppd_product); } if (ppd_psversion_obj) { if (UTF8_from_PyObj (&ppd_psversion, ppd_psversion_obj) == NULL) { ippDelete (request); return NULL; } ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "ppd-psversion", NULL, ppd_psversion); free (ppd_psversion); } if (ppd_natural_language) ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_LANGUAGE, "ppd-natural-language", NULL, ppd_natural_language); if (ppd_type) ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "ppd-type", NULL, ppd_type); debugprintf ("-> Connection_getPPDs()\n"); debugprintf ("cupsDoRequest(\"/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getPPDs() (error)\n"); return NULL; } result = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { PyObject *dict; char *ppdname = NULL; while (attr && ippGetGroupTag (attr) != IPP_TAG_PRINTER) attr = ippNextAttribute (answer); if (!attr) break; dict = PyDict_New (); for (; attr && ippGetGroupTag (attr) == IPP_TAG_PRINTER; attr = ippNextAttribute (answer)) { PyObject *val = NULL; debugprintf ("Attribute: %s\n", ippGetName (attr)); if (!strcmp (ippGetName (attr), "ppd-name") && ippGetValueTag (attr) == IPP_TAG_NAME) ppdname = (char *) ippGetString (attr, 0, NULL); else { if (all_lists) val = PyList_from_attr_values (attr); else val = PyObject_from_attr_value (attr, 0); if (val) { debugprintf ("Adding %s to ppd dict\n", ippGetName (attr)); PyDict_SetItemString (dict, ippGetName (attr), val); Py_DECREF (val); } } } if (ppdname) { PyObject *key = PyObj_from_UTF8 (ppdname); debugprintf ("Adding %s to result dict\n", ppdname); PyDict_SetItem (result, key, dict); Py_DECREF (key); } Py_DECREF (dict); if (!attr) break; } ippDelete (answer); debugprintf ("<- Connection_getPPDs() = dict\n"); return result; } static PyObject * Connection_getPPDs (Connection *self, PyObject *args, PyObject *kwds) { return do_getPPDs (self, args, kwds, 0); } static PyObject * Connection_getPPDs2 (Connection *self, PyObject *args, PyObject *kwds) { return do_getPPDs (self, args, kwds, 1); } static PyObject * Connection_getServerPPD (Connection *self, PyObject *args) { const char *ppd_name, *filename; if (!PyArg_ParseTuple (args, "s", &ppd_name)) return NULL; debugprintf ("-> Connection_getServerPPD()\n"); Connection_begin_allow_threads (self); filename = cupsGetServerPPD (self->http, ppd_name); Connection_end_allow_threads (self); if (!filename) { set_ipp_error (cupsLastError (), cupsLastErrorString ()); debugprintf ("<- Connection_getServerPPD() (error)\n"); return NULL; } debugprintf ("<- Connection_getServerPPD(\"%s\") = \"%s\"\n", ppd_name, filename); return PyUnicode_FromString (filename); } static PyObject * Connection_getDocument (Connection *self, PyObject *args) { PyObject *dict; PyObject *obj; PyObject *uriobj; char *uri; int jobid, docnum; ipp_t *request, *answer; ipp_attribute_t *attr; const char *format = NULL; const char *name = NULL; char docfilename[PATH_MAX]; int fd; if (!PyArg_ParseTuple (args, "Oii", &uriobj, &jobid, &docnum)) return NULL; if (UTF8_from_PyObj (&uri, uriobj) == NULL) return NULL; debugprintf ("-> Connection_getDocument(\"%s\",%d)\n", uri, jobid); request = ippNewRequest (CUPS_GET_DOCUMENT); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); free (uri); ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", jobid); ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "document-number", docnum); snprintf(docfilename, sizeof (docfilename), "%s/jobdoc-XXXXXX", _PATH_TMP); fd = mkstemp (docfilename); if (fd < 0) { debugprintf ("<- Connection_getDocument() EXCEPTION\n"); ippDelete (request); return PyErr_SetFromErrno (PyExc_RuntimeError); } Connection_begin_allow_threads (self); answer = cupsDoIORequest (self->http, request, "/", -1, fd); Connection_end_allow_threads (self); close (fd); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { unlink (docfilename); set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getDocument() (error)\n"); return NULL; } if ((attr = ippFindAttribute (answer, "document-format", IPP_TAG_MIMETYPE)) != NULL) format = ippGetString (attr, 0, NULL); if ((attr = ippFindAttribute (answer, "document-name", IPP_TAG_NAME)) != NULL) name = ippGetString (attr, 0, NULL); dict = PyDict_New (); obj = PyUnicode_FromString (docfilename); PyDict_SetItemString (dict, "file", obj); Py_DECREF (obj); if (format) { obj = PyUnicode_FromString (format); PyDict_SetItemString (dict, "document-format", obj); Py_DECREF (obj); } if (name) { obj = PyObj_from_UTF8 (name); PyDict_SetItemString (dict, "document-name", obj); Py_DECREF (obj); } debugprintf ("<- Connection_getDocument() = {'file':\"%s\"," "'document-format':\"%s\",'document-name':\"%s\"}\n", docfilename, format ? format : "(nul)", name ? name : "(nul)"); ippDelete (answer); return dict; } static PyObject * Connection_getDevices (Connection *self, PyObject *args, PyObject *kwds) { PyObject *result; ipp_t *request, *answer; ipp_attribute_t *attr; int limit = 0; int timeout = 0; PyObject *exclude_schemes = NULL; PyObject *include_schemes = NULL; static char *kwlist[] = { "limit", "exclude_schemes", "include_schemes", "timeout", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|iOOi", kwlist, &limit, &exclude_schemes, &include_schemes, &timeout)) return NULL; request = ippNewRequest(CUPS_GET_DEVICES); if (limit > 0) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "limit", limit); if (exclude_schemes) { size_t i, n; char **ss; if (!PyList_Check (exclude_schemes)) { PyErr_SetString (PyExc_TypeError, "List required (exclude_schemes)"); ippDelete (request); return NULL; } n = PyList_Size (exclude_schemes); ss = calloc (n + 1, sizeof (char *)); for (i = 0; i < n; i++) { PyObject *val = PyList_GetItem (exclude_schemes, i); // borrowed ref if (!PyUnicode_Check (val) && !PyBytes_Check (val)) { PyErr_SetString (PyExc_TypeError, "String list required (exclude_schemes)"); ippDelete (request); while (i > 0) free (ss[--i]); free (ss); return NULL; } UTF8_from_PyObj (&ss[i], val); } ss[n] = NULL; ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "exclude-schemes", n, NULL, (const char **) ss); for (i = 0; i < n; i++) free (ss[i]); free (ss); } if (include_schemes) { size_t i, n; char **ss; if (!PyList_Check (include_schemes)) { PyErr_SetString (PyExc_TypeError, "List required (include_schemes)"); ippDelete (request); return NULL; } n = PyList_Size (include_schemes); ss = calloc (n + 1, sizeof (char *)); for (i = 0; i < n; i++) { PyObject *val = PyList_GetItem (include_schemes, i); // borrowed ref if (!PyUnicode_Check (val) && !PyBytes_Check (val)) { PyErr_SetString (PyExc_TypeError, "String list required (include_schemes)"); ippDelete (request); while (i > 0) free (ss[--i]); free (ss); return NULL; } UTF8_from_PyObj (&ss[i], val); } ss[n] = NULL; ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "include-schemes", n, NULL, (const char **) ss); for (i = 0; i < n; i++) free (ss[i]); free (ss); } if (timeout > 0) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "timeout", timeout); debugprintf ("-> Connection_getDevices()\n"); debugprintf ("cupsDoRequest(\"/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getDevices() (error)\n"); return NULL; } result = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { PyObject *dict; char *device_uri = NULL; while (attr && ippGetGroupTag (attr) != IPP_TAG_PRINTER) attr = ippNextAttribute (answer); if (!attr) break; dict = PyDict_New (); for (; attr && ippGetGroupTag (attr) == IPP_TAG_PRINTER; attr = ippNextAttribute (answer)) { PyObject *val = NULL; debugprintf ("Attribute: %s\n", ippGetName (attr)); if (!strcmp (ippGetName (attr), "device-uri") && ippGetValueTag (attr) == IPP_TAG_URI) device_uri = (char *) ippGetString (attr, 0, NULL); else val = PyObject_from_attr_value (attr, 0); if (val) { debugprintf ("Adding %s to device dict\n", ippGetName (attr)); PyDict_SetItemString (dict, ippGetName (attr), val); Py_DECREF (val); } } if (device_uri) { PyObject *key = PyObj_from_UTF8 (device_uri); debugprintf ("Adding %s to result dict\n", device_uri); PyDict_SetItem (result, key, dict); Py_DECREF (key); } Py_DECREF (dict); if (!attr) break; } ippDelete (answer); debugprintf ("<- Connection_getDevices() = dict\n"); return result; } static int get_requested_attrs (PyObject *requested_attrs, size_t *n_attrs, char ***attrs) { long unsigned int i; size_t n; char **as; if (!PyList_Check (requested_attrs)) { PyErr_SetString (PyExc_TypeError, "List required"); return -1; } n = PyList_Size (requested_attrs); as = malloc ((n + 1) * sizeof (char *)); for (i = 0; i < n; i++) { PyObject *val = PyList_GetItem (requested_attrs, i); // borrowed ref if (!PyUnicode_Check (val) && !PyBytes_Check (val)) { PyErr_SetString (PyExc_TypeError, "String required"); while (--i >= 0) free (as[i]); free (as); return -1; } UTF8_from_PyObj (&as[i], val); } as[n] = NULL; debugprintf ("Requested attributes:\n"); for (i = 0; as[i] != NULL; i++) debugprintf (" %s\n", as[i]); *n_attrs = n; *attrs = as; return 0; } static void free_requested_attrs (size_t n_attrs, char **attrs) { long unsigned int i; for (i = 0; i < n_attrs; i++) free (attrs[i]); free (attrs); } static PyObject * Connection_getJobs (Connection *self, PyObject *args, PyObject *kwds) { PyObject *result; ipp_t *request, *answer; ipp_attribute_t *attr; char *which = NULL; int my_jobs = 0; int limit = -1; int first_job_id = -1; PyObject *requested_attrs = NULL; char **attrs = NULL; /* initialised to calm compiler */ size_t n_attrs = 0; /* initialised to calm compiler */ static char *kwlist[] = { "which_jobs", "my_jobs", "limit", "first_job_id", "requested_attributes", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|siiiO", kwlist, &which, &my_jobs, &limit, &first_job_id, &requested_attrs)) return NULL; debugprintf ("-> Connection_getJobs(%s,%d)\n", which ? which : "(null)", my_jobs); request = ippNewRequest(IPP_GET_JOBS); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "ipp://localhost/printers/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "which-jobs", NULL, which ? which : "not-completed"); ippAddBoolean (request, IPP_TAG_OPERATION, "my-jobs", my_jobs); if (my_jobs) ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser()); if (limit > 0) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "limit", limit); if (first_job_id > 0) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "first-job-id", first_job_id); if (requested_attrs) { if (get_requested_attrs (requested_attrs, &n_attrs, &attrs) == -1) { ippDelete (request); return NULL; } ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", n_attrs, NULL, (const char **) attrs); free_requested_attrs (n_attrs, attrs); } debugprintf ("cupsDoRequest(\"/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getJobs() (error)\n"); return NULL; } result = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { PyObject *dict; int job_id = -1; while (attr && ippGetGroupTag (attr) != IPP_TAG_JOB) attr = ippNextAttribute (answer); if (!attr) break; dict = PyDict_New (); for (; attr && ippGetGroupTag (attr) == IPP_TAG_JOB; attr = ippNextAttribute (answer)) { PyObject *val = NULL; debugprintf ("Attribute: %s\n", ippGetName (attr)); if (!strcmp (ippGetName (attr), "job-id") && ippGetValueTag (attr) == IPP_TAG_INTEGER) job_id = ippGetInteger (attr, 0); else if (((!strcmp (ippGetName (attr), "job-k-octets") || !strcmp (ippGetName (attr), "job-priority") || !strcmp (ippGetName (attr), "time-at-creation") || !strcmp (ippGetName (attr), "time-at-processing") || !strcmp (ippGetName (attr), "time-at-completed") || !strcmp (ippGetName (attr), "job-media-sheets") || !strcmp (ippGetName (attr), "job-media-sheets-completed")) && ippGetValueTag (attr) == IPP_TAG_INTEGER) || (!strcmp (ippGetName (attr), "job-state") && ippGetValueTag (attr) == IPP_TAG_ENUM)) val = PyLong_FromLong (ippGetInteger (attr, 0)); else if ((!strcmp (ippGetName (attr), "job-name") && ippGetValueTag (attr) == IPP_TAG_NAME) || (!strcmp (ippGetName (attr), "job-originating-user-name") && ippGetValueTag (attr) == IPP_TAG_NAME) || (!strcmp (ippGetName (attr), "job-printer-uri") && ippGetValueTag (attr) == IPP_TAG_URI)) val = PyObj_from_UTF8 (ippGetString (attr, 0, NULL)); else if (!strcmp (ippGetName (attr), "job-preserved") && ippGetValueTag (attr) == IPP_TAG_BOOLEAN) val = PyBool_FromLong (ippGetInteger (attr, 0)); else { if (ippGetCount (attr) > 1) val = PyList_from_attr_values (attr); else val = PyObject_from_attr_value (attr, 0); } if (val) { debugprintf ("Adding %s to job dict\n", ippGetName (attr)); PyDict_SetItemString (dict, ippGetName (attr), val); Py_DECREF (val); } } if (job_id != -1) { debugprintf ("Adding %d to result dict\n", job_id); PyObject *job_obj = PyLong_FromLong (job_id); PyDict_SetItem (result, job_obj, dict); Py_DECREF (job_obj); } Py_DECREF (dict); if (!attr) break; } ippDelete (answer); debugprintf ("<- Connection_getJobs() = dict\n"); return result; } static PyObject * Connection_getJobAttributes (Connection *self, PyObject *args, PyObject *kwds) { PyObject *result; ipp_t *request, *answer; ipp_attribute_t *attr; int job_id; PyObject *requested_attrs = NULL; char **attrs = NULL; /* initialised to calm compiler */ size_t n_attrs = 0; /* initialised to calm compiler */ char uri[1024]; static char *kwlist[] = { "job_id", "requested_attributes", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "i|O", kwlist, &job_id, &requested_attrs)) return NULL; if (requested_attrs) { if (get_requested_attrs (requested_attrs, &n_attrs, &attrs) == -1) return NULL; } debugprintf ("-> Connection_getJobAttributes(%d)\n", job_id); request = ippNewRequest(IPP_GET_JOB_ATTRIBUTES); snprintf (uri, sizeof (uri), "ipp://localhost/jobs/%d", job_id); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri); if (requested_attrs) ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", n_attrs, NULL, (const char **) attrs); debugprintf ("cupsDoRequest(\"/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (requested_attrs) free_requested_attrs (n_attrs, attrs); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getJobAttributes() (error)\n"); return NULL; } result = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { PyObject *obj; debugprintf ("Attr: %s\n", ippGetName (attr)); if (ippGetCount (attr) > 1 || !strcmp (ippGetName (attr), "job-printer-state-reasons")) obj = PyList_from_attr_values (attr); else obj = PyObject_from_attr_value (attr, 0); if (!obj) // Can't represent this. continue; PyDict_SetItemString (result, ippGetName (attr), obj); Py_DECREF (obj); } ippDelete (answer); debugprintf ("<- Connection_getJobAttributes() = dict\n"); return result; } static PyObject * Connection_cancelJob (Connection *self, PyObject *args, PyObject *kwds) { ipp_t *request, *answer; int job_id; int purge_job = 0; char uri[1024]; static char *kwlist[] = { "job_id", "purge_job", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "i|i", kwlist, &job_id, &purge_job)) return NULL; debugprintf ("-> Connection_cancelJob(%d)\n", job_id); request = ippNewRequest(IPP_CANCEL_JOB); snprintf (uri, sizeof (uri), "ipp://localhost/jobs/%d", job_id); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); if (purge_job) ippAddBoolean(request, IPP_TAG_OPERATION, "purge-job", 1); debugprintf ("cupsDoRequest(\"/jobs/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/jobs/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_cancelJob() (error)\n"); return NULL; } debugprintf ("<- Connection_cancelJob() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_cancelAllJobs (Connection *self, PyObject *args, PyObject *kwds) { PyObject *nameobj = NULL; char *name; PyObject *uriobj = NULL; char *uri; char consuri[HTTP_MAX_URI]; ipp_t *request, *answer; int my_jobs = 0; int purge_jobs = 1; int i; static char *kwlist[] = { "name", "uri", "my_jobs", "purge_jobs", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|OOii", kwlist, &nameobj, &uriobj, &my_jobs, &purge_jobs)) return NULL; if (nameobj && uriobj) { PyErr_SetString (PyExc_RuntimeError, "name or uri must be specified but not both"); return NULL; } if (nameobj) { if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; } else if (uriobj) { if (UTF8_from_PyObj (&uri, uriobj) == NULL) return NULL; } else { PyErr_SetString (PyExc_RuntimeError, "name or uri must be specified"); return NULL; } debugprintf ("-> Connection_cancelAllJobs(%s, my_jobs=%d, purge_jobs=%d)\n", nameobj ? name : uri, my_jobs, purge_jobs); if (nameobj) { construct_uri (consuri, sizeof (consuri), "ipp://localhost/printers/", name); uri = consuri; } for (i = 0; i < 2; i++) { request = ippNewRequest(IPP_PURGE_JOBS); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); if (my_jobs) { ippAddBoolean (request, IPP_TAG_OPERATION, "my-jobs", my_jobs); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser()); } ippAddBoolean (request, IPP_TAG_OPERATION, "purge-jobs", purge_jobs); debugprintf ("cupsDoRequest(\"/admin/\") with printer-uri=%s\n", uri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); if (uriobj) break; // Perhaps it's a class, not a printer. construct_uri (consuri, sizeof (consuri), "ipp://localhost/classes/", name); } else break; } if (nameobj) free (name); if (uriobj) free (uri); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_cancelAllJobs() (error)\n"); return NULL; } debugprintf ("<- Connection_cancelAllJobs() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_createJob (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "printer", "title", "options", NULL }; PyObject *printer_obj; char *printer; PyObject *title_obj; char *title; PyObject *options_obj, *key, *val; int num_settings = 0; DICT_POS_TYPE pos = 0; cups_option_t *settings = NULL; int jobid; if (!PyArg_ParseTupleAndKeywords (args, kwds, "OOO", kwlist, &printer_obj, &title_obj, &options_obj)) return NULL; if (UTF8_from_PyObj (&printer, printer_obj) == NULL) return NULL; if (UTF8_from_PyObj (&title, title_obj) == NULL) { free (printer); return NULL; } debugprintf ("-> Connection_createJob(printer=%s, title=%s)\n", printer, title); if (!PyDict_Check (options_obj)) { free (title); free (printer); PyErr_SetString (PyExc_TypeError, "options must be a dict"); return NULL; } while (PyDict_Next (options_obj, &pos, &key, &val)) { char *name, *value; if ((!PyUnicode_Check (key) && !PyBytes_Check (key)) || (!PyUnicode_Check (val) && !PyBytes_Check (val))) { cupsFreeOptions (num_settings, settings); free (title); free (printer); PyErr_SetString (PyExc_TypeError, "Keys and values must be strings"); return NULL; } num_settings = cupsAddOption (UTF8_from_PyObj (&name, key), UTF8_from_PyObj (&value, val), num_settings, &settings); free (name); free (value); } Connection_begin_allow_threads (self); jobid = cupsCreateJob(self->http, printer, title, num_settings, settings); Connection_end_allow_threads (self); if (jobid == 0) { cupsFreeOptions (num_settings, settings); free (title); free (printer); set_ipp_error (cupsLastError (), cupsLastErrorString ()); debugprintf ("<- Connection_createJob() = NULL\n"); return NULL; } cupsFreeOptions (num_settings, settings); free (title); free (printer); debugprintf ("<- Connection_createJob() = %d\n", jobid); return PyLong_FromLong (jobid); } static PyObject * Connection_startDocument (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "printer", "job_id", "doc_name", "format", "last_document", NULL }; PyObject *printer_obj; char *printer; int jobid; PyObject *doc_name_obj; char *doc_name; PyObject *format_obj; char *format; int last_document; http_status_t status; /* Write status */ if (!PyArg_ParseTupleAndKeywords (args, kwds, "OiOOi", kwlist, &printer_obj, &jobid, &doc_name_obj, &format_obj, &last_document)) return NULL; if (UTF8_from_PyObj (&printer, printer_obj) == NULL) return NULL; if (UTF8_from_PyObj (&doc_name, doc_name_obj) == NULL) { free (printer); return NULL; } if (UTF8_from_PyObj (&format, format_obj) == NULL) { free (doc_name); free (printer); return NULL; } debugprintf ("-> Connection_startDocument(printer=%s, jobid=%d, doc_name=%s, format=%s)\n", printer, jobid, doc_name, format); Connection_begin_allow_threads (self); status = cupsStartDocument(self->http, printer, jobid, doc_name, format, last_document); Connection_end_allow_threads (self); if (status != HTTP_CONTINUE) { free (format); free (doc_name); free (printer); set_ipp_error (cupsLastError (), cupsLastErrorString ()); debugprintf ("<- Connection_startDocument() = NULL\n"); return NULL; } free (format); free (doc_name); free (printer); debugprintf ("<- Connection_startDocument() = %d\n", status); return PyLong_FromLong (status); } static PyObject * Connection_writeRequestData (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "buffer", "length", NULL }; PyObject *buffer_obj; char *buffer; int length; http_status_t status; /* Write status */ if (!PyArg_ParseTupleAndKeywords (args, kwds, "Oi", kwlist, &buffer_obj, &length)) return NULL; buffer = (char *) malloc((size_t) length); memcpy(buffer, PyBytes_AsString(buffer_obj), length); debugprintf ("-> Connection_writeRequestData(length=%d)\n", length); Connection_begin_allow_threads (self); status = cupsWriteRequestData(self->http, buffer, length); Connection_end_allow_threads (self); if (status != HTTP_CONTINUE) { free (buffer); set_ipp_error (cupsLastError (), cupsLastErrorString ()); debugprintf ("<- Connection_writeRequestData() = NULL\n"); return NULL; } free (buffer); debugprintf ("<- Connection_writeRequestData() = %d\n", status); return PyLong_FromLong (status); } static PyObject * Connection_finishDocument (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "printer", NULL }; PyObject *printer_obj; char *printer; int answer; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O", kwlist, &printer_obj)) return NULL; if (UTF8_from_PyObj (&printer, printer_obj) == NULL) return NULL; debugprintf ("-> Connection_finishDocument(printer=%s)\n", printer); Connection_begin_allow_threads (self); answer = cupsFinishDocument(self->http, printer); Connection_end_allow_threads (self); if (answer != IPP_OK) { free (printer); set_ipp_error (cupsLastError (), cupsLastErrorString ()); debugprintf ("<- Connection_finishDocument() = NULL\n"); return NULL; } free (printer); debugprintf ("<- Connection_finishDicument() = %d\n", answer); return PyLong_FromLong (answer); } static PyObject * Connection_moveJob (Connection *self, PyObject *args, PyObject *kwds) { int job_id = -1; PyObject *printeruriobj = NULL; char *printeruri; PyObject *jobprinteruriobj = NULL; char *jobprinteruri; ipp_t *request, *answer; static char *kwlist[] = { "printer_uri", "job_id", "job_printer_uri", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|OiO", kwlist, &printeruriobj, &job_id, &jobprinteruriobj)) return NULL; if (!jobprinteruriobj) { PyErr_SetString (PyExc_RuntimeError, "No job_printer_uri (destination) given"); return NULL; } if (printeruriobj) { if (UTF8_from_PyObj (&printeruri, printeruriobj) == NULL) return NULL; } else if (job_id == -1) { PyErr_SetString (PyExc_RuntimeError, "job_id or printer_uri required"); return NULL; } if (UTF8_from_PyObj (&jobprinteruri, jobprinteruriobj) == NULL) { if (printeruriobj) free (printeruri); return NULL; } request = ippNewRequest (CUPS_MOVE_JOB); if (!printeruriobj) { char joburi[HTTP_MAX_URI]; snprintf (joburi, sizeof (joburi), "ipp://localhost/jobs/%d", job_id); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, joburi); } else { ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, printeruri); free (printeruri); if (job_id != -1) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", job_id); } ippAddString (request, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri", NULL, jobprinteruri); free (jobprinteruri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/jobs"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_authenticateJob (Connection *self, PyObject *args) { ipp_t *request, *answer; int job_id; PyObject *auth_info_list = NULL; long unsigned int num_auth_info = 0; /* initialised to calm compiler */ char *auth_info_values[3]; long unsigned int i; char uri[1024]; if (!PyArg_ParseTuple (args, "i|O", &job_id, &auth_info_list)) return NULL; if (auth_info_list) { if (!PyList_Check (auth_info_list)) { PyErr_SetString (PyExc_TypeError, "List required"); return NULL; } num_auth_info = PyList_Size (auth_info_list); debugprintf ("sizeof values = %Zd\n", sizeof (auth_info_values)); if (num_auth_info > sizeof (auth_info_values)) num_auth_info = sizeof (auth_info_values); for (i = 0; i < num_auth_info; i++) { PyObject *val = PyList_GetItem (auth_info_list, i); // borrowed ref if (UTF8_from_PyObj (&auth_info_values[i], val) == NULL) { while (--i >= 0) free (auth_info_values[i]); return NULL; } } } debugprintf ("-> Connection_authenticateJob(%d)\n", job_id); request = ippNewRequest(CUPS_AUTHENTICATE_JOB); snprintf (uri, sizeof (uri), "ipp://localhost/jobs/%d", job_id); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); if (auth_info_list) { ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_TEXT, "auth-info", num_auth_info, NULL, (const char *const *) auth_info_values); for (i = 0; i < num_auth_info; i++) free (auth_info_values[i]); } debugprintf ("cupsDoRequest(\"/jobs/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/jobs/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_authenticateJob() (error)\n"); return NULL; } debugprintf ("<- Connection_authenticateJob() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_setJobHoldUntil (Connection *self, PyObject *args) { ipp_t *request, *answer; int job_id; PyObject *job_hold_until_obj; char *job_hold_until; char uri[1024]; cups_option_t *options = NULL; int num_options = 0; if (!PyArg_ParseTuple (args, "iO", &job_id, &job_hold_until_obj)) return NULL; if (UTF8_from_PyObj (&job_hold_until, job_hold_until_obj) == NULL) return NULL; debugprintf ("-> Connection_setJobHoldUntil(%d,%s)\n", job_id, job_hold_until); request = ippNewRequest(IPP_SET_JOB_ATTRIBUTES); snprintf (uri, sizeof (uri), "ipp://localhost/jobs/%d", job_id); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); num_options = cupsAddOption ("job-hold-until", job_hold_until, num_options, &options); cupsEncodeOptions (request, num_options, options); free (job_hold_until); debugprintf ("cupsDoRequest(\"/jobs/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/jobs/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_setJobHoldUntil() (error)\n"); return NULL; } debugprintf ("<- Connection_setJobHoldUntil() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_restartJob (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "job_id", "job_hold_until", NULL }; ipp_t *request, *answer; int job_id; char *job_hold_until = NULL; char uri[1024]; if (!PyArg_ParseTupleAndKeywords (args, kwds, "i|s", kwlist, &job_id, &job_hold_until)) return NULL; debugprintf ("-> Connection_restartJob(%d)\n", job_id); request = ippNewRequest(IPP_RESTART_JOB); snprintf (uri, sizeof (uri), "ipp://localhost/jobs/%d", job_id); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); if (job_hold_until) ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-hold-until", NULL, job_hold_until); debugprintf ("cupsDoRequest(\"/jobs/\")\n"); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/jobs/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_restartJob() (error)\n"); return NULL; } debugprintf ("<- Connection_restartJob() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_getFile (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "resource", "filename", "fd", "file", NULL }; const char *resource, *filename = NULL; int fd = -1; PyObject *fileobj = NULL; http_status_t status; if (!PyArg_ParseTupleAndKeywords (args, kwds, "s|siO", kwlist, &resource, &filename, &fd, &fileobj)) return NULL; if ((fd > -1 && (filename || fileobj)) || (filename && fileobj)) { PyErr_SetString (PyExc_RuntimeError, "Only one destination type may be specified"); return NULL; } if (fileobj) { fd = PyObject_AsFileDescriptor(fileobj); } if (filename) { debugprintf ("-> Connection_getFile(%s, %s)\n", resource, filename); debugprintf ("cupsGetFile()\n"); Connection_begin_allow_threads (self); status = cupsGetFile (self->http, resource, filename); Connection_end_allow_threads (self); } else { debugprintf ("-> Connection_getFile(%s, %d)\n", resource, fd); debugprintf ("cupsGetFd()\n"); Connection_begin_allow_threads (self); status = cupsGetFd (self->http, resource, fd); Connection_end_allow_threads (self); } if (status != HTTP_OK) { set_http_error (status); debugprintf ("<- Connection_getFile() (error)\n"); return NULL; } debugprintf ("<- Connection_getFile() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_putFile (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "resource", "filename", "fd", "file", NULL }; const char *resource, *filename = NULL; int fd = -1; PyObject *fileobj = NULL; http_status_t status; if (!PyArg_ParseTupleAndKeywords (args, kwds, "s|siO", kwlist, &resource, &filename, &fd, &fileobj)) return NULL; if ((fd > -1 && (filename || fileobj)) || (filename && fileobj)) { PyErr_SetString (PyExc_RuntimeError, "Only one destination type may be specified"); return NULL; } if (fileobj) { fd = PyObject_AsFileDescriptor(fileobj); } if (filename) { debugprintf ("-> Connection_putFile(%s, %s)\n", resource, filename); debugprintf ("cupsPutFile()\n"); Connection_begin_allow_threads (self); status = cupsPutFile (self->http, resource, filename); Connection_end_allow_threads (self); } else { debugprintf ("-> Connection_putFile(%s, %d)\n", resource, fd); debugprintf ("cupsPutFd()\n"); Connection_begin_allow_threads (self); status = cupsPutFd (self->http, resource, fd); Connection_end_allow_threads (self); } if (status != HTTP_OK && status != HTTP_CREATED) { set_http_error (status); debugprintf ("<- Connection_putFile() (error)\n"); return NULL; } debugprintf ("<- Connection_putFile() = None\n"); Py_RETURN_NONE; } static ipp_t * add_modify_printer_request (const char *name) { char uri[HTTP_MAX_URI]; ipp_t *request = ippNewRequest (CUPS_ADD_MODIFY_PRINTER); construct_uri (uri, sizeof (uri), "ipp://localhost/printers/", name); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); return request; } static ipp_t * add_modify_class_request (const char *name) { char uri[HTTP_MAX_URI]; ipp_t *request = ippNewRequest (CUPS_ADD_MODIFY_CLASS); construct_uri (uri, sizeof (uri), "ipp://localhost/classes/", name); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); return request; } static PyObject * Connection_addPrinter (Connection *self, PyObject *args, PyObject *kwds) { PyObject *nameobj = NULL; char *name = NULL; PyObject *ppdfileobj = NULL; char *ppdfile = NULL; PyObject *ppdnameobj = NULL; char *ppdname = NULL; PyObject *infoobj = NULL; char *info = NULL; PyObject *locationobj = NULL; char *location = NULL; PyObject *deviceobj = NULL; char *device = NULL; PyObject *ppd = NULL; ipp_t *request, *answer; int ppds_specified = 0; static char *kwlist[] = { "name", "filename", "ppdname", "info", "location", "device", "ppd", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|OOOOOO", kwlist, &nameobj, &ppdfileobj, &ppdnameobj, &infoobj, &locationobj, &deviceobj, &ppd)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL || (ppdfileobj && UTF8_from_PyObj (&ppdfile, ppdfileobj) == NULL) || (ppdnameobj && UTF8_from_PyObj (&ppdname, ppdnameobj) == NULL) || (infoobj && UTF8_from_PyObj (&info, infoobj) == NULL) || (locationobj && UTF8_from_PyObj (&location, locationobj) == NULL) || (deviceobj && UTF8_from_PyObj (&device, deviceobj) == NULL)) { free (name); free (ppdfile); free (ppdname); free (info); free (location); free (device); return NULL; } debugprintf ("-> Connection_addPrinter(%s,%s,%s,%s,%s,%s,%s)\n", name, ppdfile ? ppdfile: "", ppdname ? ppdname: "", info ? info: "", location ? location: "", device ? device: "", ppd ? "(PPD object)": ""); if (ppdfile) ppds_specified++; if (ppdname) ppds_specified++; if (ppd) { if (!PyObject_TypeCheck (ppd, &cups_PPDType)) { PyErr_SetString (PyExc_TypeError, "Expecting cups.PPD"); debugprintf ("<- Connection_addPrinter() EXCEPTION\n"); free (name); free (ppdfile); free (ppdname); free (info); free (location); free (device); return NULL; } ppds_specified++; } if (ppds_specified > 1) { PyErr_SetString (PyExc_RuntimeError, "Only one PPD may be given"); debugprintf ("<- Connection_addPrinter() EXCEPTION\n"); free (name); free (ppdfile); free (ppdname); free (info); free (location); free (device); return NULL; } if (ppd) { // We've been given a cups.PPD object. Construct a PPD file. char template[PATH_MAX]; int fd; PyObject *args, *result; snprintf(template, sizeof (template), "%s/scp-ppd-XXXXXX", _PATH_TMP); ppdfile = strdup(template); fd = mkstemp (ppdfile); if (fd < 0) { debugprintf ("<- Connection_addPrinter() EXCEPTION\n"); free (name); free (ppdfile); free (ppdname); free (info); free (location); free (device); return PyErr_SetFromErrno (PyExc_RuntimeError); } args = Py_BuildValue ("(i)", fd); result = PPD_writeFd ((PPD *) ppd, args); Py_DECREF (args); close (fd); if (result == NULL) { unlink (ppdfile); debugprintf ("<- Connection_addPrinter() EXCEPTION\n"); free (name); free (ppdfile); free (ppdname); free (info); free (location); free (device); return NULL; } } request = add_modify_printer_request (name); free (name); if (ppdname) { ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "ppd-name", NULL, ppdname); free (ppdname); } if (info) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, info); free (info); } if (location) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", NULL, location); free (location); } if (device) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL, device); free (device); } if (ppds_specified) ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_KEYWORD, "printer-state-reasons", NULL, "none"); Connection_begin_allow_threads (self); if (ppdfile) { answer = cupsDoFileRequest (self->http, request, "/admin/", ppdfile); } else answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (ppd) { unlink (ppdfile); free (ppdfile); } else if (ppdfile) free (ppdfile); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); debugprintf ("<- Connection_addPrinter() EXCEPTION\n"); return NULL; } if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_addPrinter() EXCEPTION\n"); return NULL; } ippDelete (answer); debugprintf ("<- Connection_addPrinter() = None\n"); Py_RETURN_NONE; } static PyObject * Connection_setPrinterDevice (Connection *self, PyObject *args) { PyObject *nameobj; PyObject *device_uriobj; char *name; char *device_uri; ipp_t *request, *answer; if (!PyArg_ParseTuple (args, "OO", &nameobj, &device_uriobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&device_uri, device_uriobj) == NULL) { free (name); return NULL; } request = add_modify_printer_request (name); free (name); ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL, device_uri); free (device_uri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterInfo (Connection *self, PyObject *args) { PyObject *nameobj; PyObject *infoobj; char *name; char *info; ipp_t *request, *answer; int i; if (!PyArg_ParseTuple (args, "OO", &nameobj, &infoobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&info, infoobj) == NULL) { free (name); return NULL; } request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, info); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { // Perhaps it's a class, not a printer. ippDelete (answer); request = add_modify_class_request (name); } else break; } free (name); free (info); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterLocation (Connection *self, PyObject *args) { PyObject *nameobj; PyObject *locationobj; char *name; char *location; ipp_t *request, *answer; int i; if (!PyArg_ParseTuple (args, "OO", &nameobj, &locationobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&location, locationobj) == NULL) { free (name); return NULL; } request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", NULL, location); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { // Perhaps it's a class, not a printer. ippDelete (answer); request = add_modify_class_request (name); } else break; } free (name); free (location); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterShared (Connection *self, PyObject *args) { PyObject *nameobj; char *name; int sharing; ipp_t *request, *answer; int i; if (!PyArg_ParseTuple (args, "Oi", &nameobj, &sharing)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { ippAddBoolean (request, IPP_TAG_OPERATION, "printer-is-shared", sharing); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { // Perhaps it's a class, not a printer. ippDelete (answer); request = add_modify_class_request (name); } else break; } free (name); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterJobSheets (Connection *self, PyObject *args) { PyObject *nameobj; PyObject *startobj; PyObject *endobj; char *name; char *start; char *end; ipp_t *request, *answer; ipp_attribute_t *a; int i; if (!PyArg_ParseTuple (args, "OOO", &nameobj, &startobj, &endobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&start, startobj) == NULL) { free (name); return NULL; } if (UTF8_from_PyObj (&end, endobj) == NULL) { free (name); free (start); return NULL; } request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { a = ippAddStrings (request, IPP_TAG_PRINTER, IPP_TAG_NAME, "job-sheets-default", 2, NULL, NULL); ippSetString(request, &a, 0, strdup (start)); ippSetString(request, &a, 1, strdup (end)); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); // Perhaps it's a class, not a printer. request = add_modify_class_request (name); } else break; } free (name); free (start); free (end); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterErrorPolicy (Connection *self, PyObject *args) { PyObject *nameobj; char *name; PyObject *policyobj; char *policy; ipp_t *request, *answer; int i; if (!PyArg_ParseTuple (args, "OO", &nameobj, &policyobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&policy, policyobj) == NULL) { free (name); return NULL; } request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_NAME, "printer-error-policy", NULL, policy); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); // Perhaps it's a class, not a printer. request = add_modify_class_request (name); } else break; } free (name); free (policy); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterOpPolicy (Connection *self, PyObject *args) { PyObject *nameobj; char *name; PyObject *policyobj; char *policy; ipp_t *request, *answer; int i; if (!PyArg_ParseTuple (args, "OO", &nameobj, &policyobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&policy, policyobj) == NULL) { free (name); return NULL; } request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_NAME, "printer-op-policy", NULL, policy); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); // Perhaps it's a class, not a printer. request = add_modify_class_request (name); } else break; } free (name); free (policy); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * do_requesting_user_names (Connection *self, PyObject *args, const char *requeststr) { PyObject *nameobj; char *name; char *tmp; PyObject *users; int num_users, i, j; ipp_t *request, *answer; ipp_attribute_t *attr; if (!PyArg_ParseTuple (args, "OO", &nameobj, &users)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (!PyList_Check (users)) { PyErr_SetString (PyExc_TypeError, "List required"); return NULL; } request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { num_users = PyList_Size (users); if (num_users) { attr = ippAddStrings (request, IPP_TAG_PRINTER, IPP_TAG_NAME, requeststr, num_users, NULL, NULL); for (j = 0; j < num_users; j++) { PyObject *username = PyList_GetItem (users, j); // borrowed ref if (!PyUnicode_Check (username) && !PyBytes_Check (username)) { int k; PyErr_SetString (PyExc_TypeError, "String required"); for (k = 0; k < j; k++) { free ((void *)ippGetString (attr, k, NULL)); ippSetString(request, &attr, k, NULL); } ippDelete (request); return NULL; } ippSetString(request, &attr, j, UTF8_from_PyObj (&tmp, username)); free(tmp); } } else { attr = ippAddStrings (request, IPP_TAG_PRINTER, IPP_TAG_NAME, requeststr, 1, NULL, NULL); if (strstr (requeststr, "denied")) ippSetString(request, &attr, 0, strdup ("none")); else ippSetString(request, &attr, 0, strdup ("all")); } Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); // Perhaps it's a class, not a printer. request = add_modify_class_request (name); } else break; } free (name); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_setPrinterUsersAllowed (Connection *self, PyObject *args) { return do_requesting_user_names (self, args, "requesting-user-name-allowed"); } static PyObject * Connection_setPrinterUsersDenied (Connection *self, PyObject *args) { return do_requesting_user_names (self, args, "requesting-user-name-denied"); } static char * PyObject_to_string (PyObject *pyvalue) { char string[BUFSIZ]; char *value = "{unknown type}"; if (PyUnicode_Check (pyvalue) || PyBytes_Check (pyvalue)) { UTF8_from_PyObj (&value, pyvalue); } else if (PyBool_Check (pyvalue)) { value = (pyvalue == Py_True) ? "true" : "false"; } else if (PyLong_Check (pyvalue)) { long v = PyLong_AsLong (pyvalue); snprintf (string, sizeof (string), "%ld", v); value = string; } else if (PyFloat_Check (pyvalue)) { double v = PyFloat_AsDouble (pyvalue); snprintf (string, sizeof (string), "%f", v); value = string; } return strdup (value); } static PyObject * Connection_addPrinterOptionDefault (Connection *self, PyObject *args) { PyObject *nameobj; char *name; PyObject *optionobj; char *option; PyObject *pyvalue; const char suffix[] = "-default"; char *opt; ipp_t *request, *answer; int i; size_t optionlen; if (!PyArg_ParseTuple (args, "OOO", &nameobj, &optionobj, &pyvalue)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&option, optionobj) == NULL) { free (name); return NULL; } optionlen = strlen (option); opt = malloc (optionlen + sizeof (suffix) + 1); memcpy (opt, option, optionlen); strcpy (opt + optionlen, suffix); request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { if (!PyUnicode_Check (pyvalue) && !PyBytes_Check (pyvalue) && PySequence_Check (pyvalue)) { ipp_attribute_t *attr; int len = PySequence_Size (pyvalue); int j; attr = ippAddStrings (request, IPP_TAG_PRINTER, IPP_TAG_NAME, opt, len, NULL, NULL); for (j = 0; j < len; j++) { PyObject *each = PySequence_GetItem (pyvalue, j); ippSetString(request, &attr, j, PyObject_to_string (each)); } } else ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_NAME, opt, NULL, PyObject_to_string (pyvalue)); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); // Perhaps it's a class, not a printer. request = add_modify_class_request (name); } else break; } free (name); free (option); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_deletePrinterOptionDefault (Connection *self, PyObject *args) { PyObject *nameobj; char *name; PyObject *optionobj; char *option; const char suffix[] = "-default"; char *opt; ipp_t *request, *answer; int i; size_t optionlen; if (!PyArg_ParseTuple (args, "OO", &nameobj, &optionobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (UTF8_from_PyObj (&option, optionobj) == NULL) { free (name); return NULL; } optionlen = strlen (option); opt = malloc (optionlen + sizeof (suffix) + 1); memcpy (opt, option, optionlen); strcpy (opt + optionlen, suffix); request = add_modify_printer_request (name); for (i = 0; i < 2; i++) { ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_DELETEATTR, opt, NULL, NULL); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); // Perhaps it's a class, not a printer. request = add_modify_class_request (name); } else break; } free (name); free (option); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_deletePrinter (Connection *self, PyObject *args, PyObject *kwds) { return do_printer_request (self, args, kwds, CUPS_DELETE_PRINTER); } static PyObject * Connection_getPrinterAttributes (Connection *self, PyObject *args, PyObject *kwds) { PyObject *ret; PyObject *nameobj = NULL; char *name; PyObject *uriobj = NULL; char *uri; PyObject *requested_attrs = NULL; char **attrs = NULL; /* initialised to calm compiler */ size_t n_attrs = 0; /* initialised to calm compiler */ ipp_t *request, *answer; ipp_attribute_t *attr; char consuri[HTTP_MAX_URI]; int i; static char *kwlist[] = { "name", "uri", "requested_attributes", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|OOO", kwlist, &nameobj, &uriobj, &requested_attrs)) return NULL; if (nameobj && uriobj) { PyErr_SetString (PyExc_RuntimeError, "name or uri must be specified but not both"); return NULL; } if (nameobj) { if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; } else if (uriobj) { if (UTF8_from_PyObj (&uri, uriobj) == NULL) return NULL; } else { PyErr_SetString (PyExc_RuntimeError, "name or uri must be specified"); return NULL; } if (requested_attrs) { if (get_requested_attrs (requested_attrs, &n_attrs, &attrs) == -1) { if (nameobj) free (name); else if (uriobj) free (uri); return NULL; } } debugprintf ("-> Connection_getPrinterAttributes(%s)\n", nameobj ? name : uri); if (nameobj) { construct_uri (consuri, sizeof (consuri), "ipp://localhost/printers/", name); uri = consuri; } for (i = 0; i < 2; i++) { request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); if (requested_attrs) ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", n_attrs, NULL, (const char **) attrs); debugprintf ("trying request with uri %s\n", uri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); if (uriobj) break; // Perhaps it's a class, not a printer. construct_uri (consuri, sizeof (consuri), "ipp://localhost/classes/", name); } else break; } if (nameobj) free (name); if (uriobj) free (uri); if (requested_attrs) free_requested_attrs (n_attrs, attrs); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getPrinterAttributes() (error)\n"); return NULL; } ret = PyDict_New (); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { while (attr && ippGetGroupTag (attr) != IPP_TAG_PRINTER) attr = ippNextAttribute (answer); if (!attr) break; for (; attr && ippGetGroupTag (attr) == IPP_TAG_PRINTER; attr = ippNextAttribute (answer)) { size_t namelen = strlen (ippGetName (attr)); int is_list = ippGetCount (attr) > 1; debugprintf ("Attribute: %s\n", ippGetName (attr)); // job-sheets-default is special, since it is always two values. // Make it a tuple. if (!strcmp (ippGetName (attr), "job-sheets-default") && ippGetValueTag (attr) == IPP_TAG_NAME) { PyObject *startobj, *endobj, *tuple; const char *start, *end; start = ippGetString (attr, 0, NULL); if (ippGetCount (attr) >= 2) end = ippGetString (attr, 1, NULL); else end = ""; startobj = PyObj_from_UTF8 (start); endobj = PyObj_from_UTF8 (end); tuple = Py_BuildValue ("(OO)", startobj, endobj); Py_DECREF (startobj); Py_DECREF (endobj); PyDict_SetItemString (ret, "job-sheets-default", tuple); Py_DECREF (tuple); continue; } // Check for '-supported' suffix. Any xxx-supported attribute // that is a text type must be a list. // // Also check for attributes that are known to allow multiple // string values, and make them lists. if (!is_list && namelen > 10) { const char *multivalue_options[] = { "notify-events-default", "requesting-user-name-allowed", "requesting-user-name-denied", "printer-state-reasons", "marker-colors", "marker-names", "marker-types", "marker-levels", "member-names", NULL }; switch (ippGetValueTag (attr)) { case IPP_TAG_NAME: case IPP_TAG_TEXT: case IPP_TAG_KEYWORD: case IPP_TAG_URI: case IPP_TAG_CHARSET: case IPP_TAG_MIMETYPE: case IPP_TAG_LANGUAGE: case IPP_TAG_ENUM: case IPP_TAG_INTEGER: case IPP_TAG_RESOLUTION: is_list = !strcmp (ippGetName (attr) + namelen - 10, "-supported"); if (!is_list) { const char **opt; for (opt = multivalue_options; !is_list && *opt; opt++) is_list = !strcmp (ippGetName (attr), *opt); } default: break; } } if (is_list) { PyObject *list = PyList_from_attr_values (attr); PyDict_SetItemString (ret, ippGetName (attr), list); Py_DECREF (list); } else { PyObject *val = PyObject_from_attr_value (attr, i); PyDict_SetItemString (ret, ippGetName (attr), val); } } if (!attr) break; } debugprintf ("<- Connection_getPrinterAttributes() = dict\n"); return ret; } static PyObject * Connection_addPrinterToClass (Connection *self, PyObject *args) { PyObject *printernameobj; char *printername; PyObject *classnameobj; char *classname; char classuri[HTTP_MAX_URI]; char printeruri[HTTP_MAX_URI]; ipp_t *request, *answer; if (!PyArg_ParseTuple (args, "OO", &printernameobj, &classnameobj)) return NULL; if (UTF8_from_PyObj (&printername, printernameobj) == NULL) return NULL; if (UTF8_from_PyObj (&classname, classnameobj) == NULL) { free (printername); return NULL; } // Does the class exist, and is the printer already in it? request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES); construct_uri (classuri, sizeof (classuri), "ipp://localhost/classes/", classname); free (classname); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, classuri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (answer) { ipp_attribute_t *printers; printers = ippFindAttribute (answer, "member-names", IPP_TAG_NAME); if (printers) { int i; for (i = 0; i < ippGetCount (printers); i++) { if (!strcasecmp (ippGetString (printers, i, NULL), printername)) { ippDelete (answer); PyErr_SetString (PyExc_RuntimeError, "Printer already in class"); free (printername); return NULL; } } } } request = ippNewRequest (CUPS_ADD_CLASS); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, classuri); construct_uri (printeruri, sizeof (printeruri), "ipp://localhost/printers/", printername); free (printername); if (answer) { ipp_attribute_t *printers; printers = ippFindAttribute (answer, "member-uris", IPP_TAG_URI); if (printers) { ipp_attribute_t *attr; int i; attr = ippAddStrings (request, IPP_TAG_PRINTER, IPP_TAG_URI, "member-uris", ippGetCount (printers) + 1, NULL, NULL); for (i = 0; i < ippGetCount (printers); i++) ippSetString(request, &attr, i, strdup (ippGetString (printers, i, NULL))); ippSetString(request, &attr, ippGetCount (printers), strdup (printeruri)); } ippDelete (answer); } // If the class didn't exist, create a new one. if (!ippFindAttribute (request, "member-uris", IPP_TAG_URI)) ippAddString (request, IPP_TAG_PRINTER, IPP_TAG_URI, "member-uris", NULL, printeruri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_deletePrinterFromClass (Connection *self, PyObject *args) { const char *requested_attrs[] = { "member-names", "member-uris" }; PyObject *printernameobj; char *printername; PyObject *classnameobj; char *classname; char classuri[HTTP_MAX_URI]; ipp_t *request, *answer; ipp_attribute_t *printers; int i; if (!PyArg_ParseTuple (args, "OO", &printernameobj, &classnameobj)) return NULL; if (UTF8_from_PyObj (&printername, printernameobj) == NULL) return NULL; if (UTF8_from_PyObj (&classname, classnameobj) == NULL) { free (printername); return NULL; } // Does the class exist, and is the printer in it? request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES); construct_uri (classuri, sizeof (classuri), "ipp://localhost/classes/", classname); free (classname); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, classuri); ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", sizeof(requested_attrs) / sizeof(requested_attrs[0]), NULL, requested_attrs); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer) { set_ipp_error (cupsLastError (), cupsLastErrorString ()); free (printername); return NULL; } printers = ippFindAttribute (answer, "member-names", IPP_TAG_NAME); for (i = 0; printers && i < ippGetCount (printers); i++) if (!strcasecmp (ippGetString (printers, i, NULL), printername)) break; free (printername); if (!printers || i == ippGetCount (printers)) { ippDelete (answer); PyErr_SetString (PyExc_RuntimeError, "Printer not in class"); return NULL; } printers = ippFindAttribute (answer, "member-uris", IPP_TAG_URI); if (!printers || i >= ippGetCount (printers)) { ippDelete (answer); PyErr_SetString (PyExc_RuntimeError, "No member URIs returned"); return NULL; } request = ippNewRequest (CUPS_ADD_CLASS); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, classuri); // Only printer in class? Delete the class. if (ippGetCount (printers) == 1) ippSetOperation (request, CUPS_DELETE_CLASS); else { // Trim the printer from the list. ipp_attribute_t *newlist; int j; newlist = ippAddStrings (request, IPP_TAG_PRINTER, IPP_TAG_URI, "member-uris", ippGetCount (printers) - 1, NULL, NULL); for (j = 0; j < i; j++) ippSetString(request, &newlist, j, strdup (ippGetString (printers, j, NULL))); for (j = i; j < ippGetCount(newlist); j++) ippSetString(request, &newlist, j, strdup (ippGetString (printers, j+1, NULL))); } ippDelete (answer); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (PyErr_Occurred ()) { if (answer) ippDelete (answer); return NULL; } if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_deleteClass (Connection *self, PyObject *args) { PyObject *classnameobj; char *classname; char classuri[HTTP_MAX_URI]; ipp_t *request, *answer; if (!PyArg_ParseTuple (args, "O", &classnameobj)) return NULL; if (UTF8_from_PyObj (&classname, classnameobj) == NULL) return NULL; request = ippNewRequest (CUPS_DELETE_CLASS); construct_uri (classuri, sizeof (classuri), "ipp://localhost/classes/", classname); free (classname); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, classuri); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/admin/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } ippDelete (answer); Py_RETURN_NONE; } static PyObject * Connection_enablePrinter (Connection *self, PyObject *args, PyObject *kwds) { return do_printer_request (self, args, kwds, IPP_RESUME_PRINTER); } static PyObject * Connection_disablePrinter (Connection *self, PyObject *args, PyObject *kwds) { return do_printer_request (self, args, kwds, IPP_PAUSE_PRINTER); } static PyObject * Connection_acceptJobs (Connection *self, PyObject *args, PyObject *kwds) { return do_printer_request (self, args, kwds, CUPS_ACCEPT_JOBS); } static PyObject * Connection_rejectJobs (Connection *self, PyObject *args, PyObject *kwds) { return do_printer_request (self, args, kwds, CUPS_REJECT_JOBS); } static PyObject * Connection_getDefault (Connection *self, PyObject *args) { const char *def; PyObject *ret; debugprintf ("-> Connection_getDefault()\n"); Connection_begin_allow_threads (self); def = cupsGetDefault2 (self->http); Connection_end_allow_threads (self); if (def == NULL) { debugprintf ("<- Connection_getDefault() = None\n"); Py_RETURN_NONE; } else { debugprintf ("<- Connection_getDefault() = \"%s\"\n", def); ret = PyUnicode_FromString (def); } return ret; } static PyObject * Connection_setDefault (Connection *self, PyObject *args, PyObject *kwds) { return do_printer_request (self, args, kwds, CUPS_SET_DEFAULT); } static PyObject * Connection_getPPD (Connection *self, PyObject *args) { PyObject *ret; PyObject *printerobj; char *printer; const char *ppdfile; if (!PyArg_ParseTuple (args, "O", &printerobj)) return NULL; if (UTF8_from_PyObj (&printer, printerobj) == NULL) return NULL; debugprintf ("-> Connection_getPPD()\n"); Connection_begin_allow_threads (self); ppdfile = cupsGetPPD2 (self->http, printer); Connection_end_allow_threads (self); free (printer); if (!ppdfile) { ipp_status_t err = cupsLastError (); if (err) set_ipp_error (err, cupsLastErrorString ()); else PyErr_SetString (PyExc_RuntimeError, "cupsGetPPD2 failed"); debugprintf ("<- Connection_getPPD() (error)\n"); return NULL; } ret = PyUnicode_FromString (ppdfile); debugprintf ("<- Connection_getPPD() = %s\n", ppdfile); return ret; } static PyObject * Connection_getPPD3 (Connection *self, PyObject *args, PyObject *kwds) { PyObject *ret, *obj; PyObject *printerobj; PyObject *fmodtime = NULL; char *printer; time_t modtime; PyObject *filenameobj = NULL; char *filename = NULL; char fname[PATH_MAX]; http_status_t status; static char *kwlist[] = { "name", "modtime", "filename", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|OO", kwlist, &printerobj, &fmodtime, &filenameobj)) return NULL; if (UTF8_from_PyObj (&printer, printerobj) == NULL) return NULL; if (fmodtime) { double d = PyFloat_AsDouble (fmodtime); if (PyErr_Occurred()) { free (printer); return NULL; } modtime = (time_t) d; } else modtime = 0; if (filenameobj) if (UTF8_from_PyObj (&filename, filenameobj) == NULL) { free (printer); return NULL; } if (filename) { if (strlen (filename) > sizeof (fname)) { PyErr_SetString (PyExc_TypeError, "overlength filename"); free (printer); free (filename); return NULL; } strcpy (fname, filename); } else fname[0] = '\0'; debugprintf ("-> Connection_getPPD3()\n"); Connection_begin_allow_threads (self); status = cupsGetPPD3 (self->http, printer, &modtime, fname, sizeof (fname)); Connection_end_allow_threads (self); free (printer); free (filename); ret = PyTuple_New (3); if (!ret) return NULL; obj = PyLong_FromLong ((long) status); if (!obj) { Py_DECREF (ret); return NULL; } PyTuple_SetItem (ret, 0, obj); obj = PyFloat_FromDouble ((double) modtime); if (!obj) { Py_DECREF (ret); return NULL; } PyTuple_SetItem (ret, 1, obj); obj = PyUnicode_FromString (fname); if (!obj) { Py_DECREF (ret); return NULL; } PyTuple_SetItem (ret, 2, obj); debugprintf ("<- Connection_getPPD3() = (%d,%ld,%s)\n", status, modtime, fname); return ret; } static PyObject * Connection_printTestPage (Connection *self, PyObject *args, PyObject *kwds) { PyObject *printerobj; char *printer; PyObject *fileobj = NULL; char *file = NULL; PyObject *titleobj = NULL; char *title = NULL; PyObject *formatobj = NULL; char *format = NULL; PyObject *userobj = NULL; char *user = NULL; const char *datadir; char filename[PATH_MAX]; char uri[HTTP_MAX_URI]; ipp_t *request, *answer; ipp_attribute_t *attr; char *resource; int jobid = 0; int i; static char *kwlist[] = { "name", "file", "title", "format", "user", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|OOOO", kwlist, &printerobj, &fileobj, &titleobj, &formatobj, &userobj)) return NULL; if (UTF8_from_PyObj (&printer, printerobj) == NULL) return NULL; if ((fileobj && UTF8_from_PyObj (&file, fileobj) == NULL) || (titleobj && UTF8_from_PyObj (&title, titleobj) == NULL) || (formatobj && UTF8_from_PyObj (&format, formatobj) == NULL) || (userobj && UTF8_from_PyObj (&user, userobj) == NULL)) { free (printer); free (file); free (title); free (format); free (user); return NULL; } if (!fileobj) { const char *testprint[] = { "%s/data/testprint", "%s/data/testprint.ps", NULL }; if ((datadir = getenv ("CUPS_DATADIR")) != NULL) { const char **pattern; for (pattern = testprint; *pattern != NULL; pattern++) { snprintf (filename, sizeof (filename), *pattern, datadir); if (access (filename, R_OK) == 0) break; } } else { const char *const dirs[] = { "/usr/share/cups", "/usr/local/share/cups", NULL }; int found = 0; int i; for (i = 0; (datadir = dirs[i]) != NULL; i++) { const char **pattern; for (pattern = testprint; *pattern != NULL; pattern++) { snprintf (filename, sizeof (filename), *pattern, datadir); if (access (filename, R_OK) == 0) { found = 1; break; } } if (found) break; } if (datadir == NULL) /* We haven't found the testprint.ps file, so just pick a path * and try it. This will certainly fail with * client-error-not-found, but we'll let that happen rather * than raising an exception so as to be consistent with the * case where CUPS_DATADIR is set and we trust it. */ snprintf (filename, sizeof (filename), testprint[0], dirs[0]); } file = filename; } if (!titleobj) title = "Test Page"; if (!userobj) user = (char *) cupsUser(); construct_uri (uri, sizeof (uri), "ipp://localhost/printers/", printer); resource = uri + strlen ("ipp://localhost"); for (i = 0; i < 2; i++) { request = ippNewRequest (IPP_PRINT_JOB); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, user); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL, title); if (format) ippAddString (request, IPP_TAG_JOB, IPP_TAG_MIMETYPE, "document-format", NULL, format); Connection_begin_allow_threads (self); answer = cupsDoFileRequest (self->http, request, resource, file); Connection_end_allow_threads (self); if (answer && ippGetStatusCode (answer) == IPP_NOT_POSSIBLE) { ippDelete (answer); answer = NULL; // Perhaps it's a class, not a printer. construct_uri (uri, sizeof (uri), "ipp://localhost/classes/", printer); } else break; } free (printer); if (fileobj) free (file); if (titleobj) free (title); if (formatobj) free (format); if (userobj) free (user); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); return NULL; } attr = ippFindAttribute (answer, "job-id", IPP_TAG_INTEGER); if (attr) jobid = ippGetInteger (attr, 0); ippDelete (answer); return Py_BuildValue ("i", jobid); } static PyObject * Connection_adminExportSamba (Connection *self, PyObject *args) { int ret; PyObject *nameobj; char *name; PyObject *serverobj; char *server; PyObject *userobj; char *user; PyObject *passwordobj; char *password; char ppdfile[1024]; FILE *tmpfile(void); FILE *tf; char str[80]; if (!PyArg_ParseTuple (args, "OOOO", &nameobj, &serverobj, &userobj, &passwordobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL || UTF8_from_PyObj (&server, serverobj) == NULL || UTF8_from_PyObj (&user, userobj) == NULL || UTF8_from_PyObj (&password, passwordobj) == NULL) { free (name); free (server); free (user); free (password); PyErr_SetString(PyExc_RuntimeError, "name, samba_server, samba_username, samba_password " "must be specified"); return NULL; } if (!cupsAdminCreateWindowsPPD(self->http, name, ppdfile, sizeof(ppdfile))) { PyErr_SetString(PyExc_RuntimeError, "No PPD file found for the printer"); return NULL; } debugprintf ("-> Connection_adminExportSamba()\n"); tf = tmpfile(); Connection_begin_allow_threads (self); ret = cupsAdminExportSamba(name, ppdfile, server, user, password, tf); Connection_end_allow_threads (self); free (name); free (server); free (user); free (password); unlink (ppdfile); if (!ret) { rewind(tf); // Read logfile line by line to get Exit status message on the last line. while (fgets (str, sizeof(str), tf) != NULL) { } fclose (tf); if (str[strlen(str) -1] == '\n') { str[strlen(str) -1] = '\0'; } PyErr_SetString (PyExc_RuntimeError, str); debugprintf ("<- Connection_adminExportSamba() EXCEPTION\n"); return NULL; } fclose (tf); debugprintf ("<- Connection_adminExportSamba()\n"); Py_RETURN_NONE; } static PyObject * Connection_adminGetServerSettings (Connection *self) { PyObject *ret = PyDict_New (); int num_settings, i; cups_option_t *settings; debugprintf ("-> Connection_adminGetServerSettings()\n"); Connection_begin_allow_threads (self); cupsAdminGetServerSettings (self->http, &num_settings, &settings); Connection_end_allow_threads (self); for (i = 0; i < num_settings; i++) { PyObject *string = PyUnicode_FromString (settings[i].value); PyDict_SetItemString (ret, settings[i].name, string); Py_DECREF (string); } cupsFreeOptions (num_settings, settings); debugprintf ("<- Connection_adminGetServerSettings()\n"); return ret; } static PyObject * Connection_adminSetServerSettings (Connection *self, PyObject *args) { PyObject *dict, *key, *val; int ret; int num_settings = 0; DICT_POS_TYPE pos = 0; cups_option_t *settings = NULL; if (!PyArg_ParseTuple (args, "O", &dict)) return NULL; if (!PyDict_Check (dict)) { PyErr_SetString (PyExc_TypeError, "Expecting dict"); return NULL; } debugprintf ("-> Connection_adminSetServerSettings()\n"); while (PyDict_Next (dict, &pos, &key, &val)) { char *name, *value; if ((!PyUnicode_Check (key) && !PyBytes_Check (key)) || (!PyUnicode_Check (val) && !PyBytes_Check (val))) { cupsFreeOptions (num_settings, settings); PyErr_SetString (PyExc_TypeError, "Keys and values must be strings"); debugprintf ("<- Connection_adminSetServerSettings() EXCEPTION\n"); return NULL; } UTF8_from_PyObj (&name, key); UTF8_from_PyObj (&value, val); debugprintf ("%s: %s\n", name, value); num_settings = cupsAddOption (name, value, num_settings, &settings); free (name); free (value); } debugprintf ("num_settings=%d, settings=%p\n", num_settings, settings); Connection_begin_allow_threads (self); ret = cupsAdminSetServerSettings (self->http, num_settings, settings); Connection_end_allow_threads (self); if (!ret) { cupsFreeOptions (num_settings, settings); PyErr_SetString (PyExc_RuntimeError, "Failed to set settings"); debugprintf ("<- Connection_adminSetServerSettings() EXCEPTION\n"); return NULL; } cupsFreeOptions (num_settings, settings); debugprintf ("<- Connection_adminSetServerSettings()\n"); Py_RETURN_NONE; } static PyObject * Connection_getSubscriptions (Connection *self, PyObject *args, PyObject *kwds) { PyObject *uriobj; char *uri; PyObject *my_subscriptions = Py_False; int job_id = -1; ipp_t *request, *answer; ipp_attribute_t *attr; PyObject *result, *subscription; static char *kwlist[] = { "uri", "my_subscriptions", "job_id", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|Oi", kwlist, &uriobj, &my_subscriptions, &job_id)) return NULL; if (UTF8_from_PyObj (&uri, uriobj) == NULL) return NULL; if (my_subscriptions && !PyBool_Check (my_subscriptions)) { PyErr_SetString (PyExc_TypeError, "my_subscriptions must be a bool"); return NULL; } debugprintf ("-> Connection_getSubscriptions()\n"); request = ippNewRequest (IPP_GET_SUBSCRIPTIONS); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri); free (uri); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); if (my_subscriptions == Py_True) ippAddBoolean (request, IPP_TAG_OPERATION, "my-subscriptions", 1); if (job_id != -1) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", job_id); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getSubscriptions() EXCEPTION\n"); return NULL; } result = PyList_New (0); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) if (ippGetGroupTag (attr) == IPP_TAG_SUBSCRIPTION) break; subscription = NULL; for (; attr; attr = ippNextAttribute (answer)) { PyObject *obj; if (ippGetGroupTag (attr) == IPP_TAG_ZERO) { // End of subscription. if (subscription) { PyList_Append (result, subscription); Py_DECREF (subscription); } subscription = NULL; continue; } if (ippGetCount (attr) > 1 || !strcmp (ippGetName (attr), "notify-events")) obj = PyList_from_attr_values (attr); else obj = PyObject_from_attr_value (attr, 0); if (!obj) // Can't represent this. continue; if (!subscription) subscription = PyDict_New (); PyDict_SetItemString (subscription, ippGetName (attr), obj); Py_DECREF (obj); } if (subscription) { PyList_Append (result, subscription); Py_DECREF (subscription); } ippDelete (answer); debugprintf ("<- Connection_getSubscriptions()\n"); return result; } static PyObject * Connection_createSubscription (Connection *self, PyObject *args, PyObject *kwds) { PyObject *resource_uriobj; char *resource_uri; PyObject *events = NULL; int job_id = -1, lease_duration = -1, time_interval = -1; PyObject *recipient_uriobj = NULL, *user_dataobj = NULL; char *recipient_uri = NULL, *user_data = NULL; ipp_t *request, *answer; int i, n = 0; char *tmp; ipp_attribute_t *attr; static char *kwlist[] = { "uri", "events", "job_id", "recipient_uri", "lease_duration", "time_interval", "user_data", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|OiOiiO", kwlist, &resource_uriobj, &events, &job_id, &recipient_uriobj, &lease_duration, &time_interval, &user_dataobj)) return NULL; if (UTF8_from_PyObj (&resource_uri, resource_uriobj) == NULL) return NULL; if (recipient_uriobj && UTF8_from_PyObj (&recipient_uri, recipient_uriobj) == NULL) { free (resource_uri); return NULL; } if (user_dataobj && UTF8_from_PyObj (&user_data, user_dataobj) == NULL) { free (resource_uri); if (recipient_uriobj) free (recipient_uri); return NULL; } if (events) { if (!PyList_Check (events)) { PyErr_SetString (PyExc_TypeError, "events must be a list"); return NULL; } n = PyList_Size (events); for (i = 0; i < n; i++) { PyObject *event = PyList_GetItem (events, i); if (!PyUnicode_Check (event) && !PyBytes_Check (event)) { PyErr_SetString (PyExc_TypeError, "events must be a list of strings"); return NULL; } } } debugprintf ("-> Connection_createSubscription(%s)\n", resource_uri); request = ippNewRequest (IPP_CREATE_PRINTER_SUBSCRIPTION); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, resource_uri); ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-pull-method", NULL, "ippget"); ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_CHARSET, "notify-charset", NULL, "utf-8"); ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); if (recipient_uriobj) { ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI, "notify-recipient-uri", NULL, recipient_uri); free (recipient_uri); } if (user_dataobj) { ippAddString (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_STRING, "notify-user-data", NULL, user_data); free (user_data); } if (events) { attr = ippAddStrings (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD, "notify-events", n, NULL, NULL); for (i = 0; i < n; i++) { PyObject *event = PyList_GetItem (events, i); ippSetString(request, &attr, i, UTF8_from_PyObj (&tmp, event)); free(tmp); } } if (lease_duration != -1) ippAddInteger (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER, "notify-lease-duration", lease_duration); if (time_interval != -1) ippAddInteger (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER, "notify-time-interval", time_interval); if (job_id != -1) ippAddInteger (request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER, "notify-job-id", job_id); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_createSubscription() EXCEPTION\n"); return NULL; } i = -1; for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) { if (ippGetGroupTag (attr) == IPP_TAG_SUBSCRIPTION) { if (ippGetValueTag (attr) == IPP_TAG_INTEGER && !strcmp (ippGetName (attr), "notify-subscription-id")) i = ippGetInteger (attr, 0); else if (ippGetValueTag (attr) == IPP_TAG_ENUM && !strcmp (ippGetName (attr), "notify-status-code")) debugprintf ("notify-status-code = %d\n", ippGetInteger (attr, 0)); } } ippDelete (answer); debugprintf ("<- Connection_createSubscription() = %d\n", i); return PyLong_FromLong (i); } static PyObject * Connection_getNotifications (Connection *self, PyObject *args, PyObject *kwds) { PyObject *subscription_ids, *sequence_numbers = NULL; ipp_t *request, *answer; int i, num_ids, num_seqs = 0; ipp_attribute_t *attr; PyObject *result, *events, *event; static char *kwlist[] = { "subscription_ids", "sequence_numbers", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|O", kwlist, &subscription_ids, &sequence_numbers)) return NULL; if (!PyList_Check (subscription_ids)) { PyErr_SetString (PyExc_TypeError, "subscriptions_ids must be a list"); return NULL; } num_ids = PyList_Size (subscription_ids); for (i = 0; i < num_ids; i++) { PyObject *id = PyList_GetItem (subscription_ids, i); if (!PyLong_Check (id)) { PyErr_SetString (PyExc_TypeError, "subscription_ids must be a list " "of integers"); return NULL; } } if (sequence_numbers) { if (!PyList_Check (sequence_numbers)) { PyErr_SetString (PyExc_TypeError, "sequence_numbers must be a list"); return NULL; } num_seqs = PyList_Size (sequence_numbers); for (i = 0; i < num_seqs; i++) { PyObject *id = PyList_GetItem (sequence_numbers, i); if (!PyLong_Check (id)) { PyErr_SetString (PyExc_TypeError, "sequence_numbers must be a list " "of integers"); return NULL; } } } debugprintf ("-> Connection_getNotifications()\n"); request = ippNewRequest (IPP_GET_NOTIFICATIONS); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); attr = ippAddIntegers (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-ids", num_ids, NULL); for (i = 0; i < num_ids; i++) { PyObject *id = PyList_GetItem (subscription_ids, i); ippSetInteger (request, &attr, i, PyLong_AsLong (id)); } if (sequence_numbers) { attr = ippAddIntegers (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-sequence-numbers", num_seqs, NULL); for (i = 0; i < num_seqs; i++) { PyObject *num = PyList_GetItem (sequence_numbers, i); ippSetInteger (request, &attr, i, PyLong_AsLong (num)); } } Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_getNotifications() EXCEPTION\n"); return NULL; } result = PyDict_New (); // Result-wide attributes. attr = ippFindAttribute (answer, "notify-get-interval", IPP_TAG_INTEGER); if (attr) { PyObject *val = PyLong_FromLong (ippGetInteger (attr, 0)); PyDict_SetItemString (result, ippGetName (attr), val); Py_DECREF (val); } attr = ippFindAttribute (answer, "printer-up-time", IPP_TAG_INTEGER); if (attr) { PyObject *val = PyLong_FromLong (ippGetInteger (attr, 0)); PyDict_SetItemString (result, ippGetName (attr), val); Py_DECREF (val); } events = PyList_New (0); for (attr = ippFirstAttribute (answer); attr; attr = ippNextAttribute (answer)) if (ippGetGroupTag (attr) == IPP_TAG_EVENT_NOTIFICATION) break; event = NULL; for (; attr; attr = ippNextAttribute (answer)) { PyObject *obj; if (ippGetGroupTag (attr) == IPP_TAG_ZERO) { // End of event notification. if (event) { PyList_Append (events, event); Py_DECREF (event); } event = NULL; continue; } if (ippGetCount (attr) > 1 || !strcmp (ippGetName (attr), "notify-events") || !strcmp (ippGetName (attr), "printer-state-reasons") || !strcmp (ippGetName (attr), "job-printer-state-reasons")) obj = PyList_from_attr_values (attr); else obj = PyObject_from_attr_value (attr, 0); if (!obj) // Can't represent this. continue; if (!event) event = PyDict_New (); PyDict_SetItemString (event, ippGetName (attr), obj); Py_DECREF (obj); } if (event) { PyList_Append (events, event); Py_DECREF (event); } ippDelete (answer); PyDict_SetItemString (result, "events", events); Py_DECREF (events); debugprintf ("<- Connection_getNotifications()\n"); return result; } static PyObject * Connection_renewSubscription (Connection *self, PyObject *args, PyObject *kwds) { int id; int lease_duration = -1; ipp_t *request, *answer; static char *kwlist[] = { "id", "lease_duration", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "i|i", kwlist, &id, &lease_duration)) return NULL; debugprintf ("-> Connection_renewSubscription()\n"); request = ippNewRequest (IPP_RENEW_SUBSCRIPTION); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-id", id); if (lease_duration != -1) ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-lease-duration", lease_duration); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_renewSubscription() EXCEPTION\n"); return NULL; } ippDelete (answer); debugprintf ("<- Connection_renewSubscription()\n"); Py_RETURN_NONE; } static PyObject * Connection_cancelSubscription (Connection *self, PyObject *args) { int id; ipp_t *request, *answer; if (!PyArg_ParseTuple (args, "i", &id)) return NULL; debugprintf ("-> Connection_cancelSubscription()\n"); request = ippNewRequest (IPP_CANCEL_SUBSCRIPTION); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "/"); ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser ()); ippAddInteger (request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "notify-subscription-id", id); Connection_begin_allow_threads (self); answer = cupsDoRequest (self->http, request, "/"); Connection_end_allow_threads (self); if (!answer || ippGetStatusCode (answer) > IPP_OK_CONFLICT) { set_ipp_error (answer ? ippGetStatusCode (answer) : cupsLastError (), answer ? NULL : cupsLastErrorString ()); if (answer) ippDelete (answer); debugprintf ("<- Connection_cancelSubscription() EXCEPTION\n"); return NULL; } ippDelete (answer); debugprintf ("<- Connection_cancelSubscription()\n"); Py_RETURN_NONE; } static PyObject * Connection_printFile (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "printer", "filename", "title", "options", NULL }; PyObject *printer_obj; char *printer; PyObject *filename_obj; char *filename; PyObject *title_obj; char *title; PyObject *options_obj, *key, *val; int num_settings = 0; DICT_POS_TYPE pos = 0; cups_option_t *settings = NULL; int jobid; if (!PyArg_ParseTupleAndKeywords (args, kwds, "OOOO", kwlist, &printer_obj, &filename_obj, &title_obj, &options_obj)) return NULL; if (UTF8_from_PyObj (&printer, printer_obj) == NULL) return NULL; if (UTF8_from_PyObj (&filename, filename_obj) == NULL) { free (printer); return NULL; } if (UTF8_from_PyObj (&title, title_obj) == NULL) { free (filename); free (printer); return NULL; } if (!PyDict_Check (options_obj)) { free (title); free (filename); free (printer); PyErr_SetString (PyExc_TypeError, "options must be a dict"); return NULL; } while (PyDict_Next (options_obj, &pos, &key, &val)) { char *name, *value; if ((!PyUnicode_Check (key) && !PyBytes_Check (key)) || (!PyUnicode_Check (val) && !PyBytes_Check (val))) { cupsFreeOptions (num_settings, settings); free (title); free (filename); free (printer); PyErr_SetString (PyExc_TypeError, "Keys and values must be strings"); return NULL; } num_settings = cupsAddOption (UTF8_from_PyObj (&name, key), UTF8_from_PyObj (&value, val), num_settings, &settings); free (name); free (value); } Connection_begin_allow_threads (self); jobid = cupsPrintFile2 (self->http, printer, filename, title, num_settings, settings); Connection_end_allow_threads (self); if (jobid == 0) { cupsFreeOptions (num_settings, settings); free (title); free (filename); free (printer); set_ipp_error (cupsLastError (), cupsLastErrorString ()); return NULL; } cupsFreeOptions (num_settings, settings); free (title); free (filename); free (printer); return PyLong_FromLong (jobid); } static void free_string_list (int num_string, char **strings) { int i; for (i = 0; i < num_string; ++i) { free (strings[i]); } free (strings); } static PyObject * Connection_printFiles (Connection *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "printer", "filenames", "title", "options", NULL }; PyObject *printer_obj; char *printer; PyObject *filenames_obj; int num_filenames; char **filenames; PyObject *title_obj; char *title; PyObject *options_obj, *key, *val; int num_settings = 0; DICT_POS_TYPE pos = 0; cups_option_t *settings = NULL; int jobid; if (!PyArg_ParseTupleAndKeywords (args, kwds, "OOOO", kwlist, &printer_obj, &filenames_obj, &title_obj, &options_obj)) return NULL; if (UTF8_from_PyObj (&printer, printer_obj) == NULL) return NULL; if (!PyList_Check (filenames_obj)) { free (printer); PyErr_SetString (PyExc_TypeError, "filenames must be a list"); return NULL; } num_filenames = PyList_Size (filenames_obj); if (num_filenames == 0) { free (printer); PyErr_SetString (PyExc_RuntimeError, "filenames list is empty"); return NULL; } filenames = malloc (num_filenames * sizeof(char*)); for (pos = 0; pos < num_filenames; ++pos) { PyObject *filename_obj = PyList_GetItem(filenames_obj, pos); if (UTF8_from_PyObj (&filenames[pos], filename_obj) == NULL) { free_string_list (pos, filenames); free (printer); return NULL; } } if (UTF8_from_PyObj (&title, title_obj) == NULL) { free_string_list (num_filenames, filenames); free (printer); return NULL; } if (!PyDict_Check (options_obj)) { free (title); free_string_list (num_filenames, filenames); free (printer); PyErr_SetString (PyExc_TypeError, "options must be a dict"); return NULL; } while (PyDict_Next (options_obj, &pos, &key, &val)) { char *name, *value; if ((!PyUnicode_Check (key) && !PyBytes_Check (key)) || (!PyUnicode_Check (val) && !PyBytes_Check (val))) { cupsFreeOptions (num_settings, settings); free (title); free_string_list (num_filenames, filenames); free (printer); PyErr_SetString (PyExc_TypeError, "Keys and values must be strings"); return NULL; } num_settings = cupsAddOption (UTF8_from_PyObj (&name, key), UTF8_from_PyObj (&value, val), num_settings, &settings); free (name); free (value); } Connection_begin_allow_threads (self); jobid = cupsPrintFiles2 (self->http, printer, num_filenames, (const char **) filenames, title, num_settings, settings); Connection_end_allow_threads (self); if (jobid == 0) { cupsFreeOptions (num_settings, settings); free (title); free_string_list (num_filenames, filenames); free (printer); set_ipp_error (cupsLastError (), cupsLastErrorString ()); return NULL; } cupsFreeOptions (num_settings, settings); free (title); free_string_list (num_filenames, filenames); free (printer); return PyLong_FromLong (jobid); } PyMethodDef Connection_methods[] = { { "getPrinters", (PyCFunction) Connection_getPrinters, METH_NOARGS, "getPrinters() -> dict\n\n" "@return: a dict, indexed by name, of dicts representing\n" "queues, indexed by attribute.\n" "@raise IPPError: IPP problem" }, { "getDests", (PyCFunction) Connection_getDests, METH_NOARGS, "getDests() -> dict\n\n" "@return: a dict representing available destinations. Each \n" "dictionary key is a pair of (queue, instance) strings, and the \n" "dictionary value is a L{cups.Dest} object. In addition to the \n" "available destinations, a special dictionary key (None,None) is \n" "provided for looking up the default destination; this destination \n" "will also be available under its own key.\n" "@raise IPPError: IPP problem" }, { "getClasses", (PyCFunction) Connection_getClasses, METH_NOARGS, "getClasses() -> dict\n\n" "@return: a dict, indexed by name, of objects representing\n" "classes. Each class object is either a string, in which case it\n" "is for the remote class; or a list, in which case it is a list of\n" "queue names.\n" "@raise IPPError: IPP problem" }, { "getPPDs", (PyCFunction) Connection_getPPDs, METH_VARARGS | METH_KEYWORDS, "getPPDs(limit=0, exclude_schemes=None, include_schemes=None, \n" "ppd_natural_language=None, ppd_device_id=None, ppd_make=None, \n" "ppd_make_and_model=None, ppd_model_number=-1, ppd_product=None, \n" "ppd_psversion=None, ppd_type=None) -> dict\n\n" "@type limit: integer\n" "@param limit: maximum number of PPDs to return\n" "@type exclude_schemes: string list\n" "@param exclude_schemes: list of PPD schemes to exclude\n" "@type include_schemes: string list\n" "@param include_schemes: list of PPD schemes to include\n" "@type ppd_natural_language: string\n" "@param ppd_natural_language: required language\n" "@type ppd_device_id: string\n" "@param ppd_device_id: IEEE 1284 Device ID to match against\n" "@type ppd_make: string\n" "@param ppd_make: required printer manufacturer\n" "@type ppd_make_and_model: string\n" "@param ppd_make_and_model: required make and model\n" "@type ppd_model_number: integer\n" "@param ppd_model_number: model number required (from cupsModelNumber \n" "in PPD file)\n" "@type ppd_product: string\n" "@param ppd_product: required PostScript product string (Product)\n" "@type ppd_psversion: string\n" "@param ppd_psversion: required PostScript version (PSVersion)\n" "@type ppd_type: string\n" "@param ppd_type: required type of PPD. Valid values are fax; pdf; \n" "postscript; raster; unknown.\n" "@return: a dict, indexed by PPD name, of dicts representing\n" "PPDs, indexed by attribute.\n" "@raise IPPError: IPP problem" }, { "getPPDs2", (PyCFunction) Connection_getPPDs2, METH_VARARGS | METH_KEYWORDS, "getPPDs2(limit=0, exclude_schemes=None, include_schemes=None, \n" "ppd_natural_language=None, ppd_device_id=None, ppd_make=None, \n" "ppd_make_and_model=None, ppd_model_number=-1, ppd_product=None, \n" "ppd_psversion=None, ppd_type=None) -> dict\n\n" "@type limit: integer\n" "@param limit: maximum number of PPDs to return\n" "@type exclude_schemes: string list\n" "@param exclude_schemes: list of PPD schemes to exclude\n" "@type include_schemes: string list\n" "@param include_schemes: list of PPD schemes to include\n" "@type ppd_natural_language: string\n" "@param ppd_natural_language: required language\n" "@type ppd_device_id: string\n" "@param ppd_device_id: IEEE 1284 Device ID to match against\n" "@type ppd_make: string\n" "@param ppd_make: required printer manufacturer\n" "@type ppd_make_and_model: string\n" "@param ppd_make_and_model: required make and model\n" "@type ppd_model_number: integer\n" "@param ppd_model_number: model number required (from cupsModelNumber \n" "in PPD file)\n" "@type ppd_product: string\n" "@param ppd_product: required PostScript product string (Product)\n" "@type ppd_psversion: string\n" "@param ppd_psversion: required PostScript version (PSVersion)\n" "@type ppd_type: string\n" "@param ppd_type: required type of PPD. Valid values are fax; pdf; \n" "postscript; raster; unknown.\n" "@return: a dict, indexed by PPD name, of dicts representing\n" "PPDs, indexed by attribute. All attribute values are lists.\n" "@raise IPPError: IPP problem" }, { "getServerPPD", (PyCFunction) Connection_getServerPPD, METH_VARARGS, "getServerPPD(ppd_name) -> string\n\n" "Fetches the named PPD and stores it in a temporary file.\n\n" "@type ppd_name: string\n" "@param ppd_name: the ppd-name of a PPD\n" "@return: temporary filename holding the PPD\n" "@raise RuntimeError: Not supported in libcups until 1.3\n" "@raise IPPError: IPP problem" }, { "getDocument", (PyCFunction) Connection_getDocument, METH_VARARGS, "getDocument(printer_uri, job_id, document_number) -> dict\n\n" "Fetches the job document and stores it in a temporary file.\n\n" "@type printer_uri: string\n" "@param printer_uri: the printer-uri for the printer\n" "@type job_id: integer\n" "@param job_id: the job ID\n" "@type document_number: integer\n" "@param document_number: the document number to retrieve\n" "@return: a dict with the following keys: " " 'file' (string), temporary filename holding the job document; " " 'document-format' (string), its MIME type. There may also be a " " 'document-name' key, in which case this is for the document name.\n" "@raise RuntimeError: Not supported in libcups until 1.4\n" "@raise IPPError: IPP problem" }, { "getDevices", (PyCFunction) Connection_getDevices, METH_VARARGS | METH_KEYWORDS, "getDevices(limit=0, exclude_schemes=None, include_schemes=None) -> dict\n\n" "@type limit: integer\n" "@param limit: maximum number of devices to return\n" "@type exclude_schemes: string list\n" "@param exclude_schemes: URI schemes to exclude\n" "@type include_schemes: string list\n" "@param include_schemes: URI schemes to include\n" "@return: a dict, indexed by device URI, of dicts representing\n" "devices, indexed by attribute.\n" "@raise IPPError: IPP problem" }, { "getJobs", (PyCFunction) Connection_getJobs, METH_VARARGS | METH_KEYWORDS, "getJobs(which_jobs='not-completed', my_jobs=False, limit=-1, first_job_id=-1, requested_attributes=None) -> dict\n" "Fetch a list of jobs.\n" "@type which_jobs: string\n" "@param which_jobs: which jobs to fetch; possible values: \n" "'completed', 'not-completed', 'all'\n" "@type my_jobs: boolean\n" "@param my_jobs: whether to restrict the returned jobs to those \n" "owned by the current CUPS user (as set by L{cups.setUser}).\n" "@return: a dict, indexed by job ID, of dicts representing job\n" "attributes.\n" "@type limit: integer\n" "@param limit: maximum number of jobs to return\n" "@type first_job_id: integer\n" "@param first_job_id: lowest job ID to return\n" "@type requested_attributes: string list\n" "@param requested_attributes: list of requested attribute names\n" "@raise IPPError: IPP problem" }, { "getJobAttributes", (PyCFunction) Connection_getJobAttributes, METH_VARARGS | METH_KEYWORDS, "getJobAttributes(jobid, requested_attributes=None) -> dict\n\n" "Fetch job attributes.\n" "@type jobid: integer\n" "@param jobid: job ID\n" "@type requested_attributes: string list\n" "@param requested_attributes: list of requested attribute names\n" "@return: a dict representing job attributes.\n" "@raise IPPError: IPP problem" }, { "cancelJob", (PyCFunction) Connection_cancelJob, METH_VARARGS | METH_KEYWORDS, "cancelJob(jobid, purge_job=False) -> None\n\n" "@type jobid: integer\n" "@param jobid: job ID to cancel\n" "@type purge_job: boolean\n" "@param purge_job: whether to remove data and control files\n" "@raise IPPError: IPP problem" }, { "cancelAllJobs", (PyCFunction) Connection_cancelAllJobs, METH_VARARGS | METH_KEYWORDS, "cancelAllJobs(name=None, uri=None, my_jobs=False, purge_jobs=True) -> None\n\n" "@type name: string\n" "@param name: queue name\n" "@type uri: string\n" "@param uri: printer URI\n" "@type my_jobs: boolean\n" "@param my_jobs: whether to restrict operation to jobs owned by \n" "the current CUPS user (as set by L{cups.setUser}).\n" "@type purge_jobs: boolean\n" "@param purge_jobs: whether to remove data and control files\n" "@raise IPPError: IPP problem" }, { "moveJob", (PyCFunction) Connection_moveJob, METH_VARARGS | METH_KEYWORDS, "moveJob(printer_uri=None, job_id=-1, job_printer_uri) -> None\n\n" "Move a job specified by printer_uri and jobid (only one need be given)\n" "to the printer specified by job_printer_uri.\n\n" "@type job_id: integer\n" "@param job_id: job ID to move\n" "@type printer_uri: string\n" "@param printer_uri: printer to move job(s) from\n" "@type job_printer_uri: string\n" "@param job_printer_uri: printer to move job(s) to\n" "@raise IPPError: IPP problem" }, { "authenticateJob", (PyCFunction) Connection_authenticateJob, METH_VARARGS, "authenticateJob(jobid, auth_info=None) -> None\n\n" "@type jobid: integer\n" "@param jobid: job ID to authenticate\n" "@type auth_info: optional string list\n" "@param auth_info: authentication details\n" "@raise IPPError: IPP problem" }, { "setJobHoldUntil", (PyCFunction) Connection_setJobHoldUntil, METH_VARARGS, "setJobHoldUntil(jobid, job_hold_until) -> None\n\n" "Specifies when a job should be printed.\n" "@type jobid: integer\n" "@param jobid: job ID to adjust\n" "@type job_hold_until: string\n" "@param job_hold_until: when to print the job; examples: 'hold', \n" "'immediate', 'restart', resume'\n" "@raise IPPError: IPP problem"}, { "restartJob", (PyCFunction) Connection_restartJob, METH_VARARGS | METH_KEYWORDS, "restartJob(job_id, job_hold_until=None) -> None\n\n" "Restart a job.\n\n" "@type job_id: integer\n" "@param job_id: job ID to restart\n" "@type job_hold_until: string\n" "@param job_hold_until: new job-hold-until value for job\n" "@raise IPPError: IPP problem" }, { "getFile", (PyCFunction) Connection_getFile, METH_VARARGS | METH_KEYWORDS, "getFile(resource, filename=None, fd=-1, file=None) -> None\n\n" "Fetch a CUPS server resource to a local file.\n\n" "This is for obtaining CUPS server configuration files and \n" "log files.\n\n" "@type resource: string\n" "@param resource: resource name\n" "@type filename: string\n" "@param filename: name of local file for storage\n" "@type fd: int\n" "@param fd: file descriptor of local file\n" "@type file: file\n" "@param file: Python file object for local file\n" "@raise HTTPError: HTTP problem" }, { "putFile", (PyCFunction) Connection_putFile, METH_VARARGS | METH_KEYWORDS, "putFile(resource, filename=None, fd=-1, file=None) -> None\n\n" "This is for uploading new configuration files for the CUPS \n" "server. Note: L{adminSetServerSettings} is a way of \n" "adjusting server settings without needing to parse the \n" "configuration file.\n" "@type resource: string\n" "@param resource: resource name\n" "@type filename: string\n" "@param filename: name of local file to upload\n" "@type fd: int\n" "@param fd: file descriptor of local file\n" "@type file: file\n" "@param file: Python file object for local file\n" "@raise HTTPError: HTTP problem"}, { "addPrinter", (PyCFunction) Connection_addPrinter, METH_VARARGS | METH_KEYWORDS, "addPrinter(name) -> None\n\n" "Add or adjust a print queue. Several parameters can select which\n" "PPD to use (filename, ppdname, and ppd) but only one may be\n" "given.\n\n" "@type filename: string\n" "@keyword filename: local filename of PPD file\n" "@type ppdname: string\n" "@keyword ppdname: filename from L{getPPDs}\n" "@type info: string\n" "@keyword info: human-readable information about the printer\n" "@type location: string\n" "@keyword location: human-readable printer location\n" "@type device: string\n" "@keyword device: device URI string\n" "@type ppd: L{cups.PPD} instance\n" "@keyword ppd: PPD object\n" "@raise IPPError: IPP problem" }, { "setPrinterDevice", (PyCFunction) Connection_setPrinterDevice, METH_VARARGS, "setPrinterDevice(name, device_uri) -> None\n\n" "Set the device URI for a printer.\n\n" "@type name: string\n" "@param name: queue name\n" "@type device_uri: string\n" "@param device_uri: device URI\n" "@raise IPPError: IPP problem" }, { "setPrinterInfo", (PyCFunction) Connection_setPrinterInfo, METH_VARARGS, "setPrinterInfo(name, info) -> None\n\n" "Set the human-readable information about a printer.\n\n" "@type name: string\n" "@param name: queue name\n" "@type info: string\n" "@param info: human-readable information about the printer\n" "@raise IPPError: IPP problem" }, { "setPrinterLocation", (PyCFunction) Connection_setPrinterLocation, METH_VARARGS, "setPrinterLocation(name, location) -> None\n\n" "Set the human-readable printer location\n\n" "@type name: string\n" "@param name: queue name\n" "@type location: string\n" "@param location: human-readable printer location\n" "@raise IPPError: IPP problem" }, { "setPrinterShared", (PyCFunction) Connection_setPrinterShared, METH_VARARGS, "setPrinterShared(name, shared) -> None\n\n" "Set whether a printer is shared with other people. This works \n" "with CUPS servers of at least version 1.2, by setting the \n" "printer-is-shared printer attribute.\n\n" "@type name: string\n" "@param name: queue name\n" "@type shared: boolean\n" "@param shared: whether printer should be shared\n" "@raise IPPError: IPP problem" }, { "setPrinterJobSheets", (PyCFunction) Connection_setPrinterJobSheets, METH_VARARGS, "setPrinterJobSheets(name, start, end) -> None\n\n" "Specifies job sheets for a printer.\n\n" "@type name: string\n" "@param name: queue name\n" "@type start: string\n" "@param start: name of a sheet to print before each job\n" "@type end: string\n" "@param end: name of a sheet to print after each job\n" "@raise IPPError: IPP problem" }, { "setPrinterErrorPolicy", (PyCFunction) Connection_setPrinterErrorPolicy, METH_VARARGS, "setPrinterErrorPolicy(name, policy) -> None\n\n" "Set the printer's error policy.\n\n" "@type name: string\n" "@param name: queue name\n" "@type policy: string\n" "@param policy: policy name; supported policy names can be found \n" "by using the L{getPrinterAttributes} function and looking for the \n" "'printer-error-policy-supported' attribute\n" "@raise IPPError: IPP problem" }, { "setPrinterOpPolicy", (PyCFunction) Connection_setPrinterOpPolicy, METH_VARARGS, "setPrinterOpPolicy(name, policy) -> None\n\n" "Set the printer's operation policy.\n\n" "@type name: string\n" "@param name: queue name\n" "@type policy: string\n" "@param policy: policy name; supported policy names can be found \n" "by using the L{getPrinterAttributes} function and looking for the \n" "'printer-op-policy-supported' attribute\n" "@raise IPPError: IPP problem" }, { "setPrinterUsersAllowed", (PyCFunction) Connection_setPrinterUsersAllowed, METH_VARARGS, "setPrinterUsersAllowed(name, allowed) -> None\n\n" "Set the list of users allowed to use a printer. This works \n" "with CUPS server of at least version 1.2, by setting the \n" "requesting-user-name-allowed printer attribute.\n\n" "@type name: string\n" "@param name: queue name\n" "@type allowed: string list\n" "@param allowed: list of allowed users; ['all'] \n" "means there will be no user-name restriction.\n" "@raise IPPError: IPP problem" }, { "setPrinterUsersDenied", (PyCFunction) Connection_setPrinterUsersDenied, METH_VARARGS, "setPrinterUsersDenied(name, denied) -> None\n\n" "Set the list of users denied the use of a printer. This works \n" "with CUPS servers of at least version 1.2, by setting the \n" "requesting-user-name-denied printer attribute.\n\n" "@type name: string\n" "@param name: queue name\n" "@type denied: string list\n" "@param denied: list of denied users; ['none'] \n" "means there will be no user-name restriction.\n" "@raise IPPError: IPP problem" }, { "addPrinterOptionDefault", (PyCFunction) Connection_addPrinterOptionDefault, METH_VARARGS, "addPrinterOptionDefault(name, option, value) -> None\n\n" "Set a network default option. Jobs submitted to the named queue \n" "will have the job option added if it is not already present in the \n" "job. This works with CUPS servers of at least version 1.2.\n\n" "@type name: string\n" "@param name: queue name\n" "@type option: string\n" "@param option: option name, for example 'job-priority'\n" "@type value: string\n" "@param value: option value as a string\n" "@raise IPPError: IPP problem" }, { "deletePrinterOptionDefault", (PyCFunction) Connection_deletePrinterOptionDefault, METH_VARARGS, "deletePrinterOptionDefault(name, option) -> None\n\n" "Removes a network default option. See L{addPrinterOptionDefault}.\n\n" "@type name: string\n" "@param name: queue name\n" "@type option: string\n" "@param option: option name, for example 'job-priority'\n" "@raise IPPError: IPP problem" }, { "deletePrinter", (PyCFunction) Connection_deletePrinter, METH_VARARGS | METH_KEYWORDS, "deletePrinter(name) -> None\n\n" "Delete a printer.\n\n" "@type name: string\n" "@param name: queue name\n" "@raise IPPError: IPP problem" }, { "getPrinterAttributes", (PyCFunction) Connection_getPrinterAttributes, METH_VARARGS | METH_KEYWORDS, "getPrinterAttributes(name=None, uri=None, requested_attributes=None) -> dict\n" "Fetch the attributes for a printer, specified either by name or by \n" "uri but not both.\n\n" "@type name: string\n" "@param name: queue name\n" "@type uri: string\n" "@param uri: queue URI\n" "@type requested_attributes: string list\n" "@param requested_attributes: list of requested attribute names\n" "@return: a dict, indexed by attribute, of printer attributes\n" "for the specified printer.\n\n" "Attributes:\n" " - 'job-sheets-supported': list of strings\n" " - 'job-sheets-default': tuple of strings (start, end)\n" " - 'printer-error-policy-supported': if present, list of strings\n" " - 'printer-error-policy': if present, string\n" " - 'printer-op-policy-supported': if present, list of strings\n" " - 'printer-op-policy': if present, string\n\n" "There are other attributes; the exact list of attributes returned \n" "will depend on the IPP server.\n" "@raise IPPError: IPP problem"}, { "addPrinterToClass", (PyCFunction) Connection_addPrinterToClass, METH_VARARGS, "addPrinterToClass(name, class) -> None\n\n" "Add a printer to a class. If the class does not yet exist, \n" "it is created.\n\n" "@type name: string\n" "@param name: queue name\n" "@type class: string\n" "@param class: class name\n" "@raise IPPError: IPP problem" }, { "deletePrinterFromClass", (PyCFunction) Connection_deletePrinterFromClass, METH_VARARGS, "deletePrinterFromClass(name, class) -> None\n\n" "Remove a printer from a class. If the class would be left empty, \n" "it is removed.\n\n" "@type name: string\n" "@param name: queue name\n" "@type class: string\n" "@param class: class name\n" "@raise IPPError: IPP problem" }, { "deleteClass", (PyCFunction) Connection_deleteClass, METH_VARARGS, "deleteClass(class) -> None\n\n" "Delete a class.\n\n" "@type class: string\n" "@param class: class name\n" "@raise IPPError: IPP problem" }, { "getDefault", (PyCFunction) Connection_getDefault, METH_NOARGS, "getDefault() -> string or None\n\n" "Get the system default printer.\n\n" "@return: default printer name or None" }, { "setDefault", (PyCFunction) Connection_setDefault, METH_VARARGS | METH_KEYWORDS, "setDefault(name) -> None\n\n" "Set the system default printer. Note that this can be over-ridden \n" "on a per-user basis using the lpoptions command.\n\n" "@type name: string\n" "@param name: queue name\n" "@raise IPPError: IPP problem" }, { "getPPD", (PyCFunction) Connection_getPPD, METH_VARARGS, "getPPD(name) -> string\n\n" "Fetch a printer's PPD.\n\n" "@type name: string\n" "@param name: queue name\n" "@return: temporary PPD file name\n" "@raise IPPError: IPP problem" }, { "getPPD3", (PyCFunction) Connection_getPPD3, METH_VARARGS | METH_KEYWORDS, "getPPD3(name[, modtime, filename]) -> (status,modtime,filename)\n\n" "Fetch a printer's PPD if it is newer.\n\n" "@type name: string\n" "@param name: queue name\n" "@type modtime: float\n" "@param modtime: modification time of existing file\n" "@type filename: string\n" "@param filename: filename of existing file\n" "@return: tuple of HTTP status, modification time, and filename\n" }, { "enablePrinter", (PyCFunction) Connection_enablePrinter, METH_VARARGS | METH_KEYWORDS, "enablePrinter(name) -> None\n\n" "Enable printer. This allows the printer to process its job queue.\n\n" "@type name: string\n" "@param name: queue name\n" "@raise IPPError: IPP problem" }, { "disablePrinter", (PyCFunction) Connection_disablePrinter, METH_VARARGS | METH_KEYWORDS, "disablePrinter(name) -> None\n\n" "Disable printer. This prevents the printer from processing its \n" "job queue.\n\n" "@type name: string\n" "@param name: queue name\n" "@type reason: string\n" "@keyword reason: optional human-readable reason for disabling the \n" "printer\n" "@raise IPPError: IPP problem" }, { "acceptJobs", (PyCFunction) Connection_acceptJobs, METH_VARARGS | METH_KEYWORDS, "acceptJobs(name) -> None\n\n" "Cause printer to accept jobs.\n" "@type name: string\n" "@param name: queue name\n" "@raise IPPError: IPP problem" }, { "rejectJobs", (PyCFunction) Connection_rejectJobs, METH_VARARGS | METH_KEYWORDS, "rejectJobs(name)\n\n" "Cause printer to reject jobs.\n\n" "@type name: string\n" "@param name: queue name\n" "@type reason: string\n" "@keyword reason: optional human-readable reason for rejecting jobs\n" "@raise IPPError: IPP problem" }, { "printTestPage", (PyCFunction) Connection_printTestPage, METH_VARARGS | METH_KEYWORDS, "printTestPage(name) -> job ID\n\n" "Print a test page.\n\n" "@type name: string\n" "@param name: queue name\n" "@type file: string\n" "@keyword file: input file (default is CUPS test page)\n" "@type title: string\n" "@keyword title: job title (default 'Test Page')\n" "@type format: string\n" "@keyword format: document format (default 'application/postscript')\n" "@type user: string\n" "@keyword user: user to submit the job as\n" "@raise IPPError: IPP problem" }, { "adminExportSamba", (PyCFunction) Connection_adminExportSamba, METH_VARARGS, "adminExportSamba(name, samba_server, samba_username,\n" " samba_password) -> None\n\n" "Export a printer to Samba.\n\n" "@type name: string\n" "@param name: queue name\n" "@type samba_server: string\n" "@param samba_server: samba server\n" "@type samba_username: string\n" "@param samba_username: samba username\n" "@type samba_password: string\n" "@param samba_password: samba password\n" "@raise IPPError: IPP problem" }, { "adminGetServerSettings", (PyCFunction) Connection_adminGetServerSettings, METH_NOARGS, "adminGetServerSettings() -> dict\n\n" "Get server settings.\n\n" "@return: dict representing server settings; keywords include \n" "L{CUPS_SERVER_DEBUG_LOGGING}, L{CUPS_SERVER_REMOTE_ADMIN}, \n" "L{CUPS_SERVER_REMOTE_PRINTERS}, L{CUPS_SERVER_SHARE_PRINTERS}, \n" "L{CUPS_SERVER_USER_CANCEL_ANY}\n" "@see: L{adminSetServerSettings}\n" "@raise IPPError: IPP problem" }, { "adminSetServerSettings", (PyCFunction) Connection_adminSetServerSettings, METH_VARARGS, "adminSetServerSettings(settings) -> None\n\n" "Set server settings.\n\n" "@type settings: dict\n" "@param settings: dict of server settings\n" "@see: L{adminGetServerSettings}\n" "@raise IPPError: IPP problem" }, { "getSubscriptions", (PyCFunction) Connection_getSubscriptions, METH_VARARGS | METH_KEYWORDS, "getSubscriptions(uri) -> integer list\n\n" "Get subscriptions.\n\n" "@type uri: string\n" "@param uri: URI for object\n" "@type my_subscriptions: boolean\n" "@keyword my_subscriptions: only return subscriptions belonging to \n" "the current user (default False)\n" "@type job_id: integer\n" "@keyword job_id: only return subscriptions relating to this job\n" "@return: list of subscriptions\n" "@raise IPPError: IPP problem" }, { "createSubscription", (PyCFunction) Connection_createSubscription, METH_VARARGS | METH_KEYWORDS, "createSubscription(uri, events=[], job_id=-1, recipient_uri="",\n" " lease_duration=-1, time_interval=-1,\n" " user_data="") -> integer\n\n" "Create a subscription.\n\n" "@type uri: string\n" "@param uri: URI for object\n" "@type events: string list\n" "@keyword events: events to receive notifications for\n" "@type job_id: integer\n" "@keyword job_id: job ID to receive notifications for\n" "@type recipient_uri: string\n" "@keyword recipient_uri: URI for notifications recipient\n" "@type lease_duration: integer\n" "@keyword lease_duration: lease duration in seconds\n" "@type time_interval: integer\n" "@keyword time_interval: time interval\n" "@type user_data: string\n" "@keyword user_data: user data to receive with notifications\n" "@return: subscription ID\n" "@raise IPPError: IPP problem" }, { "getNotifications", (PyCFunction) Connection_getNotifications, METH_VARARGS | METH_KEYWORDS, "getNotifications(subscription_ids) -> list\n\n" "Get notifications for subscribed events.\n\n" "@type subscription_ids: integer list\n" "@param subscription_ids: list of subscription IDs to receive \n" "notifications for\n" "@return: list of dicts, each representing an event\n" "@raise IPPError: IPP problem" }, { "cancelSubscription", (PyCFunction) Connection_cancelSubscription, METH_VARARGS, "cancelSubscription(id) -> None\n\n" "Cancel a subscription.\n\n" "@type id: integer\n" "@param id: subscription ID\n" "@raise IPPError: IPP problem" }, { "renewSubscription", (PyCFunction) Connection_renewSubscription, METH_VARARGS | METH_KEYWORDS, "renewSubscription(id, lease_duration=-1) -> None\n\n" "Renew a subscription.\n\n" "@type id: integer\n" "@param id: subscription ID\n" "@type lease_duration: integer\n" "@param lease_duration: lease duration in seconds\n" "@raise IPPError: IPP problem" }, { "createJob", (PyCFunction) Connection_createJob, METH_VARARGS | METH_KEYWORDS, "createJob(printer, title, options) -> integer\n\n" "Create an empty job for streaming.\n\n" "@type printer: string\n" "@param printer: queue name\n" "@type title: string\n" "@param title: title of the print job\n" "@type options: dict\n" "@param options: dict of options\n" "@return: job ID\n" "@raise IPPError: IPP problem" }, { "startDocument", (PyCFunction) Connection_startDocument, METH_VARARGS | METH_KEYWORDS, "startDocument(printer, job_id, doc_name, format, last_document) -> integer\n\n" "Add a document to a job created with createJob.\n\n" "@type printer: string\n" "@param printer: queue name\n" "@type job_id: integer\n" "@param job_id: job ID to create document\n" "@type doc_name: string\n" "@param doc_name: name of the document\n" "@type format: string\n" "@param format: MIME type\n" "@type last_document: integer\n" "@param last_document: 1 for last document of job, 0 otherwise\n" "@return: HTTP status\n" "@raise IPPError: IPP problem" }, { "writeRequestData", (PyCFunction) Connection_writeRequestData, METH_VARARGS | METH_KEYWORDS, "writeRequestData(buffer, length) -> integer\n\n" "Write data after an IPP request.\n\n" "@type buffer: string\n" "@param buffer: bytes to write\n" "@type length: integer\n" "@param length: number of bytes to write\n" "@return: HTTP status\n" "@raise IPPError: IPP problem" }, { "finishDocument", (PyCFunction) Connection_finishDocument, METH_VARARGS | METH_KEYWORDS, "finishDocument(printer) -> integer\n\n" "Finish sending a document.\n\n" "@type printer: string\n" "@param printer: queue name\n" "@return: HTTP status\n" "@raise IPPError: IPP problem" }, { "printFile", (PyCFunction) Connection_printFile, METH_VARARGS | METH_KEYWORDS, "printFile(printer, filename, title, options) -> integer\n\n" "Print a file.\n\n" "@type printer: string\n" "@param printer: queue name\n" "@type filename: string\n" "@param filename: local file path to the document\n" "@type title: string\n" "@param title: title of the print job\n" "@type options: dict\n" "@param options: dict of options\n" "@return: job ID\n" "@raise IPPError: IPP problem" }, { "printFiles", (PyCFunction) Connection_printFiles, METH_VARARGS | METH_KEYWORDS, "printFiles(printer, filenames, title, options) -> integer\n\n" "Print a list of files.\n\n" "@type printer: string\n" "@param printer: queue name\n" "@type filenames: list\n" "@param filenames: list of local file paths to the documents\n" "@type title: string\n" "@param title: title of the print job\n" "@type options: dict\n" "@param options: dict of options\n" "@return: job ID\n" "@raise IPPError: IPP problem" }, { NULL } /* Sentinel */ }; PyTypeObject cups_ConnectionType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.Connection", /*tp_name*/ sizeof(Connection), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Connection_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Connection_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "CUPS connection\n" "===============\n\n" " A connection to the CUPS server. Before it is created the \n" " connection server and username should be set using \n" " L{cups.setServer} and L{cups.setUser}; otherwise the defaults will \n" " be used. When a Connection object is instantiated it results in a \n" " call to the libcups function httpConnectEncrypt().\n\n" " The constructor takes optional arguments host, port, and encryption, \n" " which default to the values of L{cups.getServer}(), \n" " L{cups.getPort}(), and L{cups.getEncryption}().\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Connection_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Connection_init, /* tp_init */ 0, /* tp_alloc */ Connection_new, /* tp_new */ }; ////////// // Dest // ////////// static PyObject * Dest_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Dest *self; self = (Dest *) type->tp_alloc (type, 0); return (PyObject *) self; } static int Dest_init (Dest *self, PyObject *args, PyObject *kwds) { self->num_options = 0; return 0; } static void Dest_dealloc (Dest *self) { if (self->num_options) { int i; for (i = 0; i < self->num_options; i++) { free (self->name[i]); free (self->value[i]); } free (self->name); free (self->value); self->num_options = 0; free (self->destname); free (self->instance); } ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static PyObject * Dest_repr (Dest *self) { char buffer[256]; snprintf (buffer, 256, "", self->destname, self->instance ? "/" : "", self->instance ? self->instance : "", self->is_default ? " (default)" : ""); return PyUnicode_FromString (buffer); } ////////// // Dest // ATTRIBUTES ////////// static PyObject * Dest_getName (Dest *self, void *closure) { return PyUnicode_FromString (self->destname); } static PyObject * Dest_getInstance (Dest *self, void *closure) { if (self->instance) return PyUnicode_FromString (self->instance); Py_RETURN_NONE; } static PyObject * Dest_getIsDefault (Dest *self, void *closure) { return PyBool_FromLong (self->is_default); } static PyObject * Dest_getOptions (Dest *self, void *closure) { PyObject *pyoptions = PyDict_New (); int i; for (i = 0; i < self->num_options; i++) { PyObject *string = PyUnicode_FromString (self->value[i]); PyDict_SetItemString (pyoptions, self->name[i], string); Py_DECREF (string); } return pyoptions; } PyGetSetDef Dest_getseters[] = { { "name", (getter) Dest_getName, (setter) NULL, "name", NULL }, { "instance", (getter) Dest_getInstance, (setter) NULL, "instance", NULL }, { "is_default", (getter) Dest_getIsDefault, (setter) NULL, "is_default", NULL }, { "options", (getter) Dest_getOptions, (setter) NULL, "options", NULL }, { NULL } }; PyTypeObject cups_DestType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.Dest", /*tp_name*/ sizeof(Dest), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Dest_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Dest_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "CUPS destination\n" "================\n\n" " A destination print queue, as returned by L{Connection.getDests}.\n\n" "@type name: string\n" "@ivar name: destination queue name\n" "@type instance: string\n" "@ivar instance: destination instance name\n" "@type is_default: boolean\n" "@ivar is_default: whether this is the default destination\n" "@type options: dict\n" "@ivar options: string:string dict of default options for this \n" "destination, indexed by option name\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Dest_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Dest_init, /* tp_init */ 0, /* tp_alloc */ Dest_new, /* tp_new */ }; pycups-2.0.4/cupsconnection.h000066400000000000000000000041061461013555200162460ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Tim Waugh * Authors: Tim Waugh * Zdenek Dohnal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef HAVE_CUPSCONNECTION_H #define HAVE_CUPSCONNECTION_H #include #include #include "cupsmodule.h" extern PyMethodDef Connection_methods[]; extern PyTypeObject cups_ConnectionType; extern PyTypeObject cups_DestType; typedef struct { PyObject_HEAD http_t *http; char *host; /* for repr */ char *cb_password; PyThreadState *tstate; } Connection; typedef struct { PyObject_HEAD int is_default; char *destname; char *instance; // Options int num_options; char **name; char **value; } Dest; extern PyObject *HTTPError; extern PyObject *IPPError; void Connection_begin_allow_threads (void *connection); void Connection_end_allow_threads (void *connection); const char *password_callback_newstyle (const char *prompt, http_t *http, const char *method, const char *resource, void *user_data); const char *password_callback_oldstyle (const char *prompt, http_t *http, const char *method, const char *resource, void *user_data); int cups_dest_cb (void *user_data, unsigned flags, cups_dest_t *dest); void set_ipp_error (ipp_status_t status, const char *message); #endif /* HAVE_CUPSCONNECTION_H */ pycups-2.0.4/cupsipp.c000066400000000000000000000533471461013555200147050ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Red Hat, Inc. * Authors: Tim Waugh * Zdenek Dohnal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "cupsipp.h" #include "cupsmodule.h" ////////////////// // IPPAttribute // ////////////////// static PyObject * IPPAttribute_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { IPPAttribute *self; self = (IPPAttribute *) type->tp_alloc (type, 0); if (self != NULL) { self->group_tag = IPP_TAG_ZERO; self->value_tag = IPP_TAG_ZERO; self->name = NULL; self->values = NULL; } return (PyObject *) self; } static int IPPAttribute_init (IPPAttribute *self, PyObject *args, PyObject *kwds) { ipp_tag_t group_tag, value_tag; PyObject *nameobj; char *name; PyObject *value = NULL; PyObject *list = NULL; if (!PyArg_ParseTuple (args, "iiO|O", &group_tag, &value_tag, &nameobj, &value)) return -1; if (UTF8_from_PyObj (&name, nameobj) == NULL) return -1; if (value == NULL) { switch (value_tag) { case IPP_TAG_ZERO: case IPP_TAG_NOVALUE: case IPP_TAG_NOTSETTABLE: case IPP_TAG_ADMINDEFINE: break; default: PyErr_SetString (PyExc_RuntimeError, "missing value list"); return -1; } } else { size_t i, n; int valid = 1; if (PyList_Check (value)) { list = value; Py_INCREF (value); n = PyList_Size (value); } else { list = PyList_New (0); PyList_Append (list, value); n = 1; } for (i = 0; valid && i < n; i++) { PyObject *v = PyList_GetItem (list, i); // borrowed switch (value_tag) { case IPP_TAG_INTEGER: case IPP_TAG_ENUM: case IPP_TAG_RANGE: valid = PyLong_Check (v); break; case IPP_TAG_BOOLEAN: valid = PyBool_Check (v); break; case IPP_TAG_TEXT: valid = PyUnicode_Check (v); break; case IPP_TAG_NAME: case IPP_TAG_KEYWORD: case IPP_TAG_URI: case IPP_TAG_MIMETYPE: case IPP_TAG_CHARSET: case IPP_TAG_LANGUAGE: valid = (PyUnicode_Check (v) || PyBytes_Check (v)); break; default: valid = 0; } } if (!valid) { PyErr_SetString (PyExc_RuntimeError, "invalid value"); Py_DECREF (list); return -1; } } self->group_tag = group_tag; self->value_tag = value_tag; self->values = list; self->name = name; return 0; } static void IPPAttribute_dealloc (IPPAttribute *self) { Py_XDECREF (self->values); if (self->name) free (self->name); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static PyObject * IPPAttribute_repr (IPPAttribute *self) { PyObject *ret; PyObject *values_repr = NULL; char *values = NULL; char buffer[1024]; if (self->values) { values_repr = PyList_Type.tp_repr (self->values); UTF8_from_PyObj (&values, values_repr); } snprintf (buffer, sizeof (buffer), "", self->name, self->group_tag, self->value_tag, values ? ": " : "", values ? values : ""); ret = PyUnicode_FromString (buffer); free (values); Py_XDECREF (values_repr); return ret; } ////////////////// // IPPAttribute // ATTRIBUTES ////////////////// static PyObject * IPPAttribute_getGroupTag (IPPAttribute *self, void *closure) { return PyLong_FromLong (self->group_tag); } static PyObject * IPPAttribute_getValueTag (IPPAttribute *self, void *closure) { return PyLong_FromLong (self->value_tag); } static PyObject * IPPAttribute_getName (IPPAttribute *self, void *closure) { return PyUnicode_FromString (self->name); } static PyObject * IPPAttribute_getValues (IPPAttribute *self, void *closure) { Py_INCREF (self->values); return self->values; } PyGetSetDef IPPAttribute_getseters[] = { { "group_tag", (getter) IPPAttribute_getGroupTag, (setter) NULL, "IPP group tag", NULL }, { "value_tag", (getter) IPPAttribute_getValueTag, (setter) NULL, "IPP value tag", NULL }, { "name", (getter) IPPAttribute_getName, (setter) NULL, "IPP attribute name", NULL }, { "values", (getter) IPPAttribute_getValues, (setter) NULL, "List of values" }, { NULL }, /* Sentinel */ }; PyMethodDef IPPAttribute_methods[] = { { NULL } /* Sentinel */ }; PyTypeObject cups_IPPAttributeType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.IPPAttribute", /*tp_name*/ sizeof(IPPAttribute), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)IPPAttribute_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)IPPAttribute_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "IPP Attribute\n" "=============\n" " An IPP attribute.\n\n" "@type group_tag: int\n" "@ivar group_tag: IPP group tag\n" "@type value_tag: int\n" "@ivar value_tag: IPP value tag\n" "@type values: list\n" "@ivar value: list of values\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ IPPAttribute_methods, /* tp_methods */ 0, /* tp_members */ IPPAttribute_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)IPPAttribute_init, /* tp_init */ 0, /* tp_alloc */ IPPAttribute_new, /* tp_new */ }; //////////////// // IPPRequest // //////////////// static PyObject * IPPRequest_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { IPPRequest *self; self = (IPPRequest *) type->tp_alloc (type, 0); if (self != NULL) self->ipp = NULL; return (PyObject *) self; } static int IPPRequest_init (IPPRequest *self, PyObject *args, PyObject *kwds) { long op = -1; if (!PyArg_ParseTuple (args, "|i", &op)) return -1; if (op == -1) self->ipp = ippNew (); else self->ipp = ippNewRequest (op); return 0; } static void IPPRequest_dealloc (IPPRequest *self) { ippDelete (self->ipp); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static IPPAttribute * build_IPPAttribute (ipp_attribute_t *attr) { IPPAttribute *attribute = NULL; PyObject *largs = NULL; PyObject *lkwlist = NULL; PyObject *values = NULL; debugprintf ("%s: ", ippGetName (attr)); if (ippGetValueTag (attr) == IPP_TAG_ZERO || ippGetValueTag (attr) == IPP_TAG_NOVALUE || ippGetValueTag (attr) == IPP_TAG_NOTSETTABLE || ippGetValueTag (attr) == IPP_TAG_ADMINDEFINE) { debugprintf ("no value\n"); } else { PyObject *value = NULL; int i; int unknown_value_tag = 0; values = PyList_New (0); if (!values) goto out; for (i = 0; i < ippGetCount (attr); i++) { switch (ippGetValueTag (attr)) { case IPP_TAG_INTEGER: case IPP_TAG_ENUM: case IPP_TAG_RANGE: value = PyLong_FromLong (ippGetInteger (attr, i)); debugprintf ("i%d", ippGetInteger (attr, i)); break; case IPP_TAG_BOOLEAN: value = PyBool_FromLong (ippGetBoolean (attr, i)); debugprintf ("b%d", ippGetInteger (attr, i)); break; case IPP_TAG_TEXT: value = PyUnicode_Decode (ippGetString (attr, i, NULL), strlen (ippGetString (attr, i, NULL)), "utf-8", NULL); debugprintf ("u%s", ippGetString (attr, i, NULL)); break; case IPP_TAG_NAME: case IPP_TAG_KEYWORD: case IPP_TAG_URI: case IPP_TAG_MIMETYPE: case IPP_TAG_CHARSET: case IPP_TAG_LANGUAGE: value = PyUnicode_FromString (ippGetString (attr, i, NULL)); debugprintf ("s%s", ippGetString (attr, i, NULL)); break; default: value = NULL; unknown_value_tag = 1; debugprintf ("Unable to encode value tag %d\n", ippGetValueTag (attr)); } if (!value) break; /* out of values loop */ debugprintf ("(%p), ", value); if (PyList_Append (values, value) != 0) { Py_DECREF (values); Py_DECREF (value); goto out; } Py_DECREF (value); } if (unknown_value_tag) { Py_DECREF (values); goto out; } debugprintf ("\n"); } if (values) { largs = Py_BuildValue ("(iisO)", ippGetGroupTag (attr), ippGetValueTag (attr), ippGetName (attr), values); Py_DECREF (values); values = NULL; } else largs = Py_BuildValue ("(iis)", ippGetGroupTag (attr), ippGetValueTag (attr), ippGetName (attr) ? ippGetName (attr) : ""); if (!largs) goto out; lkwlist = Py_BuildValue ("{}"); if (!lkwlist) goto out; attribute = (IPPAttribute *) PyType_GenericNew (&cups_IPPAttributeType, largs, lkwlist); if (!attribute) goto out; if (IPPAttribute_init (attribute, largs, lkwlist) != 0) { Py_DECREF (attribute); attribute = NULL; } out: if (values) Py_DECREF (values); if (largs) Py_DECREF (largs); if (lkwlist) Py_DECREF (lkwlist); return attribute; } static PyObject * IPPRequest_addSeparator (IPPRequest *self) { ipp_attribute_t *attr = ippAddSeparator (self->ipp); return (PyObject *) build_IPPAttribute (attr); } static PyObject * IPPRequest_add (IPPRequest *self, PyObject *args) { PyObject *obj; IPPAttribute *attribute; Py_ssize_t num_values; void *values = NULL; size_t value_size = 0; int i; if (!PyArg_ParseTuple (args, "O", &obj)) return NULL; if (Py_TYPE(obj) != &cups_IPPAttributeType) { PyErr_SetString (PyExc_TypeError, "Parameter must be IPPAttribute"); return NULL; } attribute = (IPPAttribute *) obj; num_values = PyList_Size (attribute->values); switch (attribute->value_tag) { case IPP_TAG_INTEGER: case IPP_TAG_ENUM: case IPP_TAG_RANGE: value_size = sizeof (int); break; case IPP_TAG_BOOLEAN: value_size = sizeof (char); break; case IPP_TAG_NAME: case IPP_TAG_KEYWORD: case IPP_TAG_URI: case IPP_TAG_MIMETYPE: case IPP_TAG_CHARSET: case IPP_TAG_LANGUAGE: value_size = sizeof (char *); break; default: break; } values = calloc (num_values, value_size); if (!values) { PyErr_SetString (PyExc_MemoryError, "Unable to allocate memory"); return NULL; } switch (attribute->value_tag) { case IPP_TAG_INTEGER: case IPP_TAG_ENUM: case IPP_TAG_RANGE: for (i = 0; i < num_values; i++) { PyObject *item = PyList_GetItem (attribute->values, i); if (PyLong_Check (item)) ((int *)values)[i] = PyLong_AsLong (item); } ippAddIntegers (self->ipp, attribute->group_tag, attribute->value_tag, attribute->name, num_values, values); break; case IPP_TAG_BOOLEAN: for (i = 0; i < num_values; i++) { PyObject *item = PyList_GetItem (attribute->values, i); ((char *)values)[i] = (item == Py_True ? 1 : 0); } ippAddBooleans (self->ipp, attribute->group_tag, attribute->name, num_values, values); break; case IPP_TAG_NAME: case IPP_TAG_KEYWORD: case IPP_TAG_URI: case IPP_TAG_MIMETYPE: case IPP_TAG_CHARSET: case IPP_TAG_LANGUAGE: for (i = 0; i < num_values; i++) { PyObject *item = PyList_GetItem (attribute->values, i); char *str; str = strdup (PyUnicode_AsUTF8 (item)); ((char **)values)[i] = str; if (!str) break; } if (i < num_values) { int j; for (j = 0; j < i; j++) free (((char **)values)[j]); PyErr_SetString (PyExc_MemoryError, "Unable to allocate memory"); free (values); return NULL; } ippAddStrings (self->ipp, attribute->group_tag, attribute->value_tag, attribute->name, num_values, NULL, values); for (i = 0; i < num_values; i++) free (((char **)values)[i]); break; default: break; } free (values); Py_INCREF (obj); return obj; } static ssize_t cupsipp_iocb_read (PyObject *callable, ipp_uchar_t *buffer, size_t len) { PyObject *args = Py_BuildValue ("(i)", len); PyObject *result; Py_ssize_t got = -1; char *gotbuffer; debugprintf ("-> cupsipp_iocb_read\n"); if (!args) { debugprintf ("Py_BuildValue failed\n"); goto out; } result = PyObject_Call (callable, args, NULL); Py_DECREF (args); if (result == NULL) { debugprintf ("Exception in read callback\n"); goto out; } if (PyUnicode_Check (result) || PyBytes_Check (result)) { if (PyUnicode_Check (result)) { PyObject *stringobj = PyUnicode_AsUTF8String (result); PyBytes_AsStringAndSize (stringobj, &gotbuffer, &got); } else { PyBytes_AsStringAndSize (result, &gotbuffer, &got); } if (got < 0) { debugprintf("No returned data.\n"); goto out; } if ((unsigned long)got > len) { debugprintf ("More data returned than requested! Truncated...\n"); got = len; } memcpy (buffer, gotbuffer, got); } else { debugprintf ("Unknown result object type!\n"); } Py_DECREF (result); out: debugprintf ("<- cupsipp_iocb_read() == %zd\n", got); return got; } static ssize_t cupsipp_iocb_write (PyObject *callable, ipp_uchar_t *buffer, size_t len) { PyObject *args = Py_BuildValue ("(y#)", buffer, len); PyObject *result = NULL; Py_ssize_t wrote = -1; debugprintf ("-> cupsipp_iocb_write\n"); if (!args) { debugprintf ("Py_BuildValue failed\n"); goto out; } result = PyObject_Call (callable, args, NULL); Py_DECREF (args); if (result == NULL) { debugprintf ("Exception in write callback\n"); goto out; } if (PyLong_Check (result)) wrote = PyLong_AsLong (result); else { debugprintf ("Bad return value\n"); goto out; } out: if (result) Py_DECREF (result); debugprintf ("<- cupsipp_iocb_write()\n"); return wrote; } static PyObject * IPPRequest_readIO (IPPRequest *self, PyObject *args, PyObject *kwds) { PyObject *cb; char blocking = 1; ipp_state_t state; static char *kwlist[] = { "read_fn", "blocking", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|b", kwlist, &cb, &blocking)) return NULL; if (!PyCallable_Check (cb)) { PyErr_SetString (PyExc_TypeError, "Parameter must be callable"); return NULL; } state = ippReadIO (cb, (ipp_iocb_t) cupsipp_iocb_read, blocking, NULL, self->ipp); return PyLong_FromLong (state); } static PyObject * IPPRequest_writeIO (IPPRequest *self, PyObject *args, PyObject *kwds) { PyObject *cb; char blocking = 1; ipp_state_t state; static char *kwlist[] = { "write_fn", "blocking", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|b", kwlist, &cb, &blocking)) return NULL; if (!PyCallable_Check (cb)) { PyErr_SetString (PyExc_TypeError, "Parameter must be callable"); return NULL; } state = ippWriteIO (cb, (ipp_iocb_t) cupsipp_iocb_write, blocking, NULL, self->ipp); return PyLong_FromLong (state); } /* Request properties */ static PyObject * IPPRequest_getAttributes (IPPRequest *self, void *closure) { PyObject *attrs = PyList_New (0); ipp_attribute_t *attr; for (attr = ippFirstAttribute (self->ipp); attr; attr = ippNextAttribute(self->ipp)) { IPPAttribute *attribute = build_IPPAttribute (attr); if (!attribute) goto fail; if (PyList_Append (attrs, (PyObject *) attribute) != 0) goto fail; } return attrs; fail: Py_DECREF (attrs); return NULL; } static PyObject * IPPRequest_getOperation (IPPRequest *self, void *closure) { return PyLong_FromLong (ippGetOperation (self->ipp)); } static PyObject * IPPRequest_getStatuscode (IPPRequest *self, void *closure) { return PyLong_FromLong (ippGetStatusCode (self->ipp)); } static int IPPRequest_setState (IPPRequest *self, PyObject *value, void *closure) { int state; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete state"); return -1; } if (PyLong_Check(value)) state = PyLong_AsLong (value); else { PyErr_SetString(PyExc_TypeError, "state must be an integer"); return -1; } ippSetState (self->ipp, state); return 0; } static PyObject * IPPRequest_getState (IPPRequest *self, void *closure) { return PyLong_FromLong (ippGetState (self->ipp)); } static int IPPRequest_setStatuscode (IPPRequest *self, PyObject *value, void *closure) { int statuscode; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "Cannot delete statuscode"); return -1; } if (PyLong_Check(value)) statuscode = PyLong_AsLong (value); else { PyErr_SetString(PyExc_TypeError, "statuscode must be an integer"); return -1; } ippSetStatusCode (self->ipp, statuscode); return 0; } PyGetSetDef IPPRequest_getseters[] = { { "attributes", (getter) IPPRequest_getAttributes, (setter) NULL, "IPP request attributes", NULL }, { "operation", (getter) IPPRequest_getOperation, (setter) NULL, "IPP request operation", NULL }, { "state", (getter) IPPRequest_getState, (setter) IPPRequest_setState, "IPP request transfer state", NULL }, { "statuscode", (getter) IPPRequest_getStatuscode, (setter) IPPRequest_setStatuscode, "IPP response status code", NULL }, { NULL } /* Sentinel */ }; PyMethodDef IPPRequest_methods[] = { { "addSeparator", (PyCFunction) IPPRequest_addSeparator, METH_NOARGS, "addSeparator() -> IPPAttribute\n\n" "@return: IPP request attribute" }, { "add", (PyCFunction) IPPRequest_add, METH_VARARGS, "add(attr) -> IPPAttribute\n\n" "@type attr: IPPAttribute\n" "@param attr: Attribute to add to the request\n" "@return: IPP request attribute" }, { "readIO", (PyCFunction) IPPRequest_readIO, METH_VARARGS | METH_KEYWORDS, "readIO(read_fn, blocking=True) -> IPP state\n\n" "@type read_fn: Callable function\n" "@param read_fn: A callback, taking a single integer argument for\n" "'size', for reading IPP data\n" "@type blocking: Boolean\n" "@param blocking: whether to continue reading until a complete\n" "request is read\n" "@return: IPP state value" }, { "writeIO", (PyCFunction) IPPRequest_writeIO, METH_VARARGS | METH_KEYWORDS, "writeIO(write_fn, blocking=True) -> IPP state\n\n" "@type write_fn: Callable function\n" "@param write_fn: A callback, taking a bytes object, for writing\n" "IPP data\n" "@type blocking: Boolean\n" "@param blocking: whether to continue reading until a complete\n" "request is written\n" "@return: IPP state value" }, { NULL } /* Sentinel */ }; PyTypeObject cups_IPPRequestType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.IPPRequest", /*tp_name*/ sizeof(IPPRequest), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)IPPRequest_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "IPP Request\n" "===========\n" " An IPP request. The constructor takes an optional argument of the\n" "operation code.\n\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ IPPRequest_methods, /* tp_methods */ 0, /* tp_members */ IPPRequest_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)IPPRequest_init, /* tp_init */ 0, /* tp_alloc */ IPPRequest_new, /* tp_new */ }; pycups-2.0.4/cupsipp.h000066400000000000000000000025521461013555200147020ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Red Hat, Inc * Author: Tim Waugh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef HAVE_CUPSIPP_H #define HAVE_CUPSIPP_H #define PY_SSIZE_T_CLEAN #include #include extern PyMethodDef IPPRequest_methods[]; extern PyTypeObject cups_IPPRequestType; extern PyMethodDef IPPAttribute_methods[]; extern PyTypeObject cups_IPPAttributeType; typedef struct { PyObject_HEAD ipp_t *ipp; } IPPRequest; typedef struct { PyObject_HEAD ipp_tag_t group_tag; ipp_tag_t value_tag; char *name; /* Python List of values */ PyObject *values; } IPPAttribute; #endif /* HAVE_CUPSIPP_H */ pycups-2.0.4/cupsmodule.c000066400000000000000000001070731461013555200153760ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Red Hat, Inc * Authors: Tim Waugh * Zdenek Dohnal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include "cupsmodule.h" #include #include #include #include #include "cupsconnection.h" #include "cupsppd.h" #include "cupsipp.h" static pthread_key_t tls_key = -1; static pthread_once_t tls_key_once = PTHREAD_ONCE_INIT; # define CUPS_SERVER_REMOTE_PRINTERS "_remote_printers" ////////////////////// // Worker functions // ////////////////////// /* * Thread local storage functions */ static void destroy_TLS (void *value) { struct TLS *tls = (struct TLS *) value; /* CPython API needs to be run only when our process holds * Python global interpret lock */ PyGILState_STATE gilstate; gilstate = PyGILState_Ensure(); Py_XDECREF (tls->cups_password_callback); Py_XDECREF (tls->cups_password_callback_context); // release global interpret lock PyGILState_Release(gilstate); free (value); } static void init_TLS (void) { pthread_key_create (&tls_key, destroy_TLS); } struct TLS * get_TLS (void) { struct TLS *tls; pthread_once (&tls_key_once, init_TLS); tls = (struct TLS *) pthread_getspecific (tls_key); if (tls == NULL) { tls = calloc (1, sizeof (struct TLS)); pthread_setspecific (tls_key, tls); } return tls; } static int do_model_compare (const wchar_t *a, const wchar_t *b) { const wchar_t *digits = L"0123456789"; wchar_t quick_a, quick_b; while ((quick_a = *a) != L'\0' && (quick_b = *b) != L'\0') { int end_a = wcsspn (a, digits); int end_b = wcsspn (b, digits); int min; int a_is_digit = 1; int cmp; if (quick_a != quick_b && !iswdigit (quick_a) && !iswdigit (quick_b)) { if (quick_a < quick_b) return -1; else return 1; } if (!end_a) { end_a = wcscspn (a, digits); a_is_digit = 0; } if (!end_b) { if (a_is_digit) return -1; end_b = wcscspn (b, digits); } else if (!a_is_digit) return 1; if (a_is_digit) { unsigned long n_a, n_b; n_a = wcstoul (a, NULL, 10); n_b = wcstoul (b, NULL, 10); if (n_a < n_b) cmp = -1; else if (n_a == n_b) cmp = 0; else cmp = 1; } else { min = end_a < end_b ? end_a : end_b; cmp = wcsncmp (a, b, min); } if (!cmp) { if (end_a != end_b) return end_a < end_b ? -1 : 1; a += end_a; b += end_b; continue; } return cmp; } if (quick_a == L'\0') { if (*b == L'\0') return 0; return -1; } return 1; } ////////////////////////// // Module-level methods // ////////////////////////// static PyObject * cups_modelSort (PyObject *self, PyObject *args) { PyObject *Oa, *Ob, *a, *b; long unsigned int len_a, len_b; size_t size_a, size_b; wchar_t *wca, *wcb; if (!PyArg_ParseTuple (args, "OO", &Oa, &Ob)) return NULL; a = PyUnicode_FromObject (Oa); b = PyUnicode_FromObject (Ob); if (a == NULL || b == NULL || !PyUnicode_Check (a) || !PyUnicode_Check (b)) { if (a) { Py_DECREF (a); } if (b) { Py_DECREF (b); } PyErr_SetString (PyExc_TypeError, "Unable to convert to Unicode"); return NULL; } len_a = 1 + (long unsigned)PyUnicode_GetLength (a); size_a = len_a * sizeof (wchar_t); if ((size_a / sizeof (wchar_t)) != len_a) { Py_DECREF (a); Py_DECREF (b); PyErr_SetString (PyExc_RuntimeError, "String too long"); return NULL; } len_b = 1 + (long unsigned)PyUnicode_GetLength (b); size_b = len_b * sizeof (wchar_t); if ((size_b / sizeof (wchar_t)) != len_b) { Py_DECREF (a); Py_DECREF (b); PyErr_SetString (PyExc_RuntimeError, "String too long"); return NULL; } wca = malloc (size_a); wcb = malloc (size_b); if (wca == NULL || wcb == NULL) { Py_DECREF (a); Py_DECREF (b); free (wca); free (wcb); PyErr_SetString (PyExc_RuntimeError, "Insufficient memory"); return NULL; } PyUnicode_AsWideChar (a, wca, size_a); PyUnicode_AsWideChar (b, wcb, size_b); Py_DECREF (a); Py_DECREF (b); return Py_BuildValue ("i", do_model_compare (wca, wcb)); } static PyObject * cups_setUser (PyObject *self, PyObject *args) { PyObject *userobj; char *user; if (!PyArg_ParseTuple (args, "O", &userobj)) return NULL; if (UTF8_from_PyObj (&user, userobj) == NULL) return NULL; cupsSetUser (user); free (user); Py_RETURN_NONE; } static PyObject * cups_setServer (PyObject *self, PyObject *args) { PyObject *serverobj; char *server; if (!PyArg_ParseTuple (args, "O", &serverobj)) return NULL; if (UTF8_from_PyObj (&server, serverobj) == NULL) return NULL; cupsSetServer (server); free (server); Py_RETURN_NONE; } static PyObject * cups_setPort (PyObject *self, PyObject *args) { int port; if (!PyArg_ParseTuple (args, "i", &port)) return NULL; ippSetPort (port); Py_RETURN_NONE; } static PyObject * cups_setEncryption (PyObject *self, PyObject *args) { int e; if (!PyArg_ParseTuple (args, "i", &e)) return NULL; cupsSetEncryption (e); Py_RETURN_NONE; } static PyObject * cups_getUser (PyObject *self) { return PyUnicode_FromString (cupsUser ()); } static PyObject * cups_getServer (PyObject *self) { return PyUnicode_FromString (cupsServer ()); } static PyObject * cups_getPort (PyObject *self) { return Py_BuildValue ("i", ippPort ()); } static PyObject * cups_getEncryption (PyObject *self) { return Py_BuildValue ("i", cupsEncryption ()); } static PyObject * cups_setPasswordCB (PyObject *self, PyObject *args) { struct TLS *tls = get_TLS (); PyObject *cb; if (!PyArg_ParseTuple (args, "O:cups_setPasswordCB", &cb)) return NULL; if (!PyCallable_Check (cb)) { PyErr_SetString (PyExc_TypeError, "Parameter must be callable"); return NULL; } debugprintf ("-> cups_setPasswordCB\n"); Py_XDECREF (tls->cups_password_callback_context); tls->cups_password_callback_context = NULL; Py_XINCREF (cb); Py_XDECREF (tls->cups_password_callback); tls->cups_password_callback = cb; cupsSetPasswordCB2 (password_callback_oldstyle, NULL); debugprintf ("<- cups_setPasswordCB\n"); Py_RETURN_NONE; } static PyObject * cups_setPasswordCB2 (PyObject *self, PyObject *args) { struct TLS *tls = get_TLS (); PyObject *cb; PyObject *cb_context = NULL; if (!PyArg_ParseTuple (args, "O|O", &cb, &cb_context)) return NULL; if (cb == Py_None && cb_context != NULL) { PyErr_SetString (PyExc_TypeError, "Default callback takes no context"); return NULL; } else if (cb != Py_None && !PyCallable_Check (cb)) { PyErr_SetString (PyExc_TypeError, "Parameter must be callable"); return NULL; } debugprintf ("-> cups_setPasswordCB2\n"); Py_XINCREF (cb_context); Py_XDECREF (tls->cups_password_callback_context); tls->cups_password_callback_context = cb_context; if (cb == Py_None) { Py_XDECREF (tls->cups_password_callback); tls->cups_password_callback = NULL; cupsSetPasswordCB2 (NULL, NULL); } else { Py_XINCREF (cb); Py_XDECREF (tls->cups_password_callback); tls->cups_password_callback = cb; cupsSetPasswordCB2 (password_callback_newstyle, cb_context); } debugprintf ("<- cups_setPasswordCB2\n"); Py_RETURN_NONE; } static PyObject * cups_ppdSetConformance (PyObject *self, PyObject *args) { int level; if (!PyArg_ParseTuple (args, "i", &level)) return NULL; ppdSetConformance (level); Py_RETURN_NONE; } static PyObject * cups_enumDests (PyObject *self, PyObject *args, PyObject *kwds) { PyObject *cb; int flags = 0; int msec = -1; int type = 0; int mask = 0; PyObject *user_data = NULL; CallbackContext context; int ret; static char *kwlist[] = { "cb", "flags", "msec", "type", "mask", "user_data", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|iiiiO", kwlist, &cb, &flags, &msec, &type, &mask, &user_data)) return NULL; if (!PyCallable_Check (cb)) { PyErr_SetString (PyExc_TypeError, "cb must be callable"); return NULL; } if (!user_data) user_data = Py_None; Py_XINCREF (cb); Py_XINCREF (user_data); context.cb = cb; context.user_data = user_data; ret = cupsEnumDests (flags, msec, NULL, type, mask, cups_dest_cb, &context); Py_XDECREF (cb); Py_XDECREF (user_data); if (!ret) { PyErr_SetString (PyExc_RuntimeError, "cupsEnumDests failed"); return NULL; } Py_RETURN_NONE; } static PyObject * cups_connectDest (PyObject *self, PyObject *args, PyObject *kwds) { PyObject *destobj; PyObject *cb; int flags = 0; int msec = -1; PyObject *user_data = NULL; CallbackContext context; char resource[HTTP_MAX_URI]; http_t *conn; Connection *connobj; Dest *dest_o; cups_dest_t dest; PyObject *ret; static char *kwlist[] = { "dest", "cb", "flags", "msec", "user_data", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "OO|iiO", kwlist, &destobj, &cb, &flags, &msec, &user_data)) return NULL; if (Py_TYPE(destobj) != &cups_DestType) { PyErr_SetString (PyExc_TypeError, "dest must be Dest object"); return NULL; } if (!PyCallable_Check (cb)) { PyErr_SetString (PyExc_TypeError, "cb must be callable"); return NULL; } if (!user_data) user_data = Py_None; Py_XINCREF (cb); Py_XINCREF (user_data); context.cb = cb; context.user_data = user_data; resource[0] = '\0'; dest_o = (Dest *) destobj; dest.is_default = dest_o->is_default; dest.name = dest_o->destname; dest.instance = dest_o->instance; dest.num_options = dest_o->num_options; dest.options = malloc (dest_o->num_options * sizeof (dest.options[0])); int i; for (i = 0; i < dest_o->num_options; i++) { dest.options[i].name = dest_o->name[i]; dest.options[i].value = dest_o->value[i]; } conn = cupsConnectDest (&dest, flags, msec, NULL, resource, sizeof (resource), cups_dest_cb, &context); Py_XDECREF (cb); Py_XDECREF (user_data); free (dest.options); if (!conn) { set_ipp_error (cupsLastError (), cupsLastErrorString ()); return NULL; } PyObject *largs = Py_BuildValue ("()"); PyObject *lkwlist = Py_BuildValue ("{}"); connobj = (Connection *) PyType_GenericNew (&cups_ConnectionType, largs, lkwlist); Py_DECREF (largs); Py_DECREF (lkwlist); connobj->host = strdup (""); connobj->http = conn; ret = Py_BuildValue ("(Os)", (PyObject *) connobj, resource); return ret; } static PyObject * cups_ippErrorString (PyObject *self, PyObject *args) { int op; if (!PyArg_ParseTuple (args, "i", &op)) return NULL; return PyUnicode_FromString (ippErrorString (op)); } static PyObject * cups_ippOpString (PyObject *self, PyObject *args) { int op; if (!PyArg_ParseTuple (args, "i", &op)) return NULL; return PyUnicode_FromString (ippOpString (op)); } static PyObject * cups_require (PyObject *self, PyObject *args) { const char *version = VERSION; const char *required; const char *pver, *preq; char *end; unsigned long nreq, nver; if (!PyArg_ParseTuple (args, "s", &required)) return NULL; pver = version; preq = required; nreq = strtoul (preq, &end, 0); while (preq != end) { preq = end; if (*preq == '.') preq++; nver = strtoul (pver, &end, 0); if (pver == end) goto fail; else { pver = end; if (*pver == '.') pver++; } if (nver < nreq) goto fail; if (nver > nreq) goto good; nreq = strtoul (preq, &end, 0); } good: Py_RETURN_NONE; fail: PyErr_SetString (PyExc_RuntimeError, "I am version " VERSION); return NULL; } struct module_state { PyObject *error; }; #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) static PyMethodDef cups_methods[] = { { "modelSort", cups_modelSort, METH_VARARGS, "modelSort(s1,s2) -> integer\n\n" "Sort two model strings.\n\n" "@type s1: string\n" "@param s1: first string\n" "@type s2: string\n" "@param s2: second string\n" "@return: strcmp-style comparison result"}, { "setUser", cups_setUser, METH_VARARGS, "setUser(user) -> None\n\n" "Set user to connect as.\n\n" "@type user: string\n" "@param user: username"}, { "setServer", cups_setServer, METH_VARARGS, "setServer(server) -> None\n\n" "Set server to connect to.\n\n" "@type server: string\n" "@param server: server hostname" }, { "setPort", cups_setPort, METH_VARARGS, "setPort(port) -> None\n\n" "Set IPP port to connect to.\n\n" "@type port: integer\n" "@param port: IPP port" }, { "setEncryption", cups_setEncryption, METH_VARARGS, "setEncryption(policy) -> None\n\n" "Set encryption policy.\n\n" "@type policy: integer\n" "@param policy: L{HTTP_ENCRYPT_ALWAYS}, L{HTTP_ENCRYPT_IF_REQUESTED}, \n" "L{HTTP_ENCRYPT_NEVER}, or L{HTTP_ENCRYPT_REQUIRED}" }, { "getUser", (PyCFunction) cups_getUser, METH_NOARGS, "getUser() -> string\n\n" "@return: user to connect as." }, { "getServer", (PyCFunction) cups_getServer, METH_NOARGS, "getServer() -> string\n\n" "@return: server to connect to." }, { "getPort", (PyCFunction) cups_getPort, METH_NOARGS, "getPort() -> integer\n\n" "@return: IPP port to connect to." }, { "getEncryption", (PyCFunction) cups_getEncryption, METH_NOARGS, "getEncryption() -> integer\n\n" "Get encryption policy.\n" "@see: L{setEncryption}" }, { "setPasswordCB", cups_setPasswordCB, METH_VARARGS, "setPasswordCB(fn) -> None\n\n" "Set password callback function. This Python function will be called \n" "when a password is required. It must take one string parameter \n" "(the password prompt) and it must return a string (the password), or \n" "None to abort the operation.\n\n" "@type fn: callable object\n" "@param fn: callback function" }, { "setPasswordCB2", cups_setPasswordCB2, METH_VARARGS, "setPasswordCB2(fn, context=None) -> None\n\n" "Set password callback function. This Python function will be called \n" "when a password is required. It must take parameters of type string \n" "(the password prompt), instance (the cups.Connection), string (the \n" "HTTP method), string (the HTTP resource) and, optionally, the user-\n" "supplied context. It must return a string (the password), or None \n" "to abort the operation.\n\n" "@type fn: callable object, or None for default handler\n" "@param fn: callback function" }, { "ppdSetConformance", cups_ppdSetConformance, METH_VARARGS, "ppdSetConformance(level) -> None\n\n" "Set PPD conformance level.\n\n" "@type level: integer\n" "@param level: PPD_CONFORM_RELAXED or PPD_CONFORM_STRICT" }, { "enumDests", (PyCFunction) cups_enumDests, METH_VARARGS | METH_KEYWORDS, "enumDests(cb,flags=0,msec=-1,type=0,mask=0,user_data=None) -> None\n\n" "@type cb: callable\n" "@param cb: callback function, given user_data, dest flags, and dest.\n" "Should return 1 to continue enumeration and 0 to cancel.\n" "@type flags: integer\n" "@param flags: enumeration flags\n" "@type msec: integer\n" "@param msec: timeout, or -1 for no timeout\n" "@type type: integer\n" "@param type: bitmask of printer types to return\n" "@type mask: integer\n" "@param mask: bitmask of type bits to examine\n" "@type user_data: object\n" "@param user_data: user data to pass to callback function\n"}, { "connectDest", (PyCFunction) cups_connectDest, METH_VARARGS | METH_KEYWORDS, "connectDest(dest,cb,flags=0,msec=-1,user_data=None) -> (conn, resource)\n\n" "@type dest: Dest object\n" "@param dest: destination to connect to\n" "@type cb: callable\n" "@param cb: callback function, given user_data, dest flags, and dest.\n" "Should return 1 to continue enumeration and 0 to cancel.\n" "@type flags: integer\n" "@param flags: enumeration flags\n" "@type msec: integer\n" "@param msec: timeout, or -1 for no timeout\n" "@type user_data: object\n" "@param user_data: user data to pass to callback function\n" "@return: a 2-tuple of the Connection object and the HTTP resource.\n"}, { "ippErrorString", (PyCFunction) cups_ippErrorString, METH_VARARGS, "ippErrorString(statuscode) -> name\n\n" "@type statuscode: integer\n" "@param statuscode: IPP Request status code\n" "@return: a string describing the status code\n"}, { "ippOpString", (PyCFunction) cups_ippOpString, METH_VARARGS, "ippOpString(op) -> name\n\n" "@type op: integer\n" "@param op: IPP Request operation\n" "@return: a string representing the operation name\n"}, { "require", cups_require, METH_VARARGS, "require(version) -> None\n\n" "Require pycups version.\n\n" "@type version: string\n" "@param version: minimum pycups version required\n" "@raise RuntimeError: requirement not met" }, { NULL, NULL, 0, NULL } }; static int cups_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int cups_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "cups", NULL, sizeof(struct module_state), cups_methods, NULL, cups_traverse, cups_clear, NULL }; #define INITERROR return NULL PyObject * PyInit_cups(void) { PyObject *m = PyModule_Create(&moduledef); if (m == NULL) INITERROR; struct module_state *st = GETSTATE(m); st->error = PyErr_NewException("cups.Error", NULL, NULL); if (st->error == NULL) { Py_DECREF(m); INITERROR; } PyObject *d = PyModule_GetDict (m); PyObject *obj; // Connection type cups_ConnectionType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_ConnectionType) < 0) INITERROR; PyModule_AddObject (m, "Connection", (PyObject *)&cups_ConnectionType); // PPD type cups_PPDType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_PPDType) < 0) INITERROR; PyModule_AddObject (m, "PPD", (PyObject *)&cups_PPDType); // Option type cups_OptionType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_OptionType) < 0) INITERROR; PyModule_AddObject (m, "Option", (PyObject *)&cups_OptionType); // Group type cups_GroupType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_GroupType) < 0) INITERROR; PyModule_AddObject (m, "Group", (PyObject *)&cups_GroupType); // Constraint type cups_ConstraintType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_ConstraintType) < 0) INITERROR; PyModule_AddObject (m, "Constraint", (PyObject *)&cups_ConstraintType); // Attribute type cups_AttributeType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_AttributeType) < 0) INITERROR; PyModule_AddObject (m, "Attribute", (PyObject *)&cups_AttributeType); // Dest type cups_DestType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_DestType) < 0) INITERROR; PyModule_AddObject (m, "Dest", (PyObject *)&cups_DestType); // IPPRequest type cups_IPPRequestType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_IPPRequestType) < 0) INITERROR; PyModule_AddObject (m, "IPPRequest", (PyObject *)&cups_IPPRequestType); // IPPAttribute type cups_IPPAttributeType.tp_new = PyType_GenericNew; if (PyType_Ready (&cups_IPPAttributeType) < 0) INITERROR; PyModule_AddObject (m, "IPPAttribute", (PyObject *)&cups_IPPAttributeType); // Constants # define INT_CONSTANT(name) \ PyDict_SetItemString (d, #name, PyLong_FromLong (name)) # define INT_CONSTANT_AS(name,alias) \ PyDict_SetItemString (d, alias, PyLong_FromLong (name)) # define INT_CONSTANT_ALIAS(name,alias) \ PyDict_SetItemString (d, #name, PyLong_FromLong (name)); \ PyDict_SetItemString (d, alias, PyLong_FromLong (name)) #define STR_CONSTANT(name) \ PyDict_SetItemString (d, #name, PyUnicode_FromString (name)) # define INT_17_CONSTANT(newname,oldname) \ INT_CONSTANT_ALIAS(newname,#oldname) # define INT_17_CONSTANT_NEWNAME(newname,oldname) \ INT_CONSTANT(newname) // CUPS printer types INT_CONSTANT (CUPS_PRINTER_LOCAL); INT_CONSTANT (CUPS_PRINTER_CLASS); INT_CONSTANT (CUPS_PRINTER_REMOTE); INT_CONSTANT (CUPS_PRINTER_BW); INT_CONSTANT (CUPS_PRINTER_COLOR); INT_CONSTANT (CUPS_PRINTER_DUPLEX); INT_CONSTANT (CUPS_PRINTER_STAPLE); INT_CONSTANT (CUPS_PRINTER_COPIES); INT_CONSTANT (CUPS_PRINTER_COLLATE); INT_CONSTANT (CUPS_PRINTER_PUNCH); INT_CONSTANT (CUPS_PRINTER_COVER); INT_CONSTANT (CUPS_PRINTER_BIND); INT_CONSTANT (CUPS_PRINTER_SORT); INT_CONSTANT (CUPS_PRINTER_SMALL); INT_CONSTANT (CUPS_PRINTER_MEDIUM); INT_CONSTANT (CUPS_PRINTER_LARGE); INT_CONSTANT (CUPS_PRINTER_VARIABLE); INT_CONSTANT (CUPS_PRINTER_IMPLICIT); INT_CONSTANT (CUPS_PRINTER_DEFAULT); INT_CONSTANT (CUPS_PRINTER_FAX); INT_CONSTANT (CUPS_PRINTER_REJECTING); INT_CONSTANT (CUPS_PRINTER_DELETE); INT_CONSTANT (CUPS_PRINTER_NOT_SHARED); INT_CONSTANT (CUPS_PRINTER_AUTHENTICATED); INT_CONSTANT (CUPS_PRINTER_COMMANDS); INT_CONSTANT (CUPS_PRINTER_OPTIONS); INT_CONSTANT (CUPS_PRINTER_DISCOVERED); // HTTP encryption INT_CONSTANT (HTTP_ENCRYPT_IF_REQUESTED); INT_CONSTANT (HTTP_ENCRYPT_NEVER); INT_CONSTANT (HTTP_ENCRYPT_REQUIRED); INT_CONSTANT (HTTP_ENCRYPT_ALWAYS); // Document formats STR_CONSTANT (CUPS_FORMAT_AUTO); STR_CONSTANT (CUPS_FORMAT_COMMAND); STR_CONSTANT (CUPS_FORMAT_PDF); STR_CONSTANT (CUPS_FORMAT_POSTSCRIPT); STR_CONSTANT (CUPS_FORMAT_RAW); STR_CONSTANT (CUPS_FORMAT_TEXT); // Selected HTTP status codes /* Also define legacy names */ # define INT_HTTP_STATUS_CONSTANT(name) \ INT_CONSTANT_ALIAS(HTTP_STATUS_##name, "HTTP_"#name) INT_HTTP_STATUS_CONSTANT (ERROR); INT_HTTP_STATUS_CONSTANT (OK); INT_HTTP_STATUS_CONSTANT (NOT_MODIFIED); INT_HTTP_STATUS_CONSTANT (BAD_REQUEST); INT_HTTP_STATUS_CONSTANT (UNAUTHORIZED); INT_HTTP_STATUS_CONSTANT (FORBIDDEN); INT_HTTP_STATUS_CONSTANT (NOT_FOUND); INT_HTTP_STATUS_CONSTANT (REQUEST_TIMEOUT); INT_HTTP_STATUS_CONSTANT (UPGRADE_REQUIRED); INT_HTTP_STATUS_CONSTANT (SERVER_ERROR); INT_HTTP_STATUS_CONSTANT (NOT_IMPLEMENTED); INT_HTTP_STATUS_CONSTANT (BAD_GATEWAY); INT_HTTP_STATUS_CONSTANT (SERVICE_UNAVAILABLE); INT_HTTP_STATUS_CONSTANT (GATEWAY_TIMEOUT); INT_HTTP_STATUS_CONSTANT (NOT_SUPPORTED); INT_17_CONSTANT (HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED, HTTP_AUTHORIZATION_CANCELED); INT_17_CONSTANT (HTTP_STATUS_CUPS_PKI_ERROR, HTTP_PKI_ERROR); // PPD UI enum INT_CONSTANT (PPD_UI_BOOLEAN); INT_CONSTANT (PPD_UI_PICKONE); INT_CONSTANT (PPD_UI_PICKMANY); // PPD Order dependency enum INT_CONSTANT (PPD_ORDER_ANY); INT_CONSTANT (PPD_ORDER_DOCUMENT); INT_CONSTANT (PPD_ORDER_EXIT); INT_CONSTANT (PPD_ORDER_JCL); INT_CONSTANT (PPD_ORDER_PAGE); INT_CONSTANT (PPD_ORDER_PROLOG); // Job states INT_CONSTANT (IPP_JOB_PENDING); INT_CONSTANT (IPP_JOB_HELD); INT_CONSTANT (IPP_JOB_PROCESSING); INT_CONSTANT (IPP_JOB_STOPPED); INT_CONSTANT (IPP_JOB_CANCELED); INT_CONSTANT (IPP_JOB_ABORTED); INT_CONSTANT (IPP_JOB_COMPLETED); // Printer states INT_CONSTANT (IPP_PRINTER_IDLE); INT_CONSTANT (IPP_PRINTER_PROCESSING); INT_CONSTANT (IPP_PRINTER_STOPPED); // IPP resolution units INT_CONSTANT (IPP_RES_PER_CM); INT_CONSTANT (IPP_RES_PER_INCH); // IPP finishings INT_CONSTANT (IPP_FINISHINGS_NONE); INT_CONSTANT (IPP_FINISHINGS_STAPLE); INT_CONSTANT (IPP_FINISHINGS_PUNCH); INT_CONSTANT (IPP_FINISHINGS_COVER); INT_CONSTANT (IPP_FINISHINGS_BIND); INT_CONSTANT (IPP_FINISHINGS_SADDLE_STITCH); INT_CONSTANT (IPP_FINISHINGS_EDGE_STITCH); INT_CONSTANT (IPP_FINISHINGS_FOLD); INT_CONSTANT (IPP_FINISHINGS_TRIM); INT_CONSTANT (IPP_FINISHINGS_BALE); INT_CONSTANT (IPP_FINISHINGS_BOOKLET_MAKER); INT_CONSTANT (IPP_FINISHINGS_JOB_OFFSET); INT_CONSTANT (IPP_FINISHINGS_STAPLE_TOP_LEFT); INT_CONSTANT (IPP_FINISHINGS_STAPLE_BOTTOM_LEFT); INT_CONSTANT (IPP_FINISHINGS_STAPLE_TOP_RIGHT); INT_CONSTANT (IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT); INT_CONSTANT (IPP_FINISHINGS_EDGE_STITCH_LEFT); INT_CONSTANT (IPP_FINISHINGS_EDGE_STITCH_TOP); INT_CONSTANT (IPP_FINISHINGS_EDGE_STITCH_RIGHT); INT_CONSTANT (IPP_FINISHINGS_EDGE_STITCH_BOTTOM); INT_CONSTANT (IPP_FINISHINGS_STAPLE_DUAL_LEFT); INT_CONSTANT (IPP_FINISHINGS_STAPLE_DUAL_TOP); INT_CONSTANT (IPP_FINISHINGS_STAPLE_DUAL_RIGHT); INT_CONSTANT (IPP_FINISHINGS_STAPLE_DUAL_BOTTOM); INT_CONSTANT (IPP_FINISHINGS_BIND_LEFT); INT_CONSTANT (IPP_FINISHINGS_BIND_TOP); INT_CONSTANT (IPP_FINISHINGS_BIND_RIGHT); INT_CONSTANT (IPP_FINISHINGS_BIND_BOTTOM); // IPP orientations /* Also define legacy names */ # define INT_IPP_ORIENT_CONSTANT(name) \ INT_CONSTANT_ALIAS(IPP_ORIENT_##name, "IPP_"#name) INT_IPP_ORIENT_CONSTANT (PORTRAIT); INT_IPP_ORIENT_CONSTANT (LANDSCAPE); INT_IPP_ORIENT_CONSTANT (REVERSE_PORTRAIT); INT_IPP_ORIENT_CONSTANT (REVERSE_LANDSCAPE); // IPP qualities INT_CONSTANT (IPP_QUALITY_DRAFT); INT_CONSTANT (IPP_QUALITY_NORMAL); INT_CONSTANT (IPP_QUALITY_HIGH); // IPP errors /* Also define legacy names */ # define INT_IPP_STATUS_ERROR_CONSTANT(name) \ INT_CONSTANT_ALIAS(IPP_STATUS_ERROR_##name, "IPP_"#name) # define INT_IPP_STATUS_OK_CONSTANT(name) \ INT_CONSTANT_ALIAS(IPP_STATUS_##name, "IPP_"#name) INT_IPP_STATUS_OK_CONSTANT (OK); INT_17_CONSTANT (IPP_STATUS_OK_IGNORED_OR_SUBSTITUTED, IPP_OK_SUBST); INT_17_CONSTANT (IPP_STATUS_OK_CONFLICTING, IPP_OK_CONFLICT); INT_IPP_STATUS_OK_CONSTANT (OK_IGNORED_SUBSCRIPTIONS); INT_IPP_STATUS_OK_CONSTANT (OK_IGNORED_NOTIFICATIONS); INT_IPP_STATUS_OK_CONSTANT (OK_TOO_MANY_EVENTS); INT_IPP_STATUS_OK_CONSTANT (OK_BUT_CANCEL_SUBSCRIPTION); INT_IPP_STATUS_OK_CONSTANT (OK_EVENTS_COMPLETE); INT_17_CONSTANT (IPP_STATUS_REDIRECTION_OTHER_SITE, IPP_REDIRECTION_OTHER_SITE); INT_IPP_STATUS_ERROR_CONSTANT (BAD_REQUEST); INT_IPP_STATUS_ERROR_CONSTANT (FORBIDDEN); INT_IPP_STATUS_ERROR_CONSTANT (NOT_AUTHENTICATED); INT_IPP_STATUS_ERROR_CONSTANT (NOT_AUTHORIZED); INT_IPP_STATUS_ERROR_CONSTANT (NOT_POSSIBLE); INT_IPP_STATUS_ERROR_CONSTANT (TIMEOUT); INT_IPP_STATUS_ERROR_CONSTANT (NOT_FOUND); INT_IPP_STATUS_ERROR_CONSTANT (GONE); INT_IPP_STATUS_ERROR_CONSTANT (REQUEST_ENTITY); INT_IPP_STATUS_ERROR_CONSTANT (REQUEST_VALUE); INT_17_CONSTANT (IPP_STATUS_ERROR_DOCUMENT_FORMAT_NOT_SUPPORTED, IPP_DOCUMENT_FORMAT); INT_17_CONSTANT (IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES, IPP_ATTRIBUTES); INT_IPP_STATUS_ERROR_CONSTANT (URI_SCHEME); INT_IPP_STATUS_ERROR_CONSTANT (CHARSET); INT_17_CONSTANT (IPP_STATUS_ERROR_CONFLICTING, IPP_CONFLICT); INT_IPP_STATUS_ERROR_CONSTANT (COMPRESSION_NOT_SUPPORTED); INT_IPP_STATUS_ERROR_CONSTANT (COMPRESSION_ERROR); INT_IPP_STATUS_ERROR_CONSTANT (DOCUMENT_FORMAT_ERROR); INT_17_CONSTANT (IPP_STATUS_ERROR_DOCUMENT_ACCESS, IPP_DOCUMENT_ACCESS_ERROR); INT_IPP_STATUS_ERROR_CONSTANT (ATTRIBUTES_NOT_SETTABLE); INT_IPP_STATUS_ERROR_CONSTANT (IGNORED_ALL_SUBSCRIPTIONS); INT_IPP_STATUS_ERROR_CONSTANT (TOO_MANY_SUBSCRIPTIONS); INT_IPP_STATUS_ERROR_CONSTANT (IGNORED_ALL_NOTIFICATIONS); INT_IPP_STATUS_ERROR_CONSTANT (PRINT_SUPPORT_FILE_NOT_FOUND); INT_17_CONSTANT (IPP_STATUS_ERROR_INTERNAL, IPP_INTERNAL_ERROR); INT_IPP_STATUS_ERROR_CONSTANT (OPERATION_NOT_SUPPORTED); INT_IPP_STATUS_ERROR_CONSTANT (SERVICE_UNAVAILABLE); INT_IPP_STATUS_ERROR_CONSTANT (VERSION_NOT_SUPPORTED); INT_17_CONSTANT (IPP_STATUS_ERROR_DEVICE, IPP_DEVICE_ERROR); INT_17_CONSTANT (IPP_STATUS_ERROR_TEMPORARY, IPP_TEMPORARY_ERROR); INT_17_CONSTANT (IPP_STATUS_ERROR_NOT_ACCEPTING_JOBS, IPP_NOT_ACCEPTING); INT_17_CONSTANT (IPP_STATUS_ERROR_BUSY, IPP_PRINTER_BUSY); INT_17_CONSTANT (IPP_STATUS_ERROR_JOB_CANCELED, IPP_ERROR_JOB_CANCELED); INT_IPP_STATUS_ERROR_CONSTANT (MULTIPLE_JOBS_NOT_SUPPORTED); INT_IPP_STATUS_ERROR_CONSTANT (PRINTER_IS_DEACTIVATED); INT_17_CONSTANT (IPP_STATUS_ERROR_CUPS_AUTHENTICATION_CANCELED, IPP_AUTHENTICATION_CANCELED); INT_17_CONSTANT (IPP_STATUS_ERROR_CUPS_PKI, IPP_PKI_ERROR); INT_17_CONSTANT (IPP_STATUS_ERROR_CUPS_UPGRADE_REQUIRED, IPP_UPGRADE_REQUIRED); // IPP states /* Also define legacy names */ # define INT_IPP_STATE_CONSTANT(name) \ INT_CONSTANT_ALIAS(IPP_STATE_##name, "IPP_"#name) INT_IPP_STATE_CONSTANT (ERROR); INT_IPP_STATE_CONSTANT (IDLE); INT_IPP_STATE_CONSTANT (HEADER); INT_IPP_STATE_CONSTANT (ATTRIBUTE); INT_IPP_STATE_CONSTANT (DATA); // IPP attribute tags INT_CONSTANT (IPP_TAG_ZERO); INT_CONSTANT (IPP_TAG_OPERATION); INT_CONSTANT (IPP_TAG_JOB); INT_CONSTANT (IPP_TAG_PRINTER); INT_CONSTANT (IPP_TAG_INTEGER); INT_CONSTANT (IPP_TAG_BOOLEAN); INT_CONSTANT (IPP_TAG_ENUM); INT_CONSTANT (IPP_TAG_STRING); INT_CONSTANT (IPP_TAG_RANGE); INT_CONSTANT (IPP_TAG_TEXT); INT_CONSTANT (IPP_TAG_NAME); INT_CONSTANT (IPP_TAG_KEYWORD); INT_CONSTANT (IPP_TAG_URI); INT_CONSTANT (IPP_TAG_CHARSET); INT_CONSTANT (IPP_TAG_LANGUAGE); INT_CONSTANT (IPP_TAG_MIMETYPE); // IPP operations # define INT_IPP_OP_CONSTANT(name) \ INT_CONSTANT(IPP_OP_##name) INT_IPP_OP_CONSTANT (PRINT_JOB); INT_IPP_OP_CONSTANT (PRINT_URI); INT_IPP_OP_CONSTANT (VALIDATE_JOB); INT_IPP_OP_CONSTANT (CREATE_JOB); INT_IPP_OP_CONSTANT (SEND_DOCUMENT); INT_IPP_OP_CONSTANT (SEND_URI); INT_IPP_OP_CONSTANT (CANCEL_JOB); INT_IPP_OP_CONSTANT (GET_JOB_ATTRIBUTES); INT_IPP_OP_CONSTANT (GET_JOBS); INT_IPP_OP_CONSTANT (GET_PRINTER_ATTRIBUTES); INT_IPP_OP_CONSTANT (HOLD_JOB); INT_IPP_OP_CONSTANT (RELEASE_JOB); INT_IPP_OP_CONSTANT (RESTART_JOB); INT_IPP_OP_CONSTANT (PAUSE_PRINTER); INT_IPP_OP_CONSTANT (RESUME_PRINTER); INT_IPP_OP_CONSTANT (PURGE_JOBS); INT_IPP_OP_CONSTANT (SET_PRINTER_ATTRIBUTES); INT_IPP_OP_CONSTANT (SET_JOB_ATTRIBUTES); INT_IPP_OP_CONSTANT (GET_PRINTER_SUPPORTED_VALUES); INT_17_CONSTANT (IPP_OP_CREATE_PRINTER_SUBSCRIPTIONS, IPP_CREATE_PRINTER_SUBSCRIPTION); INT_17_CONSTANT (IPP_OP_CREATE_JOB_SUBSCRIPTIONS, IPP_CREATE_JOB_SUBSCRIPTION); INT_IPP_OP_CONSTANT (GET_SUBSCRIPTIONS); INT_IPP_OP_CONSTANT (RENEW_SUBSCRIPTION); INT_IPP_OP_CONSTANT (CANCEL_SUBSCRIPTION); INT_IPP_OP_CONSTANT (GET_NOTIFICATIONS); INT_IPP_OP_CONSTANT (SEND_NOTIFICATIONS); INT_IPP_OP_CONSTANT (GET_RESOURCE_ATTRIBUTES); INT_IPP_OP_CONSTANT (GET_RESOURCE_DATA); INT_IPP_OP_CONSTANT (GET_RESOURCES); INT_IPP_OP_CONSTANT (GET_PRINT_SUPPORT_FILES); INT_IPP_OP_CONSTANT (ENABLE_PRINTER); INT_IPP_OP_CONSTANT (DISABLE_PRINTER); INT_IPP_OP_CONSTANT (PAUSE_PRINTER_AFTER_CURRENT_JOB); INT_IPP_OP_CONSTANT (HOLD_NEW_JOBS); INT_IPP_OP_CONSTANT (RELEASE_HELD_NEW_JOBS); INT_IPP_OP_CONSTANT (DEACTIVATE_PRINTER); INT_IPP_OP_CONSTANT (ACTIVATE_PRINTER); INT_IPP_OP_CONSTANT (RESTART_PRINTER); INT_IPP_OP_CONSTANT (SHUTDOWN_PRINTER); INT_IPP_OP_CONSTANT (STARTUP_PRINTER); INT_IPP_OP_CONSTANT (REPROCESS_JOB); INT_IPP_OP_CONSTANT (CANCEL_CURRENT_JOB); INT_IPP_OP_CONSTANT (SUSPEND_CURRENT_JOB); INT_IPP_OP_CONSTANT (RESUME_JOB); INT_IPP_OP_CONSTANT (PROMOTE_JOB); INT_IPP_OP_CONSTANT (SCHEDULE_JOB_AFTER); INT_IPP_OP_CONSTANT (CANCEL_JOBS); INT_IPP_OP_CONSTANT (CANCEL_MY_JOBS); INT_IPP_OP_CONSTANT (RESUBMIT_JOB); INT_IPP_OP_CONSTANT (CLOSE_JOB); INT_IPP_OP_CONSTANT (IDENTIFY_PRINTER); INT_IPP_OP_CONSTANT (VALIDATE_DOCUMENT); INT_IPP_OP_CONSTANT (SEND_HARDCOPY_DOCUMENT); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_GET_DEFAULT, CUPS_GET_DEFAULT); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_GET_PRINTERS, CUPS_GET_PRINTERS); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_ADD_MODIFY_PRINTER, CUPS_ADD_MODIFY_PRINTER); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_DELETE_PRINTER, CUPS_DELETE_PRINTER); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_GET_CLASSES, CUPS_GET_CLASSES); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_ADD_MODIFY_CLASS, CUPS_ADD_MODIFY_CLASS); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_DELETE_CLASS, CUPS_DELETE_CLASS); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_ACCEPT_JOBS, CUPS_ACCEPT_JOBS); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_REJECT_JOBS, CUPS_REJECT_JOBS); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_SET_DEFAULT, CUPS_SET_DEFAULT); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_GET_PPDS, CUPS_GET_PPDS); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_MOVE_JOB, CUPS_MOVE_JOB); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_AUTHENTICATE_JOB, CUPS_AUTHENTICATE_JOB); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_GET_PPD, CUPS_GET_PPD); INT_17_CONSTANT_NEWNAME (IPP_OP_CUPS_GET_DOCUMENT, CUPS_GET_DOCUMENT); // Limits INT_CONSTANT (IPP_MAX_NAME); // PPD conformance levels INT_CONSTANT (PPD_CONFORM_RELAXED); INT_CONSTANT (PPD_CONFORM_STRICT); // Admin Util constants STR_CONSTANT (CUPS_SERVER_DEBUG_LOGGING); STR_CONSTANT (CUPS_SERVER_REMOTE_ADMIN); STR_CONSTANT (CUPS_SERVER_REMOTE_PRINTERS); STR_CONSTANT (CUPS_SERVER_SHARE_PRINTERS); STR_CONSTANT (CUPS_SERVER_USER_CANCEL_ANY); STR_CONSTANT (CUPS_SERVER_REMOTE_ANY); // Dest enumeration flags INT_CONSTANT (CUPS_DEST_FLAGS_NONE); INT_CONSTANT (CUPS_DEST_FLAGS_UNCONNECTED); INT_CONSTANT (CUPS_DEST_FLAGS_MORE); INT_CONSTANT (CUPS_DEST_FLAGS_REMOVED); INT_CONSTANT (CUPS_DEST_FLAGS_ERROR); INT_CONSTANT (CUPS_DEST_FLAGS_RESOLVING); INT_CONSTANT (CUPS_DEST_FLAGS_CONNECTING); INT_CONSTANT (CUPS_DEST_FLAGS_CANCELED); // Exceptions obj = PyDict_New (); PyDict_SetItemString (obj, "__doc__", PyUnicode_FromString( "This exception is raised when an HTTP problem has occurred. It \n" "provides an integer HTTP status code.\n\n" "Use it like this::\n" " try:\n" " ...\n" " except cups.HTTPError as (status):\n" " print 'HTTP status is %d' % status\n")); HTTPError = PyErr_NewException ("cups.HTTPError", NULL, obj); Py_DECREF (obj); if (HTTPError == NULL) INITERROR; Py_INCREF (HTTPError); PyModule_AddObject (m, "HTTPError", HTTPError); obj = PyDict_New (); PyDict_SetItemString (obj, "__doc__", PyUnicode_FromString( "This exception is raised when an IPP error has occurred. It \n" "provides an integer IPP status code, and a human-readable string \n" "describing the error.\n\n" "Use it like this::\n" " try:\n" " ...\n" " except cups.IPPError as (status, description):\n" " print 'IPP status is %d' % status\n" " print 'Meaning:', description\n")); IPPError = PyErr_NewException ("cups.IPPError", NULL, obj); Py_DECREF (obj); if (IPPError == NULL) INITERROR; Py_INCREF (IPPError); PyModule_AddObject (m, "IPPError", IPPError); return m; } /////////////// // Debugging // /////////////// #define ENVAR "PYCUPS_DEBUG" static int debugging_enabled = -1; void debugprintf (const char *fmt, ...) { if (!debugging_enabled) return; if (debugging_enabled == -1) { if (!getenv (ENVAR)) { debugging_enabled = 0; return; } debugging_enabled = 1; } { va_list ap; va_start (ap, fmt); vfprintf (stderr, fmt, ap); va_end (ap); } } pycups-2.0.4/cupsmodule.h000066400000000000000000000031741461013555200154000ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2006-2020 Tim Waugh * Authors: Tim Waugh * Zdenek Dohnal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef HAVE_CUPSMODULE_H #define HAVE_CUPSMODULE_H #include #include #include /* GCC attributes */ #if !defined(__GNUC__) || __GNUC__ < 2 || \ (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__ # define FORMAT(x) #else /* GNU C: */ # define FORMAT(x) __attribute__ ((__format__ x)) #endif extern void debugprintf (const char *fmt, ...) FORMAT ((__printf__, 1, 2)); struct TLS { PyObject *cups_password_callback; PyObject *cups_password_callback_context; }; extern struct TLS *get_TLS (void); typedef struct { PyObject *cb; PyObject *user_data; } CallbackContext; extern const char * UTF8_from_PyObj (char **const utf8, PyObject *obj); #endif /* HAVE_CUPSMODULE_H */ pycups-2.0.4/cupsppd.c000066400000000000000000001333661461013555200147000ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Tim Waugh * Authors: Tim Waugh * Zdenek Dohnal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "cupsppd.h" #include "cupsmodule.h" #include #include #include typedef struct { PyObject_HEAD ppd_option_t *option; PPD *ppd; } Option; typedef struct { PyObject_HEAD ppd_const_t *constraint; PPD *ppd; } Constraint; typedef struct { PyObject_HEAD ppd_group_t *group; PPD *ppd; } Group; typedef struct { PyObject_HEAD ppd_attr_t *attribute; PPD *ppd; } Attribute; ///////////////////////// // Encoding conversion // ///////////////////////// static int ppd_encoding_is_utf8 (PPD *ppd) { const char *lang_encoding, *from_encoding; iconv_t cdf, cdt; if (ppd->conv_from != NULL) return 0; lang_encoding = ppd->ppd->lang_encoding; if (lang_encoding && !strcasecmp (lang_encoding, "UTF-8")) return 1; if (lang_encoding && !strcasecmp (lang_encoding, "ISOLatin1")) from_encoding = "ISO-8859-1"; else if (lang_encoding && !strcasecmp (lang_encoding, "ISOLatin2")) from_encoding = "ISO-8859-2"; else if (lang_encoding && !strcasecmp (lang_encoding, "ISOLatin5")) from_encoding = "ISO-8859-5"; else if (lang_encoding && !strcasecmp (lang_encoding, "JIS83-RKSJ")) from_encoding = "SHIFT-JIS"; else if (lang_encoding && !strcasecmp (lang_encoding, "MacStandard")) from_encoding = "MACINTOSH"; else if (lang_encoding && !strcasecmp (lang_encoding, "WindowsANSI")) from_encoding = "WINDOWS-1252"; else // Guess from_encoding = "ISO-8859-1"; cdf = iconv_open ("UTF-8", from_encoding); if (cdf == (iconv_t) -1) cdf = iconv_open ("UTF-8", "ISO-8859-1"); cdt = iconv_open (from_encoding, "UTF-8"); if (cdt == (iconv_t) -1) cdt = iconv_open ("ISO-8859-1", "UTF-8"); ppd->conv_from = malloc (sizeof (iconv_t)); *ppd->conv_from = cdf; ppd->conv_to = malloc (sizeof (iconv_t)); *ppd->conv_to = cdt; return 0; } static PyObject * cautious_PyUnicode_DecodeUTF8 (const char *str, size_t len) { PyObject *ret = PyUnicode_DecodeUTF8 (str, len, NULL); if (ret == NULL) { // It wasn't UTF-8 after all. Just make the string safe for ASCII. char *safe; size_t i; PyErr_Clear (); safe = malloc (len + 1); for (i = 0; i < len; i++) { unsigned char ch = str[i]; if (!isascii (ch)) ch = '?'; safe[i] = ch; } safe[i] = '\0'; ret = PyUnicode_DecodeUTF8 (safe, len, NULL); printf ("Bad UTF-8 string \"%s\" changed to \"%s\"\n", str, safe); free (safe); } return ret; } static PyObject * make_PyUnicode_from_ppd_string (PPD *ppd, const char *ppdstr) { iconv_t cdf; size_t len; char *outbuf, *outbufptr; size_t outbytesleft; size_t origleft; PyObject *ret; if (ppd_encoding_is_utf8 (ppd)) return cautious_PyUnicode_DecodeUTF8 (ppdstr, strlen (ppdstr)); cdf = *ppd->conv_from; // Reset to initial state iconv (cdf, NULL, NULL, NULL, NULL); len = strlen (ppdstr); // CUPS doesn't keep track of string lengths origleft = outbytesleft = MB_CUR_MAX * len; outbufptr = outbuf = malloc (outbytesleft); if (iconv (cdf, (char **) &ppdstr, &len, &outbufptr, &outbytesleft) == (size_t) -1) { free (outbuf); return PyErr_SetFromErrno (PyExc_RuntimeError); } ret = cautious_PyUnicode_DecodeUTF8 (outbuf, origleft - outbytesleft); free (outbuf); return ret; } static char * utf8_to_ppd_encoding (PPD *ppd, const char *inbuf) { char *outbuf, *ret; size_t len, outsize, outbytesleft; iconv_t cdt; if (ppd_encoding_is_utf8 (ppd)) return strdup (inbuf); cdt = *ppd->conv_to; // Reset to initial state iconv (cdt, NULL, NULL, NULL, NULL); len = strlen (inbuf); outsize = 1 + 6 * len; outbytesleft = outsize - 1; ret = outbuf = malloc (outsize); if (iconv (cdt, (char **) &inbuf, &len, &outbuf, &outbytesleft) == (size_t) -1) { free (outbuf); return NULL; } *outbuf = '\0'; return ret; } ///////// // PPD // ///////// static PyObject * PPD_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { PPD *self; self = (PPD *) type->tp_alloc (type, 0); if (self != NULL) { self->ppd = NULL; self->file = NULL; self->conv_from = NULL; self->conv_to = NULL; } return (PyObject *) self; } static int PPD_init (PPD *self, PyObject *args, PyObject *kwds) { PyObject *filenameobj; char *filename; if (!PyArg_ParseTuple (args, "O", &filenameobj)) return -1; if (UTF8_from_PyObj (&filename, filenameobj) == NULL) return -1; self->file = fopen (filename, "r"); if (!self->file) { PyErr_SetString (PyExc_RuntimeError, "fopen failed"); free (filename); return -1; } debugprintf ("+ PPD %p %s (fd %d)\n", self, filename, fileno (self->file)); self->ppd = ppdOpenFile (filename); free (filename); if (!self->ppd) { fclose (self->file); self->file = NULL; PyErr_SetString (PyExc_RuntimeError, "ppdOpenFile failed"); return -1; } self->conv_from = self->conv_to = NULL; return 0; } static void PPD_dealloc (PPD *self) { if (self->file) { debugprintf ("- PPD %p (fd %d)\n", self, fileno (self->file)); fclose (self->file); } else debugprintf ("- PPD %p (no fd)\n", self); if (self->ppd) ppdClose (self->ppd); if (self->conv_from) iconv_close (*self->conv_from); if (self->conv_to) iconv_close (*self->conv_to); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } ///////// // PPD // METHODS ///////// static PyObject * PPD_localize (PPD *self) { if (!ppdLocalize (self->ppd)) Py_RETURN_NONE; return PyErr_SetFromErrno (PyExc_RuntimeError); } static PyObject * PPD_localizeIPPReason (PPD *self, PyObject *args, PyObject *kwds) { PyObject *ret; PyObject *reasonobj; PyObject *schemeobj = NULL; char *reason; char *scheme = NULL; char *buffer; const size_t bufsize = 1024; static char *kwlist[] = { "reason", "scheme", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|O", kwlist, &reasonobj, &schemeobj)) return NULL; if (UTF8_from_PyObj (&reason, reasonobj) == NULL) return NULL; if (schemeobj) if (UTF8_from_PyObj (&scheme, schemeobj) == NULL) { free (reason); return NULL; } buffer = malloc (bufsize); if (ppdLocalizeIPPReason (self->ppd, reason, scheme, buffer, bufsize)) { ret = make_PyUnicode_from_ppd_string (self, buffer); } else { Py_RETURN_NONE; } free (reason); if (scheme) free (scheme); free (buffer); return ret; } static PyObject * PPD_localizeMarkerName (PPD *self, PyObject *args) { PyObject *ret; PyObject *nameobj; char *name; const char *lname; if (!PyArg_ParseTuple (args, "O", &nameobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; lname = ppdLocalizeMarkerName (self->ppd, name); free (name); if (lname != NULL) { ret = make_PyUnicode_from_ppd_string (self, lname); } else { Py_RETURN_NONE; } return ret; } static PyObject * PPD_markDefaults (PPD *self) { ppdMarkDefaults (self->ppd); Py_RETURN_NONE; } static PyObject * PPD_markOption (PPD *self, PyObject *args) { int conflicts; char *name, *value; char *encname, *encvalue; if (!PyArg_ParseTuple (args, "eses", "UTF-8", &name, "UTF-8", &value)) return NULL; encname = utf8_to_ppd_encoding (self, name); PyMem_Free (name); if (!encname) { PyMem_Free (value); return PyErr_SetFromErrno (PyExc_RuntimeError); } encvalue = utf8_to_ppd_encoding (self, value); PyMem_Free (value); if (!encvalue) { free (encname); return PyErr_SetFromErrno (PyExc_RuntimeError); } conflicts = ppdMarkOption (self->ppd, encname, encvalue); free (encname); free (encvalue); return Py_BuildValue ("i", conflicts); } static PyObject * PPD_conflicts (PPD *self) { return PyLong_FromLong (ppdConflicts (self->ppd)); } static PyObject * PPD_findOption (PPD *self, PyObject *args) { PyObject *ret; PyObject *optionobj; char *option; ppd_option_t *opt; if (!PyArg_ParseTuple (args, "O", &optionobj)) return NULL; if (UTF8_from_PyObj (&option, optionobj) == NULL) return NULL; opt = ppdFindOption (self->ppd, option); free (option); if (opt) { PyObject *args = Py_BuildValue ("()"); PyObject *kwlist = Py_BuildValue ("{}"); Option *optobj = (Option *) PyType_GenericNew (&cups_OptionType, args, kwlist); Py_DECREF (args); Py_DECREF (kwlist); optobj->option = opt; optobj->ppd = self; Py_INCREF (self); ret = (PyObject *) optobj; } else { Py_RETURN_NONE; } return ret; } static PyObject * PPD_findAttr (PPD *self, PyObject *args, PyObject *kwds) { PyObject *ret; PyObject *nameobj; PyObject *specobj = NULL; char *name; char *spec = NULL; ppd_attr_t *attr; static char *kwlist[] = { "name", "spec", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|O", kwlist, &nameobj, &specobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (specobj) if (UTF8_from_PyObj (&spec, specobj) == NULL) { free (name); return NULL; } attr = ppdFindAttr (self->ppd, name, spec); free (name); if (spec) free (spec); if (attr) { PyObject *largs = Py_BuildValue ("()"); PyObject *lkwlist = Py_BuildValue ("{}"); Attribute *attrobj = (Attribute *) PyType_GenericNew (&cups_AttributeType, largs, lkwlist); Py_DECREF (largs); Py_DECREF (lkwlist); attrobj->attribute = attr; attrobj->ppd = self; Py_INCREF (self); ret = (PyObject *) attrobj; } else { Py_RETURN_NONE; } return ret; } static PyObject * PPD_findNextAttr (PPD *self, PyObject *args, PyObject *kwds) { PyObject *ret; PyObject *nameobj; PyObject *specobj = NULL; char *name; char *spec = NULL; ppd_attr_t *attr; static char *kwlist[] = { "name", "spec", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|O", kwlist, &nameobj, &specobj)) return NULL; if (UTF8_from_PyObj (&name, nameobj) == NULL) return NULL; if (specobj) if (UTF8_from_PyObj (&spec, specobj) == NULL) { free (name); return NULL; } attr = ppdFindNextAttr (self->ppd, name, spec); free (name); if (spec) free (spec); if (attr) { PyObject *largs = Py_BuildValue ("()"); PyObject *lkwlist = Py_BuildValue ("{}"); Attribute *attrobj = (Attribute *) PyType_GenericNew (&cups_AttributeType, largs, lkwlist); Py_DECREF (largs); Py_DECREF (lkwlist); attrobj->attribute = attr; attrobj->ppd = self; Py_INCREF (self); ret = (PyObject *) attrobj; } else { Py_RETURN_NONE; } return ret; } static int nondefaults_are_marked (ppd_group_t *g) { ppd_option_t *o; int oi; for (oi = 0, o = g->options; oi < g->num_options; oi++, o++) { ppd_choice_t *c; int ci; for (ci = 0, c = o->choices; ci < o->num_choices; ci++, c++) { if (c->marked) { if (strcmp (c->choice, o->defchoice)) return 1; break; } } } return 0; } static PyObject * PPD_nondefaultsMarked (PPD *self) { int nondefaults_marked = 0; ppd_group_t *g; int gi; for (gi = 0, g = self->ppd->groups; gi < self->ppd->num_groups && !nondefaults_marked; gi++, g++) { ppd_group_t *sg; int sgi; if (nondefaults_are_marked (g)) { nondefaults_marked = 1; break; } for (sgi = 0, sg = g->subgroups; sgi < g->num_subgroups; sgi++, sg++) { if (nondefaults_are_marked (sg)) { nondefaults_marked = 1; break; } } } return PyBool_FromLong (nondefaults_marked); } #if !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) /* * A rudimentary emulation of getline() for systems that dont support it * natively. Since this is used for PPD file reading, it assumes (possibly * falsely) that BUFSIZ is big enough. */ ssize_t getline(char **line, size_t *linelen, FILE *fp) { if (*linelen == 0) { *linelen = BUFSIZ; *line = malloc(*linelen); } memset(*line, 0, *linelen); fgets(*line, *linelen, fp); return (strlen(*line)); } #endif /* * emit marked options by returning a string. */ static PyObject * PPD_emitString (PPD *self, PyObject *args) { ppd_section_t section; float min_order; char *emitted; PyObject *ret; if (!PyArg_ParseTuple (args, "if", §ion, &min_order)) return NULL; emitted = ppdEmitString(self->ppd, section, min_order); if (emitted) { ret = PyUnicode_FromString (emitted); free (emitted); } else { Py_RETURN_NONE; } return ret; } /* * emit marked options by writing to a file object. */ static PyObject * PPD_emit (PPD *self, PyObject *args) { PyObject *pyFile; ppd_section_t section; FILE *f; if (!PyArg_ParseTuple (args, "Oi", &pyFile, §ion)) return NULL; int fd = PyObject_AsFileDescriptor(pyFile); f = fdopen(fd, "w"); if (!f) return PyErr_SetFromErrno (PyExc_RuntimeError); if (!ppdEmit(self->ppd, f, section)) Py_RETURN_NONE; return PyErr_SetFromErrno (PyExc_RuntimeError); } /* * emit marked options after order dependency by writing to a file object. */ static PyObject * PPD_emitAfterOrder (PPD *self, PyObject *args) { PyObject *pyFile; ppd_section_t section; FILE *f; int limit; float min_order; if (!PyArg_ParseTuple (args, "Oiif", &pyFile, §ion, &limit, &min_order)) return NULL; int fd = PyObject_AsFileDescriptor(pyFile); f = fdopen(fd, "w"); if (!f) return PyErr_SetFromErrno (PyExc_RuntimeError); if (!ppdEmitAfterOrder(self->ppd, f, section, limit, min_order)) Py_RETURN_NONE; return PyErr_SetFromErrno (PyExc_RuntimeError); } /* * emit marked options by writing to a file descriptor. */ static PyObject * PPD_emitFd (PPD *self, PyObject *args) { ppd_section_t section; int f; if (!PyArg_ParseTuple (args, "ii", &f, §ion)) return NULL; if (!ppdEmitFd(self->ppd, f, section)) Py_RETURN_NONE; return PyErr_SetFromErrno (PyExc_RuntimeError); } /* * emit JCL options by writing to a file object. */ static PyObject * PPD_emitJCL (PPD *self, PyObject *args) { PyObject *pyFile; int job_id; PyObject *userobj; PyObject *titleobj; char *user; char *title; FILE *f; if (!PyArg_ParseTuple (args, "OiOO", &pyFile, &job_id, &userobj, &titleobj)) return NULL; if (UTF8_from_PyObj (&user, userobj) == NULL) return NULL; if (UTF8_from_PyObj (&title, titleobj) == NULL) { free (user); return NULL; } int fd = PyObject_AsFileDescriptor(pyFile); f = fdopen(fd, "w"); if (!f) return PyErr_SetFromErrno (PyExc_RuntimeError); if (!ppdEmitJCL(self->ppd, f, job_id, user, title)) Py_RETURN_NONE; free (user); free (title); return PyErr_SetFromErrno (PyExc_RuntimeError); } /* * emit JCL end by writing to a file object. */ static PyObject * PPD_emitJCLEnd (PPD *self, PyObject *args) { PyObject *pyFile; FILE *f; if (!PyArg_ParseTuple (args, "O", &pyFile)) return NULL; int fd = PyObject_AsFileDescriptor(pyFile); f = fdopen(fd, "w"); if (!f) return PyErr_SetFromErrno (PyExc_RuntimeError); if (!ppdEmitJCLEnd(self->ppd, f)) Py_RETURN_NONE; return PyErr_SetFromErrno (PyExc_RuntimeError); } PyObject * PPD_writeFd (PPD *self, PyObject *args) { char *line = NULL; size_t linelen = 0; FILE *out; int fd; int dfd; if (!PyArg_ParseTuple (args, "i", &fd)) return NULL; dfd = dup (fd); if (dfd == -1) return PyErr_SetFromErrno (PyExc_RuntimeError); out = fdopen (dfd, "w"); if (!out) return PyErr_SetFromErrno (PyExc_RuntimeError); rewind (self->file); while (!feof (self->file)) { int written = 0; ssize_t got = getline (&line, &linelen, self->file); if (got == -1) break; if (!strncmp (line, "*Default", 8)) { char *keyword; char *start = line + 8; char *end; ppd_choice_t *choice; for (end = start; *end; end++) if (isspace (*end) || *end == ':') break; keyword = calloc(1, (end - start) + 1); strncpy(keyword, start, end - start); choice = ppdFindMarkedChoice (self->ppd, keyword); // Treat PageRegion, PaperDimension and ImageableArea specially: // if not marked, use PageSize option. if (!choice && (!strcmp (keyword, "PageRegion") || !strcmp (keyword, "PaperDimension") || !strcmp (keyword, "ImageableArea"))) choice = ppdFindMarkedChoice (self->ppd, "PageSize"); if (choice) { fprintf (out, "*Default%s: %s", keyword, choice->choice); if (strchr (end, '\r')) fputs ("\r", out); fputs ("\n", out); written = 1; } } if (!written) fputs (line, out); } fclose (out); if (line) free (line); Py_RETURN_NONE; } ///////// // PPD // ATTRIBUTES ///////// static PyObject * PPD_getConstraints (PPD *self, void *closure) { PyObject *ret = PyList_New (0); ppd_const_t *c; int i; for (i = 0, c = self->ppd->consts; i < self->ppd->num_consts; i++, c++) { PyObject *args = Py_BuildValue ("()"); PyObject *kwlist = Py_BuildValue ("{}"); Constraint *cns = (Constraint *) PyType_GenericNew (&cups_ConstraintType, args, kwlist); Py_DECREF (args); Py_DECREF (kwlist); cns->constraint = c; cns->ppd = self; Py_INCREF (self); PyList_Append (ret, (PyObject *) cns); } return ret; } static PyObject * PPD_getAttributes (PPD *self, void *closure) { PyObject *ret = PyList_New (0); int i; for (i = 0; i < self->ppd->num_attrs; i++) { PyObject *args = Py_BuildValue ("()"); PyObject *kwlist = Py_BuildValue ("{}"); Attribute *as = (Attribute *) PyType_GenericNew (&cups_AttributeType, args, kwlist); ppd_attr_t *a = self->ppd->attrs[i]; Py_DECREF (args); Py_DECREF (kwlist); as->attribute = a; as->ppd = self; Py_INCREF (self); PyList_Append (ret, (PyObject *) as); } return ret; } static PyObject * PPD_getOptionGroups (PPD *self, void *closure) { PyObject *ret = PyList_New (0); ppd_group_t *group; int i; for (i = 0, group = self->ppd->groups; i < self->ppd->num_groups; i++, group++) { PyObject *args = Py_BuildValue ("()"); PyObject *kwlist = Py_BuildValue ("{}"); Group *grp = (Group *) PyType_GenericNew (&cups_GroupType, args, kwlist); Py_DECREF (args); Py_DECREF (kwlist); grp->group = group; grp->ppd = self; Py_INCREF (self); PyList_Append (ret, (PyObject *) grp); } return ret; } PyGetSetDef PPD_getseters[] = { { "constraints", (getter) PPD_getConstraints, (setter) NULL, "List of constraints", NULL }, { "attributes", (getter) PPD_getAttributes, (setter) NULL, "List of attributes", NULL }, { "optionGroups", (getter) PPD_getOptionGroups, (setter) NULL, "List of PPD option groups" }, { NULL }, /* Sentinel */ }; PyMethodDef PPD_methods[] = { { "localize", (PyCFunction) PPD_localize, METH_NOARGS, "localize() -> None\n\n" "Localize PPD to the current locale." }, { "localizeIPPReason", (PyCFunction) PPD_localizeIPPReason, METH_VARARGS | METH_KEYWORDS, "localizeIPPReason(reason, scheme) -> string or None\n\n" "Localize IPP reason to the current locale." }, { "localizeMarkerName", (PyCFunction) PPD_localizeMarkerName, METH_VARARGS, "localizeMarkerName(name) -> string or None\n\n" "Localize marker name to the current locale." }, { "markDefaults", (PyCFunction) PPD_markDefaults, METH_NOARGS, "markDefaults() -> None\n\n" "Set (mark) all options to their default choices." }, { "markOption", (PyCFunction) PPD_markOption, METH_VARARGS, "markOption(option, choice) -> integer\n\n" "Set an option to a particular choice.\n\n" "@type option: string\n" "@param option: option keyword\n" "@type choice: string\n" "@param choice: option choice\n" "@return: number of conflicts" }, { "conflicts", (PyCFunction) PPD_conflicts, METH_NOARGS, "conflicts() -> integer\n\n" "@return: number of conflicts." }, { "findOption", (PyCFunction) PPD_findOption, METH_VARARGS, "findOption(name)\n\n" "@type name: string\n" "@param name: option keyword\n" "@rtype: L{Option} or None\n" "@return: named option, or None if not found." }, { "findAttr", (PyCFunction) PPD_findAttr, METH_VARARGS | METH_KEYWORDS, "findAttr(name)\n\n" "@type name: string\n" "@param name: attribute name\n" "@type spec: string\n" "@keyword spec: specifier string (optional)\n" "@rtype: L{Attribute} or None\n" "@return: matching attribute, or None if not found." }, { "findNextAttr", (PyCFunction) PPD_findNextAttr, METH_VARARGS | METH_KEYWORDS, "findNextAttr(name)\n\n" "@type name: string\n" "@param name: attribute name\n" "@type spec: string\n" "@keyword spec: specifier string (optional)\n" "@rtype: L{Attribute} or None\n" "@return: next matching attribute, or None if not found." }, { "nondefaultsMarked", (PyCFunction) PPD_nondefaultsMarked, METH_NOARGS, "nondefaultsMarked() -> boolean\n\n" "Returns true if any non-default option choices are marked." }, { "emitString", (PyCFunction) PPD_emitString, METH_VARARGS, "emitString(section, min_order) -> string\n\n" "Return a string with the marked options for section, with at least min_order order dependency.\n" "@type section: integer\n" "@param section: section id\n" "@type min_order: float\n" "@param min_order: minimum order dependency\n" "@return: string containing emitted postscript" }, { "emit", (PyCFunction) PPD_emit, METH_VARARGS, "emit(file, section) -> None\n\n" "Output marked options for section to a file.\n" "@type file: file\n" "@param file: file object\n" "@type section: integer\n" "@param section: section id" }, { "emitAfterOrder", (PyCFunction) PPD_emitAfterOrder, METH_VARARGS, "emitAfterOrder(file, section, limit, min_order) -> None\n\n" "Output marked options for section to a file.\n" "@type file: file\n" "@param file: file object\n" "@type section: integer\n" "@param section: section id\n" "@type limit: integer\n" "@param limit: non-zero to use min_order\n" "@type min_order: float\n" "@param min_order: minimum order dependency" }, { "emitFd", (PyCFunction) PPD_emitFd, METH_VARARGS, "emitFd(fd, section) -> None\n\n" "Output marked options for section to a file descriptor.\n" "@type fd: integer\n" "@param fd: file descriptor\n" "@type section: integer\n" "@param section: section id" }, { "emitJCL", (PyCFunction) PPD_emitJCL, METH_VARARGS, "emitJCL(file, job_id, user, title) -> None\n\n" "Emit code for JCL options to a file.\n" "@type file: file object\n" "@param file: file\n" "@type job_id: integer\n" "@param job_id: job id\n" "@type user: string\n" "@param user: user name on job\n" "@type title: string\n" "@param title: title of job" }, { "emitJCLEnd", (PyCFunction) PPD_emitJCLEnd, METH_VARARGS, "emitJCLEnd(file) -> None\n\n" "Emit JCLEnd code to a file.\n" "@type file: file object\n" "@param file: file" }, { "writeFd", (PyCFunction) PPD_writeFd, METH_VARARGS, "writeFd(fd) -> None\n\n" "Write PPD file, with marked choices as defaults, to file\n" "descriptor.\n\n" "@type fd: integer\n" "@param fd: open file descriptor" }, { NULL } /* Sentinel */ }; PyTypeObject cups_PPDType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.PPD", /*tp_name*/ sizeof(PPD), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PPD_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PPD file\n" "========\n" " A PPD file.\n\n" "@type constraints: L{Constraint} list\n" "@ivar constraints: list of constraints\n" "@type attributes: L{Attribute} list\n" "@ivar attributes: list of attributes\n" "@type optionGroups: L{Group} list\n" "@ivar optionGroups: list of PPD option groups\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ PPD_methods, /* tp_methods */ 0, /* tp_members */ PPD_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PPD_init, /* tp_init */ 0, /* tp_alloc */ PPD_new, /* tp_new */ }; //////////// // Option // //////////// static PyObject * Option_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Option *self; self = (Option *) type->tp_alloc (type, 0); return (PyObject *) self; } static int Option_init (Option *self, PyObject *args, PyObject *kwds) { self->option = NULL; return 0; } static void Option_dealloc (Option *self) { Py_XDECREF (self->ppd); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static PyObject * Option_repr (Option *self) { ppd_option_t *option = self->option; if (!option) return PyUnicode_FromString (""); char buffer[256]; snprintf (buffer, 256, "", option->keyword, option->defchoice); return PyUnicode_FromString (buffer); } //////////// // Option // ATTRIBUTES //////////// static PyObject * Option_getConflicted (Option *self, void *closure) { if (!self->option || self->option->conflicted) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyObject * Option_getKeyword (Option *self, void *closure) { if (!self->option) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->option->keyword); } static PyObject * Option_getDefchoice (Option *self, void *closure) { if (!self->option) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->option->defchoice); } static PyObject * Option_getText (Option *self, void *closure) { if (!self->option) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->option->text); } static PyObject * Option_getUI (Option *self, void *closure) { if (!self->option) { Py_RETURN_NONE; } return PyLong_FromLong (self->option->ui); } static PyObject * Option_getChoices (Option *self, void *closure) { PyObject *choices = PyList_New (0); ppd_choice_t *choice; bool defchoice_seen = false; int i; if (!self->option) return choices; for (i = 0, choice = self->option->choices; i < self->option->num_choices; i++, choice++) { PyObject *choice_dict = PyDict_New (); PyObject *u; u = make_PyUnicode_from_ppd_string (self->ppd, choice->choice); PyDict_SetItemString (choice_dict, "choice", u); Py_DECREF (u); u = make_PyUnicode_from_ppd_string (self->ppd, choice->text); PyDict_SetItemString (choice_dict, "text", u); Py_DECREF (u); u = PyBool_FromLong (choice->marked); PyDict_SetItemString (choice_dict, "marked", u); Py_DECREF (u); PyList_Append (choices, choice_dict); if (!strcmp (choice->choice, self->option->defchoice)) defchoice_seen = true; } if (!defchoice_seen) { // This PPD option has a default choice that isn't one of the choices. // This really happens. const char *defchoice = self->option->defchoice; PyObject *choice_dict = PyDict_New (); PyObject *u; u = make_PyUnicode_from_ppd_string (self->ppd, defchoice); PyDict_SetItemString (choice_dict, "choice", u); Py_DECREF (u); u = make_PyUnicode_from_ppd_string (self->ppd, defchoice); PyDict_SetItemString (choice_dict, "text", u); Py_DECREF (u); PyList_Append (choices, choice_dict); } return choices; } PyGetSetDef Option_getseters[] = { { "conflicted", (getter) Option_getConflicted, (setter) NULL, "Whether this option is in conflict", NULL }, { "keyword", (getter) Option_getKeyword, (setter) NULL, "keyword", NULL }, { "defchoice", (getter) Option_getDefchoice, (setter) NULL, "defchoice", NULL }, { "text", (getter) Option_getText, (setter) NULL, "text", NULL }, { "ui", (getter) Option_getUI, (setter) NULL, "ui", NULL }, { "choices", (getter) Option_getChoices, (setter) NULL, "choices", NULL }, { NULL } }; PyMethodDef Option_methods[] = { { NULL } /* Sentinel */ }; PyTypeObject cups_OptionType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.Option", /*tp_name*/ sizeof(Option), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Option_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Option_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PPD option\n" "==========\n" " A PPD option.\n\n" "@type conflicted: boolean\n" "@ivar conflicted: whether this option is in conflict\n" "@type keyword: string\n" "@ivar keyword: the option keyword e.g. Duplex\n" "@type defchoice: string\n" "@ivar defchoice: the default option choice\n" "@type text: string\n" "@ivar text: the user-presentable option name e.g. Double-sided printing\n" "@type ui: integer\n" "@ivar ui: the option type; one of L{PPD_UI_BOOLEAN}, \n" "L{PPD_UI_PICKONE}, L{PPD_UI_PICKMANY}\n" "@type choices: list\n" "@ivar choices: list of the option's choices\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Option_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Option_init, /* tp_init */ 0, /* tp_alloc */ Option_new, /* tp_new */ }; /////////// // Group // /////////// static PyObject * Group_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Group *self; self = (Group *) type->tp_alloc (type, 0); return (PyObject *) self; } static int Group_init (Group *self, PyObject *args, PyObject *kwds) { self->group = NULL; return 0; } static void Group_dealloc (Group *self) { Py_XDECREF (self->ppd); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static PyObject * Group_repr (Group *self) { ppd_group_t *group = self->group; if (!group) return PyUnicode_FromString (""); char buffer[256]; snprintf (buffer, 256, "", group->name); return PyUnicode_FromString (buffer); } /////////// // Group // ATTRIBUTES /////////// static PyObject * Group_getText (Group *self, void *closure) { if (!self->group) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->group->text); } static PyObject * Group_getName (Group *self, void *closure) { if (!self->group) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->group->name); } static PyObject * Group_getOptions (Group *self, void *closure) { PyObject *options = PyList_New (0); ppd_option_t *option; int i; if (!self->group) return options; for (i = 0, option = self->group->options; i < self->group->num_options; i++, option++) { PyObject *args = Py_BuildValue ("()"); PyObject *kwlist = Py_BuildValue ("{}"); Option *opt = (Option *) PyType_GenericNew (&cups_OptionType, args, kwlist); Py_DECREF (args); Py_DECREF (kwlist); opt->option = option; opt->ppd = self->ppd; Py_INCREF (self->ppd); PyList_Append (options, (PyObject *) opt); } return options; } static PyObject * Group_getSubgroups (Group *self, void *closure) { PyObject *subgroups = PyList_New (0); ppd_group_t *subgroup; int i; if (!self->group) return subgroups; for (i = 0, subgroup = self->group->subgroups; i < self->group->num_subgroups; i++, subgroup++) { PyObject *args = Py_BuildValue ("()"); PyObject *kwlist = Py_BuildValue ("{}"); Group *grp = (Group *) PyType_GenericNew (&cups_GroupType, args, kwlist); Py_DECREF (args); Py_DECREF (kwlist); grp->group = subgroup; grp->ppd = self->ppd; Py_INCREF (self->ppd); PyList_Append (subgroups, (PyObject *) grp); } return subgroups; } PyGetSetDef Group_getseters[] = { { "text", (getter) Group_getText, (setter) NULL, "text", NULL }, { "name", (getter) Group_getName, (setter) NULL, "name", NULL }, { "options", (getter) Group_getOptions, (setter) NULL, "options", NULL }, { "subgroups", (getter) Group_getSubgroups, (setter) NULL, "subgroups", NULL }, { NULL } }; PyMethodDef Group_methods[] = { { NULL } /* Sentinel */ }; PyTypeObject cups_GroupType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.Group", /*tp_name*/ sizeof(Group), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Group_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Group_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PPD option group\n" "================\n\n" " A PPD option group.\n\n" "@type text: string\n" "@ivar text: user-presentable group name\n" "@type name: string\n" "@ivar name: unique group name\n" "@type options: L{Option} list\n" "@ivar options: list of options in the group\n" "@type subgroups: L{Group} list\n" "@ivar subgroups: list of subgroups in the group\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Group_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Group_init, /* tp_init */ 0, /* tp_alloc */ Group_new, /* tp_new */ }; //////////////// // Constraint // //////////////// static PyObject * Constraint_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Constraint *self; self = (Constraint *) type->tp_alloc (type, 0); return (PyObject *) self; } static int Constraint_init (Constraint *self, PyObject *args, PyObject *kwds) { self->constraint = NULL; return 0; } static void Constraint_dealloc (Constraint *self) { Py_XDECREF (self->ppd); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } //////////////// // Constraint // ATTRIBUTES //////////////// static PyObject * Constraint_getOption1 (Constraint *self, void *closure) { if (!self->constraint) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->constraint->option1); } static PyObject * Constraint_getChoice1 (Constraint *self, void *closure) { if (!self->constraint) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->constraint->choice1); } static PyObject * Constraint_getOption2 (Constraint *self, void *closure) { if (!self->constraint) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->constraint->option2); } static PyObject * Constraint_getChoice2 (Constraint *self, void *closure) { if (!self->constraint) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->constraint->choice2); } PyGetSetDef Constraint_getseters[] = { { "option1", (getter) Constraint_getOption1, (setter) NULL, "option1", NULL }, { "choice1", (getter) Constraint_getChoice1, (setter) NULL, "choice1", NULL }, { "option2", (getter) Constraint_getOption2, (setter) NULL, "option2", NULL }, { "choice2", (getter) Constraint_getChoice2, (setter) NULL, "choice2", NULL }, { NULL } }; PyTypeObject cups_ConstraintType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.Constraint", /*tp_name*/ sizeof(Constraint), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Constraint_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PPD constraint\n" "==============\n\n" " A PPD constraint.\n\n" "@type option1: string\n" "@ivar option1: first option keyword\n" "@type choice1: string\n" "@ivar choice1: first option choice\n" "@type option2: string\n" "@ivar option2: second option keyword\n" "@type choice2: string\n" "@ivar choice2: secondoption choice\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Constraint_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Constraint_init, /* tp_init */ 0, /* tp_alloc */ Constraint_new, /* tp_new */ }; /////////////// // Attribute // /////////////// static PyObject * Attribute_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Attribute *self; self = (Attribute *) type->tp_alloc (type, 0); return (PyObject *) self; } static int Attribute_init (Attribute *self, PyObject *args, PyObject *kwds) { self->attribute = NULL; return 0; } static void Attribute_dealloc (Attribute *self) { Py_XDECREF (self->ppd); ((PyObject *)self)->ob_type->tp_free ((PyObject *) self); } static PyObject * Attribute_repr (Attribute *self) { ppd_attr_t *attribute = self->attribute; if (!attribute) return PyUnicode_FromString (""); char buffer[256]; snprintf (buffer, 256, "", attribute->name, attribute->spec[0] != '\0' ? " ": "", attribute->spec); return PyUnicode_FromString (buffer); } /////////////// // Attribute // ATTRIBUTES /////////////// static PyObject * Attribute_getName (Attribute *self, void *closure) { if (!self->attribute) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->attribute->name); } static PyObject * Attribute_getSpec (Attribute *self, void *closure) { if (!self->attribute) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->attribute->spec); } static PyObject * Attribute_getText (Attribute *self, void *closure) { if (!self->attribute) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->attribute->text); } static PyObject * Attribute_getValue (Attribute *self, void *closure) { if (!self->attribute) { Py_RETURN_NONE; } return make_PyUnicode_from_ppd_string (self->ppd, self->attribute->value); } PyGetSetDef Attribute_getseters[] = { { "name", (getter) Attribute_getName, (setter) NULL, "name", NULL }, { "spec", (getter) Attribute_getSpec, (setter) NULL, "spec", NULL }, { "text", (getter) Attribute_getText, (setter) NULL, "text", NULL }, { "value", (getter) Attribute_getValue, (setter) NULL, "value", NULL }, { NULL } }; PyTypeObject cups_AttributeType = { PyVarObject_HEAD_INIT(NULL, 0) "cups.Attribute", /*tp_name*/ sizeof(Attribute), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Attribute_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)Attribute_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PPD attribute\n" "=============\n\n" " A PPD attribute.\n\n" "@type name: string\n" "@ivar name: attribute name\n" "@type spec: string\n" "@ivar spec: specifier string (if any)\n" "@type text: string\n" "@ivar text: human-readable text (if any)\n" "@type value: string\n" "@ivar value: attribute value\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Attribute_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Attribute_init, /* tp_init */ 0, /* tp_alloc */ Attribute_new, /* tp_new */ }; pycups-2.0.4/cupsppd.h000066400000000000000000000025161461013555200146750ustar00rootroot00000000000000/* * cups - Python bindings for CUPS * Copyright (C) 2002-2020 Tim Waugh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef HAVE_CUPSPPD_H #define HAVE_CUPSPPD_H #include #include #include extern PyMethodDef PPD_methods[]; extern PyTypeObject cups_PPDType; extern PyTypeObject cups_OptionType; extern PyTypeObject cups_GroupType; extern PyTypeObject cups_ConstraintType; extern PyTypeObject cups_AttributeType; typedef struct { PyObject_HEAD ppd_file_t *ppd; FILE *file; iconv_t *conv_from; iconv_t *conv_to; } PPD; extern PyObject *PPD_writeFd (PPD *self, PyObject *args); #endif /* HAVE_CUPSPPD_H */ pycups-2.0.4/examples/000077500000000000000000000000001461013555200146605ustar00rootroot00000000000000pycups-2.0.4/examples/cupstree.py000077500000000000000000000041021461013555200170640ustar00rootroot00000000000000import cups def do_indent (indent): return " "*indent def getippqueue (dev, queue, depth): name = dev.rfind ('/') name = dev[name + 1:] dev = dev[6:] e = dev.find (':') if e == -1: e = dev.find ('/') host = dev[:e] cups.setServer (host) try: c = cups.Connection () printers = c.getPrinters () classes = c.getClasses () except RuntimeError: # Failed to connect. return except cups.IPPError as e: if e == cups.IPP_OPERATION_NOT_SUPPORTED: # CUPS-Get-Printers not supported so not a CUPS server. printers = {} classes = {} else: return queue = c.getPrinterAttributes (name) dev = queue['device-uri'] getqueue (name, queue, host, depth + 1, printers, classes) def getqueue (name, queue, host, depth, printers, classes): indent = do_indent(depth) if queue['printer-type'] & cups.CUPS_PRINTER_CLASS: print ("%s* Name:\t%s[@%s] (class)" % (indent, name, host)) dev = queue['device-uri'] if dev.startswith ('ipp:'): getippqueue (dev, queue, depth) else: members = classes[name] depth += 1 indent = do_indent(depth) for member in members: getqueue (member, printers[member], host, depth, printers, classes) else: print ("%s* Name:\t%s[@%s]" % (indent, name, host)) dev = queue['device-uri'] info = queue['printer-info'] print ("%sURI:\t%s" % (indent, dev)) print ("%sInfo:\t%s" % (indent, info)) if dev.startswith ('ipp:'): getippqueue (dev, name, depth) if depth == 0: print ("") def gethost (host=None, depth=0): if host: cups.setServer (host) else: host = "localhost" c = cups.Connection () printers = c.getPrinters () classes = c.getClasses () indent = do_indent(depth) for name, queue in printers.items (): getqueue (name, queue, host, depth, printers, classes) gethost() pycups-2.0.4/postscriptdriver.prov000077500000000000000000000171121461013555200174050ustar00rootroot00000000000000#!/usr/bin/python3 ## Copyright (C) 2009-2020 Red Hat, Inc. ## Author: Tim Waugh ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import sys try: import cups CAN_EXAMINE_PPDS = True except: CAN_EXAMINE_PPDS = False from getopt import getopt import errno import os import posix import re import shlex import signal import subprocess import sys import tempfile if len (sys.argv) > 1: RPM_BUILD_ROOT = sys.argv[1] else: RPM_BUILD_ROOT = os.environ.get ("RPM_BUILD_ROOT") class TimedOut(Exception): def __init__ (self): Exception.__init__ (self, "Timed out") class DeviceIDs: def __init__ (self): self.ids = dict() def get_dict (self): return self.ids def get_tags (self): ret = [] for mfg, mdlset in self.ids.items (): mfgl = mfg.lower ().replace (" ", "_") for mdl in mdlset: mdll = mdl.lower ().replace (" ", "_") ret.append ("postscriptdriver(%s;%s;)" % (mfgl, mdll)) return ret def __add__ (self, other): if isinstance(other, DeviceIDs): for omfg, omdlset in other.ids.items (): try: mdlset = self.ids[omfg] except KeyError: mdlset = set() self.ids[omfg] = mdlset mdlset.update (omdlset) return self pieces = other.split (';') mfg = mdl = None for piece in pieces: s = piece.split (":") if len (s) != 2: continue key, value = s key = key.upper ().strip () if key in ["MFG", "MANUFACTURER"]: mfg = value.strip () elif key in ["MDL", "MODEL"]: mdl = value.strip () if mfg and mdl: try: mdlset = self.ids[mfg] except KeyError: mdlset = set() self.ids[mfg] = mdlset mdlset.add (mdl) return self class Driver: def __init__ (self): self.ids = DeviceIDs() def list (self): return self.ids class PPDDriver(Driver): def __init__ (self, pathname=None): Driver.__init__ (self) self.pathname = pathname def list (self): if self.pathname != None: self.examine_file (self.pathname) return Driver.list (self) def examine_file (self, path): try: ppd = cups.PPD (path) except RuntimeError: # Not a PPD file. Perhaps it's a drv file. drv = DrvDriver (path) self.ids += drv.list () return attr = ppd.findAttr ('1284DeviceID') while attr: self.ids += attr.value attr = ppd.findNextAttr ('1284DeviceID') class DynamicDriver(Driver): def __init__ (self, driver): Driver.__init__ (self) self.driver = driver signal.signal (signal.SIGALRM, self._alarm) def _alarm (self, sig, stack): raise TimedOut def list (self): signal.alarm (180) env = os.environ.copy () if RPM_BUILD_ROOT: buildroot = RPM_BUILD_ROOT if not buildroot.endswith (os.path.sep): buildroot += os.path.sep env["DESTDIR"] = RPM_BUILD_ROOT env["LD_LIBRARY_PATH"] = "%susr/lib64:%susr/lib" % (buildroot, buildroot) p = subprocess.Popen ([self.driver, "list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) try: (stdout, stderr) = p.communicate () signal.alarm (0) except TimedOut: posix.kill (p.pid, signal.SIGKILL) raise if stderr: print(stderr.decode (), file=sys.stderr) ppds = [] lines = stdout.decode ().split ('\n') for line in lines: l = shlex.split (line) if len (l) < 5: continue self.ids += l[4] return Driver.list (self) class DrvDriver(PPDDriver): def __init__ (self, pathname): PPDDriver.__init__ (self) self.drv = pathname def _alarm (self, sig, stack): raise TimedOut def list (self): tmpdir = os.environ.get ("TMPDIR", "/tmp") + os.path.sep outputdir = tempfile.mkdtemp (dir=tmpdir) argv = [ "ppdc", "-d", outputdir, "-I", "/usr/share/cups/ppdc", self.drv ] signal.alarm (60) try: p = subprocess.Popen (argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: # ppdc not available. os.rmdir (outputdir) return Driver.list (self) try: (stdout, stderr) = p.communicate () signal.alarm (0) except TimedOut: posix.kill (p.pid, signal.SIGKILL) raise for (dirpath, dirnames, filenames) in os.walk (outputdir, topdown=False): for filename in filenames: path = dirpath + os.path.sep + filename self.examine_file (path) try: os.unlink (path) except OSError: pass for dirname in dirnames: try: os.rmdir (dirpath + os.paht.sep + dirname) except OSError: pass try: os.rmdir (outputdir) except OSError: pass return Driver.list (self) class TagBuilder: def __init__ (self, filelist=None): if filelist == None: filelist = sys.stdin paths = [x.rstrip () for x in filelist.readlines ()] self.ids = DeviceIDs () for path in paths: if path.find ("/usr/lib/cups/driver/") != -1 and \ path.find("driverless") == -1: try: self.ids += DynamicDriver (path).list () except TimedOut: pass except OSError as exc: (e, s) = exc.args if e == errno.EACCES or e == errno.ENOENT: # Not executable pass else: raise if CAN_EXAMINE_PPDS: for path in paths: try: self.ids += PPDDriver (path).list () except TimedOut: pass def get_tags (self): return self.ids.get_tags () if __name__ == "__main__": builder = TagBuilder () tags = builder.get_tags () for tag in tags: print (tag) pycups-2.0.4/psdriver.attr000066400000000000000000000002451461013555200155750ustar00rootroot00000000000000%__psdriver_provides %{_rpmconfigdir}/postscriptdriver.prov %__psdriver_path ^(/usr/lib/cups/driver/.*|%{_datadir}/cups/drv/.*\.drv)$ %__psdriver_magic ^PPD file.*$ pycups-2.0.4/setup.py000066400000000000000000000051471461013555200145630ustar00rootroot00000000000000#!/usr/bin/python ## Copyright (C) 2002-2020 Red Hat, Inc ## Authors: Tim Waugh ## Zdenek Dohnal ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """This is a set of Python bindings for the libcups library from the CUPS project. >>> # Example of getting a list of printers >>> import cups >>> conn = cups.Connection () >>> printers = conn.getPrinters () >>> for printer in printers: ... print printer, printers[printer]["device-uri"] ... HP ipp://192.168.1.1:631/printers/HP duplex ipp://192.168.1.1:631/printers/duplex HP-LaserJet-6MP ipp://192.168.1.1:631/printers/HP-LaserJet-6MP EPSON-Stylus-D78 usb://EPSON/Stylus%20D78 """ from distutils.core import setup, Extension import sys VERSION="2.0.4" libraries=["cups"] if sys.platform == "darwin" or sys.platform.startswith("freebsd"): libraries.append ("iconv") setup (name="pycups", version=VERSION, description="Python bindings for libcups", long_description=__doc__, maintainer="Zdenek Dohnal", maintainer_email="zdohnal@redhat.com", url="https://github.com/OpenPrinting/pycups", download_url="https://github.com/OpenPrinting/pycups/releases", classifiers=[ "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: GNU General Public License (GPL)", "Development Status :: 5 - Production/Stable", "Operating System :: Unix", "Programming Language :: C", "Programming Language :: Python", "Programming Language :: Python :: 3", ], license="GPLv2+", ext_modules=[Extension("cups", ["cupsmodule.c", "cupsconnection.c", "cupsppd.c", "cupsipp.c"], libraries=libraries, define_macros=[("VERSION", '"%s"' % VERSION)])]) pycups-2.0.4/test-enum.py000066400000000000000000000005721461013555200153410ustar00rootroot00000000000000#!/usr/bin/python import cups, os def f(user_data, flags, dest): user_data.append (dest) print (flags, dest) return 1 l=[] cups.enumDests(f, user_data=l) for i in l: uri = i.options['printer-uri-supported'] c, resource = cups.connectDest (i, lambda x, y, z: 1) name = resource.split ('/')[-1] print (name) n = c.getPPD(name) os.unlink (n) pycups-2.0.4/test.py000066400000000000000000000025711461013555200144000ustar00rootroot00000000000000#!/usr/bin/python import cups # Simple demonstration of cups module def callback (prompt): print ("Password is required for this operation") password = raw_input (prompt) return password def test_cups_module (): cups.setUser ("root") cups.setPasswordCB (callback) try: conn = cups.Connection () except RuntimeError as er: print ("Couldn't get a connection to local CUPS server - {}" " - is CUPS running?".format(er)) return # get destinations - temporary and permanent printers dests = list(conn.getDests ().keys ()) if len(dests) == 0: print ("No printers found, exiting.") return # get permanent printers printers = list(conn.getPrinters ().keys ()) if 0: print ("Getting cupsd.conf") file ("cupsd.conf", "w") conn.getFile ("/admin/conf/cupsd.conf", "cupsd.conf") print ("Putting cupsd.conf") conn.putFile ("/admin/conf/cupsd.conf", "cupsd.conf") assert len(printers) > 0 print ("Getting PPD for %s" % printers[len (printers) - 1]) f = conn.getPPD (printers[len (printers) - 1]) ppd = cups.PPD (f) ppd.markDefaults () print (ppd.conflicts ()) groups = ppd.optionGroups for group in groups: for opt in group.options: print (list (map (lambda x: x["text"], opt.choices))) test_cups_module ()