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

Revision 764, 10.3 kB (checked in by jalet, 21 years ago)

Name check method moved here

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
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$
17# Revision 1.15  2003/02/08 22:09:52  jalet
18# Name check method moved here
19#
20# Revision 1.14  2003/02/07 10:42:45  jalet
21# Indentation problem
22#
23# Revision 1.13  2003/02/07 08:34:16  jalet
24# Test wrt date limit was wrong
25#
26# Revision 1.12  2003/02/06 23:20:02  jalet
27# warnpykota doesn't need any user/group name argument, mimicing the
28# warnquota disk quota tool.
29#
30# Revision 1.11  2003/02/06 22:54:33  jalet
31# warnpykota should be ok
32#
33# Revision 1.10  2003/02/06 15:03:11  jalet
34# added a method to set the limit date
35#
36# Revision 1.9  2003/02/06 10:39:23  jalet
37# Preliminary edpykota work.
38#
39# Revision 1.8  2003/02/06 09:19:02  jalet
40# More robust behavior (hopefully) when the user or printer is not managed
41# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
42# printer and/or user not 'yet?' in storage.
43#
44# Revision 1.7  2003/02/06 00:00:45  jalet
45# Now includes the printer name in email messages
46#
47# Revision 1.6  2003/02/05 23:55:02  jalet
48# Cleaner email messages
49#
50# Revision 1.5  2003/02/05 23:45:09  jalet
51# Better DateTime manipulation wrt grace delay
52#
53# Revision 1.4  2003/02/05 23:26:22  jalet
54# Incorrect handling of grace delay
55#
56# Revision 1.3  2003/02/05 22:16:20  jalet
57# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
58#
59# Revision 1.2  2003/02/05 22:10:29  jalet
60# Typos
61#
62# Revision 1.1  2003/02/05 21:28:17  jalet
63# Initial import into CVS
64#
65#
66#
67
68import sys
69import os
70import getopt
71import smtplib
72
73from mx import DateTime
74
75from pykota import version, config, storage, logger
76
77class PyKotaToolError(Exception):
78    """An exception for PyKota config related stuff."""
79    def __init__(self, message = ""):
80        self.message = message
81        Exception.__init__(self, message)
82    def __repr__(self):
83        return self.message
84    __str__ = __repr__
85   
86class PyKotaTool :   
87    """Base class for all PyKota command line tools."""
88    def __init__(self, isfilter=0, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
89        """Initializes the command line tool."""
90        self.documentation = doc
91        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
92        self.logger = logger.openLogger(self.config)
93        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
94        self.printername = os.environ.get("PRINTER", None)
95        self.smtpserver = self.config.getSMTPServer()
96        self.admin = self.config.getAdmin()
97        self.adminmail = self.config.getAdminMail()
98       
99    def display_version_and_quit(self) :
100        """Displays version number, then exists successfully."""
101        print version.__version__
102        sys.exit(0)
103   
104    def display_usage_and_quit(self) :
105        """Displays command line usage, then exists successfully."""
106        print self.documentation
107        sys.exit(0)
108       
109    def parseCommandline(self, argv, short, long, allownothing=0) :
110        """Parses the command line, controlling options."""
111        # split options in two lists: those which need an argument, those which don't need any
112        withoutarg = []
113        witharg = []
114        lgs = len(short)
115        i = 0
116        while i < lgs :
117            ii = i + 1
118            if (ii < lgs) and (short[ii] == ':') :
119                # needs an argument
120                witharg.append(short[i])
121                ii = ii + 1 # skip the ':'
122            else :
123                # doesn't need an argument
124                withoutarg.append(short[i])
125            i = ii
126               
127        for option in long :
128            if option[-1] == '=' :
129                # needs an argument
130                witharg.append(option[:-1])
131            else :
132                # doesn't need an argument
133                withoutarg.append(option)
134       
135        # we begin with all possible options unset
136        parsed = {}
137        for option in withoutarg + witharg :
138            parsed[option] = None
139       
140        # then we parse the command line
141        args = []       # to not break if something unexpected happened
142        try :
143            options, args = getopt.getopt(argv, short, long)
144            if options :
145                for (o, v) in options :
146                    # we skip the '-' chars
147                    lgo = len(o)
148                    i = 0
149                    while (i < lgo) and (o[i] == '-') :
150                        i = i + 1
151                    o = o[i:]
152                    if o in witharg :
153                        # needs an argument : set it
154                        parsed[o] = v
155                    elif o in withoutarg :
156                        # doesn't need an argument : boolean
157                        parsed[o] = 1
158                    else :
159                        # should never occur
160                        raise PyKotaToolError, "Unexpected problem when parsing command line"
161            elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
162                self.display_usage_and_quit()
163        except getopt.error, msg :
164            sys.stderr.write("%s\n" % msg)
165            sys.stderr.flush()
166            self.display_usage_and_quit()
167        return (parsed, args)
168   
169    def isValidName(self, name) :
170        """Checks if a user or printer name is valid."""
171        # unfortunately Python 2.1 string modules doesn't define ascii_letters...
172        asciiletters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
173        digits = '0123456789'
174        if name[0] in asciiletters :
175            validchars = asciiletters + digits + "-_"
176            for c in name[1:] :
177                if c not in validchars :
178                    return 0
179            return 1       
180        return 0
181       
182    def sendMessage(self, touser, fullmessage) :
183        """Sends an email message containing headers to some user."""
184        if "@" not in touser :
185            touser = "%s@%s" % (touser, self.smtpserver)
186        server = smtplib.SMTP(self.smtpserver)
187        server.sendmail(self.adminmail, [touser], fullmessage)
188        server.quit()
189       
190    def sendMessageToUser(self, username, subject, message) :
191        """Sends an email message to a user."""
192        message += "\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n" % (self.admin, self.adminmail)
193        self.sendMessage(username, "Subject: %s\n\n%s" % (subject, message))
194       
195    def sendMessageToAdmin(self, subject, message) :
196        """Sends an email message to the Print Quota administrator."""
197        self.sendMessage(self.adminmail, "Subject: %s\n\n%s" % (subject, message))
198       
199    def checkUserPQuota(self, username, printername) :
200        """Checks the user quota on a printer and deny or accept the job."""
201        quota = self.storage.getUserPQuota(username, printername)
202        if quota is None :
203            # Unknown user or printer or combination
204            policy = self.config.getPrinterPolicy(printername)
205            if policy in [None, "ALLOW"] :
206                action = "ALLOW"
207            else :   
208                action = "DENY"
209            self.logger.log_message("Unable to match user %s on printer %s, applying default policy (%s)" % (username, printername, action), "warn")
210            return (action, None, None)
211        else :   
212            pagecounter = quota["pagecounter"]
213            softlimit = quota["softlimit"]
214            hardlimit = quota["hardlimit"]
215            datelimit = quota["datelimit"]
216            if datelimit is not None :
217                datelimit = DateTime.ISO.ParseDateTime(datelimit)
218            if softlimit is not None :
219                if pagecounter < softlimit :
220                    action = "ALLOW"
221                elif hardlimit is not None :
222                    if softlimit <= pagecounter < hardlimit :   
223                        now = DateTime.now()
224                        if datelimit is None :
225                            datelimit = now + self.config.getGraceDelay()
226                            self.storage.setDateLimit(username, printername, datelimit)
227                        if now < datelimit :
228                            action = "WARN"
229                        else :   
230                            action = "DENY"
231                    else :         
232                        action = "DENY"
233                else :       
234                    action = "DENY"
235            else :       
236                action = "ALLOW"
237            return (action, (hardlimit - pagecounter), datelimit)
238   
239    def warnGroupPQuota(self, username, printername=None) :
240        """Checks a user quota and send him a message if quota is exceeded on current printer."""
241        pname = printername or self.printername
242        raise PyKotaToolError, "Group quotas are currently not implemented."
243       
244    def warnUserPQuota(self, username, printername=None) :
245        """Checks a user quota and send him a message if quota is exceeded on current printer."""
246        pname = printername or self.printername
247        (action, grace, gracedate) = self.checkUserPQuota(username, pname)
248        if action == "DENY" :
249            if (grace is not None) and (gracedate is not None) :
250                # only when both user and printer are known
251                adminmessage = "Print Quota exceeded for user %s on printer %s" % (username, pname)
252                self.logger.log_message(adminmessage)
253                self.sendMessageToUser(username, "Print Quota Exceeded", "You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s." % pname)
254                self.sendMessageToAdmin("Print Quota", adminmessage)
255        elif action == "WARN" :   
256            adminmessage = "Print Quota soft limit exceeded for user %s on printer %s" % (username, pname)
257            self.logger.log_message(adminmessage)
258            self.sendMessageToUser(username, "Print Quota Exceeded", "You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s." % pname)
259            self.sendMessageToAdmin("Print Quota", adminmessage)
260        return action       
261   
Note: See TracBrowser for help on using the browser.