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