Index: tea4cups/tags/2.10/COPYING
===================================================================
--- tea4cups/tags/2.10/COPYING (revision 595)
+++ tea4cups/tags/2.10/COPYING (revision 595)
@@ -0,0 +1,340 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                          59 Temple Place, Suite 330
+                          Boston, MA 02111-1307, 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 Library 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
+
+        Appendix: 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.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) 19yy  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, 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) 19yy 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.
+
+  <signature of Ty Coon>, 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 Library General
+Public License instead of this License.
Index: tea4cups/tags/2.10/tea4cups
===================================================================
--- tea4cups/tags/2.10/tea4cups (revision 615)
+++ tea4cups/tags/2.10/tea4cups (revision 615)
@@ -0,0 +1,888 @@
+#! /usr/bin/env python
+# -*- coding: ISO-8859-15 -*-
+
+# Tea4CUPS : Tee for CUPS
+#
+# (c) 2005 Jerome Alet <alet@librelogiciel.com>
+# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+#
+#
+
+import sys
+import os
+import popen2
+import errno
+import md5
+import cStringIO
+import shlex
+import tempfile
+import ConfigParser
+import select
+import signal
+import time
+from struct import unpack
+
+version = "2.10_unofficial"
+
+class TeeError(Exception):
+    """Base exception for Tea4CUPS related stuff."""
+    def __init__(self, message = ""):
+        self.message = message
+        Exception.__init__(self, message)
+    def __repr__(self):
+        return self.message
+    __str__ = __repr__
+    
+class ConfigError(TeeError) :    
+    """Configuration related exceptions."""
+    pass 
+    
+class IPPError(TeeError) :    
+    """IPP related exceptions."""
+    pass 
+    
+class Popen4ForCUPS(popen2.Popen4) :
+    """Our own class to execute real backends.
+    
+       Their first argument is different from their path so using
+       native popen2.Popen3 would not be feasible.
+    """
+    def __init__(self, cmd, bufsize=-1, arg0=None) :
+        self.arg0 = arg0
+        popen2.Popen4.__init__(self, cmd, bufsize)
+        
+    def _run_child(self, cmd):
+        try :
+            MAXFD = os.sysconf("SC_OPEN_MAX")
+        except (AttributeError, ValueError) :    
+            MAXFD = 256
+        for i in range(3, MAXFD) : 
+            try:
+                os.close(i)
+            except OSError:
+                pass
+        try:
+            os.execvpe(cmd[0], [self.arg0 or cmd[0]] + cmd[1:], os.environ)
+        finally:
+            os._exit(1)
+    
+# Some IPP constants    
+OPERATION_ATTRIBUTES_TAG = 0x01
+JOB_ATTRIBUTES_TAG = 0x02
+END_OF_ATTRIBUTES_TAG = 0x03
+PRINTER_ATTRIBUTES_TAG = 0x04
+UNSUPPORTED_ATTRIBUTES_TAG = 0x05
+
+class IPPMessage :
+    """A class for IPP message files."""
+    def __init__(self, data) :
+        """Initializes an IPP Message object."""
+        self.data = data
+        self._attributes = {}
+        self.curname = None
+        self.tags = [ None ] * 256      # by default all tags reserved
+        
+        # Delimiter tags
+        self.tags[0x01] = "operation-attributes-tag"
+        self.tags[0x02] = "job-attributes-tag"
+        self.tags[0x03] = "end-of-attributes-tag"
+        self.tags[0x04] = "printer-attributes-tag"
+        self.tags[0x05] = "unsupported-attributes-tag"
+        
+        # out of band values
+        self.tags[0x10] = "unsupported"
+        self.tags[0x11] = "reserved-for-future-default"
+        self.tags[0x12] = "unknown"
+        self.tags[0x13] = "no-value"
+        
+        # integer values
+        self.tags[0x20] = "generic-integer"
+        self.tags[0x21] = "integer"
+        self.tags[0x22] = "boolean"
+        self.tags[0x23] = "enum"
+        
+        # octetString
+        self.tags[0x30] = "octetString-with-an-unspecified-format"
+        self.tags[0x31] = "dateTime"
+        self.tags[0x32] = "resolution"
+        self.tags[0x33] = "rangeOfInteger"
+        self.tags[0x34] = "reserved-for-collection"
+        self.tags[0x35] = "textWithLanguage"
+        self.tags[0x36] = "nameWithLanguage"
+        
+        # character strings
+        self.tags[0x20] = "generic-character-string"
+        self.tags[0x41] = "textWithoutLanguage"
+        self.tags[0x42] = "nameWithoutLanguage"
+        # self.tags[0x43] = "reserved"
+        self.tags[0x44] = "keyword"
+        self.tags[0x45] = "uri"
+        self.tags[0x46] = "uriScheme"
+        self.tags[0x47] = "charset"
+        self.tags[0x48] = "naturalLanguage"
+        self.tags[0x49] = "mimeMediaType"
+        
+        # now parses the IPP message
+        self.parse()
+        
+    def __getattr__(self, attrname) :    
+        """Allows self.attributes to return the attributes names."""
+        if attrname == "attributes" :
+            keys = self._attributes.keys()
+            keys.sort()
+            return keys
+        raise AttributeError, attrname
+            
+    def __getitem__(self, ippattrname) :    
+        """Fakes a dictionnary d['key'] notation."""
+        value = self._attributes.get(ippattrname)
+        if value is not None :
+            if len(value) == 1 :
+                value = value[0]
+        return value        
+    get = __getitem__    
+        
+    def parseTag(self) :    
+        """Extracts information from an IPP tag."""
+        pos = self.position
+        valuetag = self.tags[ord(self.data[pos])]
+        # print valuetag.get("name")
+        pos += 1
+        posend = pos2 = pos + 2
+        namelength = unpack(">H", self.data[pos:pos2])[0]
+        if not namelength :
+            name = self.curname
+        else :    
+            posend += namelength
+            self.curname = name = self.data[pos2:posend]
+        pos2 = posend + 2
+        valuelength = unpack(">H", self.data[posend:pos2])[0]
+        posend = pos2 + valuelength
+        value = self.data[pos2:posend]
+        oldval = self._attributes.setdefault(name, [])
+        oldval.append(value)
+        return posend - self.position
+        
+    def operation_attributes_tag(self) : 
+        """Indicates that the parser enters into an operation-attributes-tag group."""
+        return self.parseTag()
+        
+    def job_attributes_tag(self) : 
+        """Indicates that the parser enters into an operation-attributes-tag group."""
+        return self.parseTag()
+        
+    def printer_attributes_tag(self) : 
+        """Indicates that the parser enters into an operation-attributes-tag group."""
+        return self.parseTag()
+        
+    def parse(self) :
+        """Parses an IPP Message.
+        
+           NB : Only a subset of RFC2910 is implemented.
+           We are only interested in textual informations for now anyway.
+        """
+        self.version = "%s.%s" % (ord(self.data[0]), ord(self.data[1]))
+        self.operation_id = "0x%04x" % unpack(">H", self.data[2:4])[0]
+        self.request_id = "0x%08x" % unpack(">I", self.data[4:8])[0]
+        self.position = 8
+        try :
+            tag = ord(self.data[self.position])
+            while tag != END_OF_ATTRIBUTES_TAG :
+                self.position += 1
+                name = self.tags[tag]
+                if name is not None :
+                    func = getattr(self, name.replace("-", "_"), None)
+                    if func is not None :
+                        self.position += func()
+                        if ord(self.data[self.position]) > UNSUPPORTED_ATTRIBUTES_TAG :
+                            self.position -= 1
+                            continue
+                tag = ord(self.data[self.position])
+        except IndexError :
+            raise IPPError, "Unexpected end of IPP message."
+            
+class FakeConfig :    
+    """Fakes a configuration file parser."""
+    def get(self, section, option, raw=0) :
+        """Fakes the retrieval of a global option."""
+        raise ConfigError, "Invalid configuration file : no option %s in section [%s]" % (option, section)
+        
+class CupsBackend :
+    """Base class for tools with no database access."""
+    def __init__(self) :
+        """Initializes the CUPS backend wrapper."""
+        signal.signal(signal.SIGTERM, signal.SIG_IGN)
+        signal.signal(signal.SIGPIPE, signal.SIG_IGN)
+        self.MyName = "Tea4CUPS"
+        self.myname = "tea4cups"
+        self.pid = os.getpid()
+        confdir = os.environ.get("CUPS_SERVERROOT", ".") 
+        self.conffile = os.path.join(confdir, "%s.conf" % self.myname)
+        if os.path.isfile(self.conffile) :
+            self.config = ConfigParser.ConfigParser()
+            self.config.read([self.conffile])
+            self.debug = self.isTrue(self.getGlobalOption("debug", ignore=1))
+        else :    
+            self.config = FakeConfig()
+            self.debug = 1      # no config, so force debug mode !
+            
+    def logInfo(self, message, level="info") :        
+        """Logs a message to CUPS' error_log file."""
+        sys.stderr.write("%s: %s v%s (PID %i) : %s\n" % (level.upper(), self.MyName, version, os.getpid(), message))
+        sys.stderr.flush()
+        
+    def logDebug(self, message) :    
+        """Logs something to debug output if debug is enabled."""
+        if self.debug :
+            self.logInfo(message, level="debug")
+        
+    def isTrue(self, option) :        
+        """Returns 1 if option is set to true, else 0."""
+        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
+            return 1
+        else :    
+            return 0
+                        
+    def getGlobalOption(self, option, ignore=0) :    
+        """Returns an option from the global section, or raises a ConfigError if ignore is not set, else returns None."""
+        try :
+            return self.config.get("global", option, raw=1)
+        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :    
+            if not ignore :
+                raise ConfigError, "Option %s not found in section global of %s" % (option, self.conffile)
+                
+    def getPrintQueueOption(self, printqueuename, option, ignore=0) :    
+        """Returns an option from the printer section, or the global section, or raises a ConfigError."""
+        globaloption = self.getGlobalOption(option, ignore=1)
+        try :
+            return self.config.get(printqueuename, option, raw=1)
+        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :    
+            if globaloption is not None :
+                return globaloption
+            elif not ignore :
+                raise ConfigError, "Option %s not found in section [%s] of %s" % (option, printqueuename, self.conffile)
+                
+    def enumBranches(self, printqueuename, branchtype="tee") :
+        """Returns the list of branchtypes branches for a particular section's."""
+        branchbasename = "%s_" % branchtype.lower()
+        try :
+            globalbranches = [ (k, v) for (k, v) in self.config.items("global") if k.startswith(branchbasename) ]
+        except ConfigParser.NoSectionError, msg :    
+            raise ConfigError, "Invalid configuration file : %s" % msg
+        try :
+            sectionbranches = [ (k, v) for (k, v) in self.config.items(printqueuename) if k.startswith(branchbasename) ]
+        except ConfigParser.NoSectionError, msg :    
+            self.logInfo("No section for print queue %s : %s" % (printqueuename, msg))
+            sectionbranches = []
+        branches = {}
+        for (k, v) in globalbranches :
+            value = v.strip()
+            if value :
+                branches[k] = value
+        for (k, v) in sectionbranches :    
+            value = v.strip()
+            if value :
+                branches[k] = value # overwrite any global option or set a new value
+            else :    
+                del branches[k] # empty value disables a global option
+        return branches
+        
+    def discoverOtherBackends(self) :    
+        """Discovers the other CUPS backends.
+        
+           Executes each existing backend in turn in device enumeration mode.
+           Returns the list of available backends.
+        """
+        # Unfortunately this method can't output any debug information
+        # to stdout or stderr, else CUPS considers that the device is
+        # not available.
+        available = []
+        (directory, myname) = os.path.split(sys.argv[0])
+        if not directory :
+            directory = "./"
+        tmpdir = tempfile.gettempdir()
+        lockfilename = os.path.join(tmpdir, "%s..LCK" % myname)
+        if os.path.exists(lockfilename) :
+            lockfile = open(lockfilename, "r")
+            pid = int(lockfile.read())
+            lockfile.close()
+            try :
+                # see if the pid contained in the lock file is still running
+                os.kill(pid, 0)
+            except OSError, e :    
+                if e.errno != errno.EPERM :
+                    # process doesn't exist anymore
+                    os.remove(lockfilename)
+            
+        if not os.path.exists(lockfilename) :
+            lockfile = open(lockfilename, "w")
+            lockfile.write("%i" % self.pid)
+            lockfile.close()
+            allbackends = [ os.path.join(directory, b) \
+                                for b in os.listdir(directory) 
+                                    if os.access(os.path.join(directory, b), os.X_OK) \
+                                        and (b != myname)] 
+            for backend in allbackends :                            
+                answer = os.popen(backend, "r")
+                try :
+                    devices = [line.strip() for line in answer.readlines()]
+                except :    
+                    devices = []
+                status = answer.close()
+                if status is None :
+                    for d in devices :
+                        # each line is of the form : 
+                        # 'xxxx xxxx "xxxx xxx" "xxxx xxx"'
+                        # so we have to decompose it carefully
+                        fdevice = cStringIO.StringIO(d)
+                        tokenizer = shlex.shlex(fdevice)
+                        tokenizer.wordchars = tokenizer.wordchars + \
+                                                        r".:,?!~/\_$*-+={}[]()#"
+                        arguments = []
+                        while 1 :
+                            token = tokenizer.get_token()
+                            if token :
+                                arguments.append(token)
+                            else :
+                                break
+                        fdevice.close()
+                        try :
+                            (devicetype, device, name, fullname) = arguments
+                        except ValueError :    
+                            pass    # ignore this 'bizarre' device
+                        else :    
+                            if name.startswith('"') and name.endswith('"') :
+                                name = name[1:-1]
+                            if fullname.startswith('"') and fullname.endswith('"') :
+                                fullname = fullname[1:-1]
+                            available.append('%s %s:%s "%s+%s" "%s managed %s"' \
+                                                 % (devicetype, self.myname, device, self.MyName, name, self.MyName, fullname))
+            os.remove(lockfilename)
+        available.append('direct %s:// "%s+Nothing" "%s managed Virtual Printer"' \
+                             % (self.myname, self.MyName, self.MyName))
+        return available
+                        
+    def initBackend(self) :    
+        """Initializes the backend's attributes."""
+        # check that the DEVICE_URI environment variable's value is 
+        # prefixed with self.myname otherwise don't touch it.
+        # If this is the case, we have to remove the prefix from 
+        # the environment before launching the real backend 
+        muststartwith = "%s:" % self.myname
+        device_uri = os.environ.get("DEVICE_URI", "")
+        if device_uri.startswith(muststartwith) :
+            fulldevice_uri = device_uri[:]
+            device_uri = fulldevice_uri[len(muststartwith):]
+            for i in range(2) :
+                if device_uri.startswith("/") :  
+                    device_uri = device_uri[1:]
+        try :
+            (backend, destination) = device_uri.split(":", 1) 
+        except ValueError :    
+            if not device_uri :
+                self.logDebug("Not attached to an existing print queue.")
+                backend = ""
+            else :    
+                raise TeeError, "Invalid DEVICE_URI : %s\n" % device_uri
+        
+        self.JobId = sys.argv[1].strip()
+        self.UserName = sys.argv[2].strip()
+        self.Title = sys.argv[3].strip()
+        self.Copies = int(sys.argv[4].strip())
+        self.Options = sys.argv[5].strip()
+        if len(sys.argv) == 7 :
+            self.InputFile = sys.argv[6] # read job's datas from file
+        else :    
+            self.InputFile = None        # read job's datas from stdin
+            
+        self.RealBackend = backend
+        self.DeviceURI = device_uri
+        self.PrinterName = os.environ.get("PRINTER", "")
+        self.Directory = self.getPrintQueueOption(self.PrinterName, "directory")
+        self.DataFile = os.path.join(self.Directory, "%s-%s-%s-%s" % (self.myname, self.PrinterName, self.UserName, self.JobId))
+        (ippfilename, ippmessage) = self.parseIPPMessageFile()
+        self.ControlFile = ippfilename
+        self.ClientHost = ippmessage.get("job-originating-host-name")
+        self.JobBilling = ippmessage.get("job-billing")
+            
+    def getCupsConfigDirectives(self, directives=[]) :
+        """Retrieves some CUPS directives from its configuration file.
+        
+           Returns a mapping with lowercased directives as keys and 
+           their setting as values.
+        """
+        dirvalues = {} 
+        cupsroot = os.environ.get("CUPS_SERVERROOT", "/etc/cups")
+        cupsdconf = os.path.join(cupsroot, "cupsd.conf")
+        try :
+            conffile = open(cupsdconf, "r")
+        except IOError :    
+            raise TeeError, "Unable to open %s" % cupsdconf
+        else :    
+            for line in conffile.readlines() :
+                linecopy = line.strip().lower()
+                for di in [d.lower() for d in directives] :
+                    if linecopy.startswith("%s " % di) :
+                        try :
+                            val = line.split()[1]
+                        except :    
+                            pass # ignore errors, we take the last value in any case.
+                        else :    
+                            dirvalues[di] = val
+            conffile.close()            
+        return dirvalues       
+            
+    def parseIPPMessageFile(self) :        
+        """Extracts the client's hostname or IP address from the CUPS message file for current job."""
+        cupsdconf = self.getCupsConfigDirectives(["RequestRoot"])
+        requestroot = cupsdconf.get("requestroot", "/var/spool/cups")
+        if (len(self.JobId) < 5) and self.JobId.isdigit() :
+            ippmessagefile = "c%05i" % int(self.JobId)
+        else :    
+            ippmessagefile = "c%s" % self.JobId
+        ippmessagefile = os.path.join(requestroot, ippmessagefile)
+        ippmessage = {}
+        try :
+            ippdatafile = open(ippmessagefile)
+        except :    
+            self.logInfo("Unable to open IPP message file %s" % ippmessagefile, "warn")
+        else :    
+            self.logDebug("Parsing of IPP message file %s begins." % ippmessagefile)
+            try :
+                ippmessage = IPPMessage(ippdatafile.read())
+            except IPPError, msg :    
+                self.logInfo("Error while parsing %s : %s" % (ippmessagefile, msg), "warn")
+            else :    
+                self.logDebug("Parsing of IPP message file %s ends." % ippmessagefile)
+            ippdatafile.close()
+        return (ippmessagefile, ippmessage)
+                
+    def exportAttributes(self) :    
+        """Exports our backend's attributes to the environment."""
+        os.environ["DEVICE_URI"] = self.DeviceURI       # WARNING !
+        os.environ["TEAPRINTERNAME"] = self.PrinterName
+        os.environ["TEADIRECTORY"] = self.Directory
+        os.environ["TEADATAFILE"] = self.DataFile
+        os.environ["TEAJOBSIZE"] = str(self.JobSize)
+        os.environ["TEAMD5SUM"] = self.JobMD5Sum
+        os.environ["TEACLIENTHOST"] = self.ClientHost or ""
+        os.environ["TEAJOBID"] = self.JobId
+        os.environ["TEAUSERNAME"] = self.UserName
+        os.environ["TEATITLE"] = self.Title
+        os.environ["TEACOPIES"] = str(self.Copies)
+        os.environ["TEAOPTIONS"] = self.Options
+        os.environ["TEAINPUTFILE"] = self.InputFile or ""
+        os.environ["TEABILLING"] = self.JobBilling or ""
+        os.environ["TEACONTROLFILE"] = self.ControlFile
+        
+    def saveDatasAndCheckSum(self) :
+        """Saves the input datas into a static file."""
+        self.logDebug("Duplicating data stream into %s" % self.DataFile)
+        mustclose = 0
+        if self.InputFile is not None :
+            infile = open(self.InputFile, "rb")
+            mustclose = 1
+        else :    
+            infile = sys.stdin
+        CHUNK = 64*1024         # read 64 Kb at a time
+        dummy = 0
+        sizeread = 0
+        checksum = md5.new()
+        outfile = open(self.DataFile, "wb")    
+        while 1 :
+            data = infile.read(CHUNK) 
+            if not data :
+                break
+            sizeread += len(data)    
+            outfile.write(data)
+            checksum.update(data)    
+            if not (dummy % 32) : # Only display every 2 Mb
+                self.logDebug("%s bytes saved..." % sizeread)
+            dummy += 1    
+        outfile.close()
+        if mustclose :    
+            infile.close()
+        self.JobSize = sizeread    
+        self.JobMD5Sum = checksum.hexdigest()
+        self.logDebug("Job %s is %s bytes long." % (self.JobId, self.JobSize))
+        self.logDebug("Job %s MD5 sum is %s" % (self.JobId, self.JobMD5Sum))
+
+    def cleanUp(self) :
+        """Cleans up the place."""
+        if not self.isTrue(self.getPrintQueueOption(self.PrinterName, "keepfiles", ignore=1)) :
+            os.remove(self.DataFile)
+            
+    def sigtermHandler(self, signum, frame) :
+        """Sets an attribute whenever SIGTERM is received."""
+        self.gotSigTerm = 1
+        self.logInfo("SIGTERM received for Job %s." % self.JobId)
+        
+    def runBranches(self) :         
+        """Launches each hook or tee defined for the current print queue."""
+        exitcode = 0
+        self.isCancelled = 0    # did a prehook cancel the print job ?
+        self.gotSigTerm = 0
+        signal.signal(signal.SIGTERM, self.sigtermHandler)
+        serialize = self.isTrue(self.getPrintQueueOption(self.PrinterName, "serialize", ignore=1))
+        for branchtype in ["prehook", "tee", "posthook"] :
+            branches = self.enumBranches(self.PrinterName, branchtype)
+            status = self.runCommands(branchtype, branches, serialize)
+            if status :
+                exitcode = status
+            if (branchtype == "prehook") and self.isCancelled :
+                break # We don't want to execute tees or posthooks in this case
+        signal.signal(signal.SIGTERM, signal.SIG_IGN)
+        if not exitcode :
+            self.logInfo("OK")
+        else :    
+            self.logInfo("An error occured, please check CUPS' error_log file.")
+        return exitcode
+        
+    def runCommands(self, btype, branches, serialize) :    
+        """Runs the commands for a particular branch type."""
+        exitcode = 0 
+        btype = btype.lower()
+        btypetitle = btype.title()
+        branchlist = branches.keys()    
+        branchlist.sort()
+        if serialize :
+            self.logDebug("Begin serialized %ss" % btypetitle)
+            if (btype == "tee") and self.RealBackend :
+                self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName))
+                retcode = self.runOriginalBackend()
+                if os.WIFEXITED(retcode) :
+                    retcode = os.WEXITSTATUS(retcode)
+                os.environ["TEASTATUS"] = str(retcode)
+                exitcode = retcode
+            for branch in branchlist :
+                command = branches[branch]
+                if self.gotSigTerm :
+                    break
+                self.logDebug("Launching %s : %s" % (branch, command))
+                retcode = os.system(command)
+                self.logDebug("Exit code for %s %s on printer %s is %s" % (btype, branch, self.PrinterName, retcode))
+                if os.WIFEXITED(retcode) :
+                    retcode = os.WEXITSTATUS(retcode)
+                if retcode :    
+                    if (btype == "prehook") and (retcode == 255) : # -1
+                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
+                        self.isCancelled = 1
+                    else :    
+                        self.logInfo("%s %s on printer %s didn't exit successfully." % (btypetitle, branch, self.PrinterName), "error")
+                        exitcode = 1
+            self.logDebug("End serialized %ss" % btypetitle)
+        else :        
+            self.logDebug("Begin forked %ss" % btypetitle)
+            pids = {}
+            if (btype == "tee") and self.RealBackend :
+                branches["Original backend"] = None     # Fakes a tee to launch one more child
+                branchlist = ["Original backend"] + branchlist
+            for branch in branchlist :
+                command = branches[branch]
+                if self.gotSigTerm :
+                    break
+                pid = os.fork()
+                if pid :
+                    pids[branch] = pid
+                else :    
+                    if branch == "Original backend" :
+                        self.logDebug("Launching original backend %s for printer %s" % (self.RealBackend, self.PrinterName))
+                        sys.exit(self.runOriginalBackend())
+                    else :
+                        self.logDebug("Launching %s : %s" % (branch, command))
+                        retcode = os.system(command)
+                        if os.WIFEXITED(retcode) :
+                            retcode = os.WEXITSTATUS(retcode)
+                        else :    
+                            retcode = -1
+                        sys.exit(retcode)
+            for (branch, pid) in pids.items() :
+                (childpid, retcode) = os.waitpid(pid, 0)
+                self.logDebug("Exit code for %s %s (PID %s) on printer %s is %s" % (btype, branch, childpid, self.PrinterName, retcode))
+                if os.WIFEXITED(retcode) :
+                    retcode = os.WEXITSTATUS(retcode)
+                if retcode :    
+                    if (btype == "prehook") and (retcode == 255) : # -1
+                        self.logInfo("Job %s cancelled by prehook %s" % (self.JobId, branch))
+                        self.isCancelled = 1
+                    else :    
+                        self.logInfo("%s %s (PID %s) on printer %s didn't exit successfully." % (btypetitle, branch, childpid, self.PrinterName), "error")
+                        exitcode = 1
+                if branch == "Original backend" :    
+                    os.environ["TEASTATUS"] = str(retcode)
+            self.logDebug("End forked %ss" % btypetitle)
+        return exitcode
+        
+    def unregisterFileNo(self, pollobj, fileno) :                
+        """Removes a file handle from the polling object."""
+        try :
+            pollobj.unregister(fileno)
+        except KeyError :    
+            self.logInfo("File number %s unregistered twice from polling object, ignored." % fileno, "warn")
+        except :    
+            self.logDebug("Error while unregistering file number %s from polling object." % fileno)
+        else :    
+            self.logDebug("File number %s unregistered from polling object." % fileno)
+            
+    def formatFileEvent(self, fd, mask) :        
+        """Formats file debug info."""
+        maskval = []
+        if mask & select.POLLIN :
+            maskval.append("POLLIN")
+        if mask & select.POLLOUT :
+            maskval.append("POLLOUT")
+        if mask & select.POLLPRI :
+            maskval.append("POLLPRI")
+        if mask & select.POLLERR :
+            maskval.append("POLLERR")
+        if mask & select.POLLHUP :
+            maskval.append("POLLHUP")
+        if mask & select.POLLNVAL :
+            maskval.append("POLLNVAL")
+        return "%s (%s)" % (fd, " | ".join(maskval))
+        
+    def runOriginalBackend(self) :    
+        """Launches the original backend."""
+        originalbackend = os.path.join(os.path.split(sys.argv[0])[0], self.RealBackend)
+        arguments = sys.argv
+        self.logDebug("Starting original backend %s with args %s" % (originalbackend, " ".join(['"%s"' % a for a in ([os.environ["DEVICE_URI"]] + arguments[1:])])))
+        subprocess = Popen4ForCUPS([originalbackend] + arguments[1:], bufsize=0, arg0=os.environ["DEVICE_URI"])
+        
+        # Save file descriptors, we will need them later.
+        stderrfno = sys.stderr.fileno()
+        fromcfno = subprocess.fromchild.fileno()
+        tocfno = subprocess.tochild.fileno()
+        
+        # We will have to be careful when dealing with I/O 
+        # So we use a poll object to know when to read or write
+        pollster = select.poll()
+        pollster.register(fromcfno, select.POLLIN | select.POLLPRI)
+        pollster.register(stderrfno, select.POLLOUT)
+        pollster.register(tocfno, select.POLLOUT)
+        
+        # Initialize our buffers
+        indata = ""
+        outdata = ""
+        endinput = endoutput = 0
+        inputclosed = outputclosed = 0
+        totaltochild = totalfromcups = 0
+        totalfromchild = totaltocups = 0
+        
+        if self.InputFile is None :
+           # this is not a real file, we read the job's data
+            # from our temporary file which is a copy of stdin 
+            inf = open(self.DataFile, "rb")
+            infno = inf.fileno()
+            pollster.register(infno, select.POLLIN | select.POLLPRI)
+        else :    
+            # job's data is in a file, no need to pass the data
+            # to the original backend
+            self.logDebug("Job's data is in %s" % self.InputFile)
+            infno = None
+            endinput = 1
+        
+        self.logDebug("Entering streams polling loop...")
+        MEGABYTE = 1024*1024
+        killed = 0
+        status = -1
+        while (status == -1) and (not killed) and not (inputclosed and outputclosed) :
+            # First check if original backend is still alive
+            status = subprocess.poll()
+            
+            # Now if we got SIGTERM, we have 
+            # to kill -TERM the original backend
+            if self.gotSigTerm and not killed :
+                try :
+                    os.kill(subprocess.pid, signal.SIGTERM)
+                except OSError, msg : # ignore but logs if process was already killed.
+                    self.logDebug("Error while sending signal to pid %s : %s" % (subprocess.pid, msg))
+                else :    
+                    self.logInfo(_("SIGTERM was sent to original backend %s (PID %s)") % (originalbackend, subprocess.pid))
+                    killed = 1
+            
+            # In any case, deal with any remaining I/O
+            try :
+                availablefds = pollster.poll(5000)
+            except select.error, msg :    
+                self.logDebug("Interrupted poll : %s" % msg)
+                availablefds = []
+            if not availablefds :
+                self.logDebug("Nothing to do, sleeping a bit...")
+                time.sleep(0.01) # give some time to the system
+            else :
+                for (fd, mask) in availablefds :
+                    try :
+                        if mask & select.POLLOUT :
+                            # We can write
+                            if fd == tocfno :
+                                if indata :
+                                    try :
+                                        nbwritten = os.write(fd, indata)    
+                                    except (OSError, IOError), msg :    
+                                        self.logDebug("Error while writing to original backend's stdin %s : %s" % (fd, msg))
+                                    else :    
+                                        if len(indata) != nbwritten :
+                                            self.logDebug("Short write to original backend's input !")
+                                        totaltochild += nbwritten    
+                                        self.logDebug("%s bytes sent to original backend so far..." % totaltochild)
+                                        indata = indata[nbwritten:]
+                                else :        
+                                    self.logDebug("No data to send to original backend yet, sleeping a bit...")
+                                    time.sleep(0.01)
+                                    
+                                if endinput :    
+                                    self.unregisterFileNo(pollster, tocfno)        
+                                    self.logDebug("Closing original backend's stdin.")
+                                    os.close(tocfno)
+                                    inputclosed = 1
+                            elif fd == stderrfno :
+                                if outdata :
+                                    try :
+                                        nbwritten = os.write(fd, outdata)
+                                    except (OSError, IOError), msg :    
+                                        self.logDebug("Error while writing to CUPS back channel (stderr) %s : %s" % (fd, msg))
+                                    else :
+                                        if len(outdata) != nbwritten :
+                                            self.logDebug("Short write to stderr (CUPS) !")
+                                        totaltocups += nbwritten    
+                                        self.logDebug("%s bytes sent back to CUPS so far..." % totaltocups)
+                                        outdata = outdata[nbwritten:]
+                                else :        
+                                    # self.logDebug("No data to send back to CUPS yet, sleeping a bit...") # Uncommenting this fills your logs
+                                    time.sleep(0.01) # Give some time to the system, stderr is ALWAYS writeable it seems.
+                                    
+                                if endoutput :    
+                                    self.unregisterFileNo(pollster, stderrfno)        
+                                    outputclosed = 1
+                            else :    
+                                self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
+                                time.sleep(0.01)
+                                
+                        if mask & (select.POLLIN | select.POLLPRI) :     
+                            # We have something to read
+                            try :
+                                data = os.read(fd, MEGABYTE)
+                            except (IOError, OSError), msg :    
+                                self.logDebug("Error while reading file %s : %s" % (fd, msg))
+                            else :
+                                if fd == infno :
+                                    if not data :    # If yes, then no more input data
+                                        self.unregisterFileNo(pollster, infno)
+                                        self.logDebug("Input data ends.")
+                                        endinput = 1 # this happens with real files.
+                                    else :    
+                                        indata += data
+                                        totalfromcups += len(data)
+                                        self.logDebug("%s bytes read from CUPS so far..." % totalfromcups)
+                                elif fd == fromcfno :
+                                    if not data :
+                                        self.logDebug("No back channel data to read from original backend yet, sleeping a bit...")
+                                        time.sleep(0.01)
+                                    else :
+                                        outdata += data
+                                        totalfromchild += len(data)
+                                        self.logDebug("%s bytes read from original backend so far..." % totalfromchild)
+                                else :    
+                                    self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
+                                    time.sleep(0.01)
+                                    
+                        if mask & (select.POLLHUP | select.POLLERR) :
+                            # Treat POLLERR as an EOF.
+                            # Some standard I/O stream has no more datas
+                            self.unregisterFileNo(pollster, fd)
+                            if fd == infno :
+                                # Here we are in the case where the input file is stdin.
+                                # which has no more data to be read.
+                                self.logDebug("Input data ends.")
+                                endinput = 1
+                            elif fd == fromcfno :    
+                                # We are no more interested in this file descriptor        
+                                self.logDebug("Closing original backend's stdout+stderr.")
+                                os.close(fromcfno)
+                                endoutput = 1
+                            else :    
+                                self.logDebug("Unexpected : %s - Sleeping a bit..." % self.formatFileEvent(fd, mask))
+                                time.sleep(0.01)
+                                
+                        if mask & select.POLLNVAL :        
+                            self.logDebug("File %s was closed. Unregistering from polling object." % fd)
+                            self.unregisterFileNo(pollster, fd)
+                    except IOError, msg :            
+                        self.logDebug("Got an IOError : %s" % msg) # we got signalled during an I/O
+                
+        # We must close the original backend's input stream
+        if killed and not inputclosed :
+            self.logDebug("Forcing close of original backend's stdin.")
+            os.close(tocfno)
+        
+        self.logDebug("Exiting streams polling loop...")
+        
+        self.logDebug("input data's final length : %s" % len(indata))
+        self.logDebug("back-channel data's final length : %s" % len(outdata))
+        
+        self.logDebug("Total bytes read from CUPS (job's datas) : %s" % totalfromcups)
+        self.logDebug("Total bytes sent to original backend (job's datas) : %s" % totaltochild)
+        
+        self.logDebug("Total bytes read from original backend (back-channel datas) : %s" % totalfromchild)
+        self.logDebug("Total bytes sent back to CUPS (back-channel datas) : %s" % totaltocups)
+        
+        # Check exit code of original CUPS backend.    
+        if status == -1 :
+            # we exited the loop before the original backend exited
+            # now we have to wait for it to finish and get its status
+            self.logDebug("Waiting for original backend to exit...")
+            try :
+                status = subprocess.wait()
+            except OSError : # already dead : TODO : detect when abnormal
+                status = 0
+        if os.WIFEXITED(status) :
+            return os.WEXITSTATUS(status)
+        elif not killed :    
+            self.logInfo("CUPS backend %s died abnormally." % originalbackend, "error")
+            return -1
+        else :    
+            return 1
+        
+if __name__ == "__main__" :    
+    # This is a CUPS backend, we should act and die like a CUPS backend
+    wrapper = CupsBackend()
+    if len(sys.argv) == 1 :
+        print "\n".join(wrapper.discoverOtherBackends())
+        sys.exit(0)                
+    elif len(sys.argv) not in (6, 7) :    
+        sys.stderr.write("ERROR: %s job-id user title copies options [file]\n"\
+                              % sys.argv[0])
+        sys.exit(1)
+    else :    
+        try :
+            wrapper.initBackend()
+            wrapper.saveDatasAndCheckSum()
+            wrapper.exportAttributes()
+            retcode = wrapper.runBranches()
+            wrapper.cleanUp()
+        except SystemExit, e :    
+            retcode = e.code
+        except :    
+            import traceback
+            lines = []
+            for line in traceback.format_exception(*sys.exc_info()) :
+                lines.extend([l for l in line.split("\n") if l])
+            msg = "ERROR: ".join(["%s (PID %s) : %s\n" % (wrapper.MyName, wrapper.pid, l) for l in (["ERROR: Tea4CUPS v%s" % version] + lines)])
+            sys.stderr.write(msg)
+            sys.stderr.flush()
+            retcode = 1
+        sys.exit(retcode)
Index: tea4cups/tags/2.10/NEWS
===================================================================
--- tea4cups/tags/2.10/NEWS (revision 615)
+++ tea4cups/tags/2.10/NEWS (revision 615)
@@ -0,0 +1,41 @@
+# $Id$
+
+Tea4CUPS : Tee for CUPS
+
+(c) 2005 Jerome Alet <alet@librelogiciel.com>
+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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+=============================================================================
+
+Tea4CUPS News :
+   
+  * 2.10 : 
+  
+    - Makes the IPP message filename and the Job's billing code available.
+    
+  * 2.00 :
+
+    - Introduces the notions of pre and post hooks.
+    
+    - Prehooks can decide to entirely cancel the print job if needed.
+
+    - Original CUPS backend's exit code is available in posthooks.
+
+    - prehooks, posthooks and tees are now launched in alphabetical order.
+
+  * 1.00 :
+
+    - First Official release.
+
Index: tea4cups/tags/2.10/tea4cups.conf
===================================================================
--- tea4cups/tags/2.10/tea4cups.conf (revision 615)
+++ tea4cups/tags/2.10/tea4cups.conf (revision 615)
@@ -0,0 +1,141 @@
+# $Id$
+#
+# Tea4CUPS : Tee for CUPS
+#
+# (c) 2005 Jerome Alet <alet@librelogiciel.com>
+# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+# 
+#
+
+# First we set all top-level directives in the [global] section
+[global]
+
+# Should we log debugging information to CUPS' error_log file ?
+# defaults to No if unset.
+debug : yes
+
+# In which directory will we create our files ? It must already exist !
+# This directive MUST be present since there's no sane default value.
+# Can be set either in the [global] section or any print queue section.
+# The value defined in a print queue section takes precedence over the
+# value defined in the [global] section.
+# directory : /var/spool/tea4cups/
+directory : /var/spool/cups/
+
+# Should Tea4CUPS keep the files it creates once all tees have ended ?
+# Defaults to No if unset, meaning that files are automatically deleted
+# once all tees have ended.
+# Can be set either in the [global] section or any print queue section.
+# The value defined in a print queue section takes precedence over the
+# value defined in the [global] section.
+# BEWARE : this may use huge amounts of disk space !
+# keepfiles : yes
+
+# Should we serialize the launch of all tees : launch one tee after
+# the other to save some system resources.
+# Defaults to No if unset, meaning that all tees (or hooks) are launched in
+# parallel.
+#
+# NB : in any case, hooks or tees names are sorted alphabetically and 
+# are launched in this sort order (obviously when launched in parallel
+# this is unnoticeable).
+# 
+# Can be set either in the [global] section or any print queue section.
+# The value defined in a print queue section takes precedence over the
+# value defined in the [global] section.
+# This value also applies to prehooks and posthooks (see below)
+# serialize : yes
+
+# When executing the contents of a tee, prehook or posthook directive, 
+# tea4cups makes the following environment variables available to your
+# own commands :
+#
+# TEAPRINTERNAME : The print queue name.
+# TEADIRECTORY : Tea4CUPS output directory.
+# TEADATAFILE : Full name of Tea4CUPS work file (in $TEADIRECTORY).
+# TEAJOBSIZE : Job's size in bytes.
+# TEAMD5SUM : MD5 sum of the job's datas.
+# TEACLIENTHOST : Client's hostname or IP address.
+# TEAJOBID : Job's Id.
+# TEAUSERNAME : Name of the user who launched the print job.
+# TEATITLE : Job's title.
+# TEACOPIES : Number of copies requested.
+# TEAOPTIONS : Options of the print job.
+# TEAINPUTFILE : Job's data file or empty when job read from stdin.
+# TEABILLING : Job's billing code (lp -o job-billing=SomeCode file.ps)
+# TEACONTROLFILE : Job's IPP message file (usually /var/spool/cups/c?????)
+#
+# Your own commands will mostly be interested in TEADATAFILE which is
+# the name of the file from which your commands may extract the final
+# job's datas. Don't rely on TEAINPUTFILE, use TEADATAFILE instead
+# since the first one may be empty depending on your printer driver.
+        
+# Now defines some default tees which will always be launched
+# at the same time that the job's datas are being sent to the 
+# printer.
+# The tee names are completely free BUT THEY MUST BEGIN WITH 'tee_'
+#
+# These are just some stupid examples.
+#tee_0 : cat $TEADATAFILE >/tmp/$TEAJOBID.prn
+#tee_pdf : cat $TEADATAFILE | su -c "lp -dPDFGenerator" $TEAUSERNAME
+
+# Some hooks : prehooks and posthooks
+#
+# Contrary to tees, prehooks are guaranteed to be launched 
+# BEFORE the job's datas are sent to the printer, and 
+# posthooks are guaranteed to be launched AFTER the job's
+# datas have been sent to the printer.
+#
+# prehook names are completely free BUT THEY MUST BEGIN WITH 'prehook_'
+# posthook names are completely free BUT THEY MUST BEGIN WITH 'posthook_'
+#
+# An additionnal environment variable is made available to posthooks,
+# named TEASTATUS which contains the exitcode of the real CUPS backend.
+# The normal value is 0, meaning that the real CUPS backend exited
+# successfully. Any other value indicates that a problem occured
+# in the CUPS backend which handles the transmission of the job
+# to the printer.
+# 
+# prehook_0 : echo "Your print job has been accepted" | smbclient -M $TEAUSERNAME
+# posthook_0 : echo "Your print job has been printed with status $TEASTATUS" | smbclient -M $TEAUSERNAME
+#
+# NB : as a special feature, any prehook which exits with a -1 status (255) 
+# causes the job to NOT be sent to the real backend, effectively cancelling it.
+# None of the tees and posthooks gets executed in this case, but all 
+# remaining prehooks are still executed.
+# 
+
+
+# Sample section for print queue HP2100
+# Uncomment and adapt to your needs.
+#
+#[HP2100]
+#
+# By using a same tee name as in the [global] section, the new
+# value takes precedence
+#tee_0 : cat $TEADATAFILE >~$TEAUSERNAME/savejobs/$TEAJOBID.prn
+
+# An empty value deletes a value defined in the [global] section
+# so this particular tee doesn't get executed.
+#tee_pdf : 
+
+# A reflector which produces 4 copies each time :
+#tee_4copies : lp -dotherprinter -n4 $CUPSDATAFILE 
+
+# A simple accounting mechanism 
+#tee_accounting : echo $TEAPRINTERNAME $TEAJOBID $TEAUSERNAME `pkpgcounter $TEADATAFILE` >/var/log/printaccounting.log
+
+# An additionnal posthook :
+#posthook_dummy : echo "$TEAJOBID : $TEAMD5SUM" >>/tmp/jobmd5sums
Index: tea4cups/tags/2.10/CREDITS
===================================================================
--- tea4cups/tags/2.10/CREDITS (revision 611)
+++ tea4cups/tags/2.10/CREDITS (revision 611)
@@ -0,0 +1,41 @@
+# $Id$
+
+Tea4CUPS : Tee for CUPS
+
+(c) 2005 Jerome Alet <alet@librelogiciel.com>
+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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+============================================================
+
+Supporters :
+------------
+
+  The following people supports the Tea4CUPS project enhancement
+  by funding it :
+  
+  - Anwar Bashir - University of Teesside
+
+==============================================================
+
+  IF YOUR NAME DOESN'T APPEAR IN THE LISTS ABOVE, AND YOU
+  THINK YOU DESERVE TO BE LISTED, JUST SEND ME AN EMAIL
+  ASKING FOR BEING INCLUDED.
+  
+  I APOLOGIZE IN ADVANCE IF I'VE FORGOTTEN TO ADD YOUR NAME.
+  
+  ALSO, SOME PEOPLE MAY HAVE REFUSED TO BE LISTED HERE, THIS 
+  IS YOUR RIGHT TO DO SO TOO, JUST TELL ME.
+  
+==============================================================
Index: tea4cups/tags/2.10/README
===================================================================
--- tea4cups/tags/2.10/README (revision 617)
+++ tea4cups/tags/2.10/README (revision 617)
@@ -0,0 +1,141 @@
+# $Id$
+
+Tea4CUPS : Tee for CUPS
+
+(c) 2005 Jerome Alet <alet@librelogiciel.com>
+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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+=============================================================================
+
+Tea4CUPS is the equivalent of the *nix command 'tee', but as a CUPS
+backend.
+
+Tea4CUPS behaves just like any other CUPS backend, but allows you to
+transparently send print jobs' datas to any number of outputs : other
+CUPS backends, files or pipes.
+
+This for example allows you to output the same print job on several
+printers at the same time, which is not possible with CUPS.
+
+Another possibility would be for example to send the same document to 
+a printer, a PDF generator, a Fax, and as an attachment to an email
+message, all of this by printing it a single time.
+
+Tea4CUPS provides three ways to launch commands :
+
+        - prehooks : these are guaranteed to be launched before the 
+                     print job is sent to the real printer.
+                     Any prehook which exits -1 can cancel the 
+                     print job.
+                     
+        - tees : these are launched at the same time the job is being             
+                 sent to the real printer, unless the job was 
+                 previously cancelled by a prehook.
+                 
+        - posthooks : these are guaranteed to be launched after the
+                      print job has been sent to the real printer,
+                      unless the job was previously cancelled by a
+                      prehook.
+                 
+To help your own commands, Tea4CUPS makes available as part of the
+environment several variables which can be used from the
+commands you use :
+
+        TEAPRINTERNAME : The print queue name.
+        TEADIRECTORY : Tea4CUPS output directory.
+        TEADATAFILE : Full name of Tea4CUPS work file (in $TEADIRECTORY).
+        TEAJOBSIZE : Job's size in bytes.
+        TEAMD5SUM : MD5 sum of the job's datas.
+        TEACLIENTHOST : Client's hostname or IP address.
+        TEAJOBID : Job's Id.
+        TEAUSERNAME : Name of the user who launched the print job.
+        TEATITLE : Job's title.
+        TEACOPIES : Number of copies requested.
+        TEAOPTIONS : Options of the print job.
+        TEAINPUTFILE : Print job's data file or empty when job read from stdin.
+        TEABILLING : Job's billing code (lp -o job-billing=SomeCode file.ps)
+        TEACONTROLFILE : Job's IPP message file (usually /var/spool/cups/c?????)
+        TEASTATUS : Original CUPS backend's exit code : ONLY AVAILABLE FROM 
+                    posthooks, obviously.
+        
+In the case you want to use both Tea4CUPS and PyKota, you MUST install 
+PyKota v1.22alpha2 or higher to avoid a race condition.
+
+=============================================================================
+
+Installation :
+--------------
+
+  0 - Download Tea4CUPS from :
+  
+        http://www.librelogiciel.com/software/Tea4CUPS/action_Presentation
+        
+      and extract it :  
+      
+        $ tar -zxf tea4cups-x.yy.tar.gz
+        
+        where x.yy is Tea4CUPS' version number.
+        
+  1 - Copy the 'tea4cups' command into CUPS' backend directory, 
+      for example :
+      
+        $ cp tea4cups /usr/lib/cups/backend
+        
+  2 - Restart CUPS in order for this new backend to be detected.        
+  
+  3 - Either from CUPS' web interface, add new printers with 
+      'Tea4CUPS managed' in front of the device's name.
+          
+      Or by directly modifying CUPS' printers.conf file, prepend    
+      each DeviceURI value with 'tea4cups://', and restart CUPS.
+      
+  4 - Copy tea4cups.conf into CUPS' configuration directory (where    
+      cupsd.conf resides) :
+      
+        $ cp tea4cups.conf /etc/cups/
+        
+  5 - Modify tea4cups.conf to suit your needs. Several examples      
+      are included.
+      
+  6 - There's no 6 !    
+  
+=============================================================================
+
+Troubleshooting : 
+-----------------
+
+  1 - Set "LogLevel debug2" in CUPS' cupsd.conf
+  
+  2 - Restart CUPS.
+  
+  3 - Set "debug: yes" in the [global] section of tea4cups.conf
+  
+  4 - Print something on a print queue managed
+      by Tea4CUPS.
+      
+  5 - Look at CUPS' error_log file for diagnostic and error messages.
+  
+=============================================================================
+
+CUPS (Common UNIX(r) Printing System) is trademark property of Easy Software 
+Products.
+
+You can download CUPS from :
+
+        http://www.cups.org
+
+=============================================================================
+    
+Please e-mail bugs to : alet@librelogiciel.com (Jerome Alet)
