root / pykota / trunk / pykota / tool.py @ 817

Revision 817, 11.7 kB (checked in by jalet, 21 years ago)

Added a method to match strings against wildcard patterns

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[695]1#! /usr/bin/env python
2
3# PyKota - Print Quotas for CUPS
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# You're welcome to redistribute this software under the
7# terms of the GNU General Public Licence version 2.0
8# or, at your option, any higher version.
9#
10# You can read the complete GNU GPL in the file COPYING
11# which should come along with this software, or visit
12# the Free Software Foundation's WEB site http://www.fsf.org
13#
14# $Id$
15#
16# $Log$
[817]17# Revision 1.22  2003/02/27 09:09:20  jalet
18# Added a method to match strings against wildcard patterns
19#
[804]20# Revision 1.21  2003/02/17 23:01:56  jalet
21# Typos
22#
[802]23# Revision 1.20  2003/02/17 22:55:01  jalet
24# More options can now be set per printer or globally :
25#
[804]26#       admin
27#       adminmail
28#       gracedelay
29#       requester
[802]30#
31# the printer option has priority when both are defined.
32#
[788]33# Revision 1.19  2003/02/10 11:28:45  jalet
34# Localization
35#
[782]36# Revision 1.18  2003/02/10 01:02:17  jalet
37# External requester is about to work, but I must sleep
38#
[773]39# Revision 1.17  2003/02/09 13:05:43  jalet
40# Internationalization continues...
41#
[772]42# Revision 1.16  2003/02/09 12:56:53  jalet
43# Internationalization begins...
44#
[764]45# Revision 1.15  2003/02/08 22:09:52  jalet
46# Name check method moved here
47#
[742]48# Revision 1.14  2003/02/07 10:42:45  jalet
49# Indentation problem
50#
[733]51# Revision 1.13  2003/02/07 08:34:16  jalet
52# Test wrt date limit was wrong
53#
[729]54# Revision 1.12  2003/02/06 23:20:02  jalet
55# warnpykota doesn't need any user/group name argument, mimicing the
56# warnquota disk quota tool.
57#
[728]58# Revision 1.11  2003/02/06 22:54:33  jalet
59# warnpykota should be ok
60#
[722]61# Revision 1.10  2003/02/06 15:03:11  jalet
62# added a method to set the limit date
63#
[715]64# Revision 1.9  2003/02/06 10:39:23  jalet
65# Preliminary edpykota work.
66#
[713]67# Revision 1.8  2003/02/06 09:19:02  jalet
68# More robust behavior (hopefully) when the user or printer is not managed
69# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
70# printer and/or user not 'yet?' in storage.
71#
[712]72# Revision 1.7  2003/02/06 00:00:45  jalet
73# Now includes the printer name in email messages
74#
[711]75# Revision 1.6  2003/02/05 23:55:02  jalet
76# Cleaner email messages
77#
[709]78# Revision 1.5  2003/02/05 23:45:09  jalet
79# Better DateTime manipulation wrt grace delay
80#
[708]81# Revision 1.4  2003/02/05 23:26:22  jalet
82# Incorrect handling of grace delay
83#
[699]84# Revision 1.3  2003/02/05 22:16:20  jalet
85# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
86#
[698]87# Revision 1.2  2003/02/05 22:10:29  jalet
88# Typos
89#
[695]90# Revision 1.1  2003/02/05 21:28:17  jalet
91# Initial import into CVS
92#
93#
94#
95
96import sys
97import os
[817]98import fnmatch
[715]99import getopt
[695]100import smtplib
[772]101import gettext
[782]102import locale
[695]103
[708]104from mx import DateTime
105
[715]106from pykota import version, config, storage, logger
[695]107
108class PyKotaToolError(Exception):
109    """An exception for PyKota config related stuff."""
110    def __init__(self, message = ""):
111        self.message = message
112        Exception.__init__(self, message)
113    def __repr__(self):
114        return self.message
115    __str__ = __repr__
116   
117class PyKotaTool :   
118    """Base class for all PyKota command line tools."""
[715]119    def __init__(self, isfilter=0, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
[695]120        """Initializes the command line tool."""
[772]121        # locale stuff
[788]122        try :
[782]123            locale.setlocale(locale.LC_ALL, "")
[788]124            gettext.install("pykota")
125        except (locale.Error, IOError) :
126            gettext.NullTranslations().install()
[772]127   
128        # pykota specific stuff
[715]129        self.documentation = doc
[695]130        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
[698]131        self.logger = logger.openLogger(self.config)
[695]132        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
133        self.printername = os.environ.get("PRINTER", None)
134        self.smtpserver = self.config.getSMTPServer()
135       
[715]136    def display_version_and_quit(self) :
137        """Displays version number, then exists successfully."""
138        print version.__version__
139        sys.exit(0)
140   
141    def display_usage_and_quit(self) :
142        """Displays command line usage, then exists successfully."""
143        print self.documentation
144        sys.exit(0)
145       
[729]146    def parseCommandline(self, argv, short, long, allownothing=0) :
[715]147        """Parses the command line, controlling options."""
148        # split options in two lists: those which need an argument, those which don't need any
149        withoutarg = []
150        witharg = []
151        lgs = len(short)
152        i = 0
153        while i < lgs :
154            ii = i + 1
155            if (ii < lgs) and (short[ii] == ':') :
156                # needs an argument
157                witharg.append(short[i])
158                ii = ii + 1 # skip the ':'
159            else :
160                # doesn't need an argument
161                withoutarg.append(short[i])
162            i = ii
163               
164        for option in long :
165            if option[-1] == '=' :
166                # needs an argument
167                witharg.append(option[:-1])
168            else :
169                # doesn't need an argument
170                withoutarg.append(option)
171       
172        # we begin with all possible options unset
173        parsed = {}
174        for option in withoutarg + witharg :
175            parsed[option] = None
176       
177        # then we parse the command line
178        args = []       # to not break if something unexpected happened
179        try :
180            options, args = getopt.getopt(argv, short, long)
181            if options :
182                for (o, v) in options :
183                    # we skip the '-' chars
184                    lgo = len(o)
185                    i = 0
186                    while (i < lgo) and (o[i] == '-') :
187                        i = i + 1
188                    o = o[i:]
189                    if o in witharg :
190                        # needs an argument : set it
191                        parsed[o] = v
192                    elif o in withoutarg :
193                        # doesn't need an argument : boolean
194                        parsed[o] = 1
195                    else :
196                        # should never occur
197                        raise PyKotaToolError, "Unexpected problem when parsing command line"
[729]198            elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
[715]199                self.display_usage_and_quit()
200        except getopt.error, msg :
201            sys.stderr.write("%s\n" % msg)
202            sys.stderr.flush()
203            self.display_usage_and_quit()
204        return (parsed, args)
205   
[764]206    def isValidName(self, name) :
207        """Checks if a user or printer name is valid."""
208        # unfortunately Python 2.1 string modules doesn't define ascii_letters...
209        asciiletters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
210        digits = '0123456789'
211        if name[0] in asciiletters :
212            validchars = asciiletters + digits + "-_"
213            for c in name[1:] :
214                if c not in validchars :
215                    return 0
216            return 1       
217        return 0
218       
[817]219    def matchString(self, s, patterns) :
220        """Returns 1 if the string s matches one of the patterns, else 0."""
221        for pattern in patterns :
222            if fnmatch.fnmatchcase(s, pattern) :
223                return 1
224        return 0
225       
[802]226    def sendMessage(self, adminmail, touser, fullmessage) :
[695]227        """Sends an email message containing headers to some user."""
228        if "@" not in touser :
229            touser = "%s@%s" % (touser, self.smtpserver)
230        server = smtplib.SMTP(self.smtpserver)
[802]231        server.sendmail(adminmail, [touser], fullmessage)
[695]232        server.quit()
233       
[802]234    def sendMessageToUser(self, admin, adminmail, username, subject, message) :
[695]235        """Sends an email message to a user."""
[802]236        message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail)
237        self.sendMessage(adminmail, username, "Subject: %s\n\n%s" % (subject, message))
[695]238       
[802]239    def sendMessageToAdmin(self, adminmail, subject, message) :
[695]240        """Sends an email message to the Print Quota administrator."""
[802]241        self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message))
[695]242       
[708]243    def checkUserPQuota(self, username, printername) :
244        """Checks the user quota on a printer and deny or accept the job."""
245        quota = self.storage.getUserPQuota(username, printername)
[713]246        if quota is None :
247            # Unknown user or printer or combination
248            policy = self.config.getPrinterPolicy(printername)
249            if policy in [None, "ALLOW"] :
[708]250                action = "ALLOW"
[713]251            else :   
252                action = "DENY"
[773]253            self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (username, printername, action), "warn")
[713]254            return (action, None, None)
255        else :   
256            pagecounter = quota["pagecounter"]
257            softlimit = quota["softlimit"]
258            hardlimit = quota["hardlimit"]
259            datelimit = quota["datelimit"]
260            if datelimit is not None :
261                datelimit = DateTime.ISO.ParseDateTime(datelimit)
262            if softlimit is not None :
263                if pagecounter < softlimit :
264                    action = "ALLOW"
265                elif hardlimit is not None :
[742]266                    if softlimit <= pagecounter < hardlimit :   
267                        now = DateTime.now()
268                        if datelimit is None :
[804]269                            datelimit = now + self.config.getGraceDelay(printername)
[742]270                            self.storage.setDateLimit(username, printername, datelimit)
271                        if now < datelimit :
272                            action = "WARN"
273                        else :   
274                            action = "DENY"
275                    else :         
276                        action = "DENY"
[713]277                else :       
278                    action = "DENY"
[708]279            else :       
[713]280                action = "ALLOW"
281            return (action, (hardlimit - pagecounter), datelimit)
[708]282   
[728]283    def warnGroupPQuota(self, username, printername=None) :
[695]284        """Checks a user quota and send him a message if quota is exceeded on current printer."""
[728]285        pname = printername or self.printername
[773]286        raise PyKotaToolError, _("Group quotas are currently not implemented.")
[728]287       
288    def warnUserPQuota(self, username, printername=None) :
289        """Checks a user quota and send him a message if quota is exceeded on current printer."""
290        pname = printername or self.printername
[802]291        admin = self.config.getAdmin(pname)
292        adminmail = self.config.getAdminMail(pname)
[728]293        (action, grace, gracedate) = self.checkUserPQuota(username, pname)
[695]294        if action == "DENY" :
[713]295            if (grace is not None) and (gracedate is not None) :
296                # only when both user and printer are known
[773]297                adminmessage = _("Print Quota exceeded for user %s on printer %s") % (username, pname)
[713]298                self.logger.log_message(adminmessage)
[802]299                self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % pname)
300                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
[695]301        elif action == "WARN" :   
[773]302            adminmessage = _("Print Quota soft limit exceeded for user %s on printer %s") % (username, pname)
[695]303            self.logger.log_message(adminmessage)
[802]304            self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % pname)
305            self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
[695]306        return action       
307   
Note: See TracBrowser for help on using the browser.