Debian Codegraph @

ipapython/ipachangeconf.py

raw
1 #
2 # ipachangeconf - configuration file manipulation classes and functions
3 # partially based on authconfig code
4 # Copyright (c) 1999-2007 Red Hat, Inc.
5 # Author: Simo Sorce <[email protected]>
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 import fcntl
22 import logging
23 import os
24 import shutil
25
26 import six
27
28 if six.PY3:
29 unicode = str
30
31 logger = logging.getLogger(__name__)
32
33
34 def openLocked(filename, perms):
35 fd = -1
36 try:
37 fd = os.open(filename, os.O_RDWR | os.O_CREAT, perms)
38
39 fcntl.lockf(fd, fcntl.LOCK_EX)
40 except OSError as e:
41 if fd != -1:
42 try:
43 os.close(fd)
44 except OSError:
45 pass
46 raise IOError(e.errno, e.strerror)
47 return os.fdopen(fd, "r+")
48
49 # TODO: add subsection as a concept
50 # (ex. REALM.NAME = { foo = x bar = y } )
51 # TODO: put section delimiters as separating element of the list
52 # so that we can process multiple sections in one go
53 # TODO: add a comment all but provided options as a section option
54
55
56 class IPAChangeConf:
57 def __init__(self, name):
58 self.progname = name
59 self.indent = ("", "", "")
60 self.assign = (" = ", "=")
61 self.dassign = self.assign[0]
62 self.comment = ("#",)
63 self.dcomment = self.comment[0]
64 self.eol = ("\n",)
65 self.deol = self.eol[0]
66 self.sectnamdel = ("[", "]")
67 self.subsectdel = ("{", "}")
68 self.case_insensitive_sections = True
69
70 def setProgName(self, name):
71 self.progname = name
72
73 def setIndent(self, indent):
74 if type(indent) is tuple:
75 self.indent = indent
76 elif type(indent) is str:
77 self.indent = (indent, )
78 else:
79 raise ValueError('Indent must be a list of strings')
80
81 def setOptionAssignment(self, assign):
82 if type(assign) is tuple:
83 self.assign = assign
84 else:
85 self.assign = (assign, )
86 self.dassign = self.assign[0]
87
88 def setCommentPrefix(self, comment):
89 if type(comment) is tuple:
90 self.comment = comment
91 else:
92 self.comment = (comment, )
93 self.dcomment = self.comment[0]
94
95 def setEndLine(self, eol):
96 if type(eol) is tuple:
97 self.eol = eol
98 else:
99 self.eol = (eol, )
100 self.deol = self.eol[0]
101
102 def setSectionNameDelimiters(self, delims):
103 self.sectnamdel = delims
104
105 def setSubSectionDelimiters(self, delims):
106 self.subsectdel = delims
107
108 def matchComment(self, line):
109 for v in self.comment:
110 if line.lstrip().startswith(v):
111 return line.lstrip()[len(v):]
112 return False
113
114 def matchEmpty(self, line):
115 if line.strip() == "":
116 return True
117 return False
118
119 def matchSection(self, line):
120 cl = "".join(line.strip().split())
121 cl = cl.lower() if self.case_insensitive_sections else cl
122
123 if len(self.sectnamdel) != 2:
124 return False
125 if not cl.startswith(self.sectnamdel[0]):
126 return False
127 if not cl.endswith(self.sectnamdel[1]):
128 return False
129 return cl[len(self.sectnamdel[0]):-len(self.sectnamdel[1])]
130
131 def matchSubSection(self, line):
132 if self.matchComment(line):
133 return False
134
135 parts = line.split(self.dassign, 1)
136 if len(parts) < 2:
137 return False
138
139 if parts[1].strip() == self.subsectdel[0]:
140 return parts[0].strip()
141
142 return False
143
144 def matchSubSectionEnd(self, line):
145 if self.matchComment(line):
146 return False
147
148 if line.strip() == self.subsectdel[1]:
149 return True
150
151 return False
152
153 def getSectionLine(self, section):
154 if len(self.sectnamdel) != 2:
155 return section
156 return self._dump_line(self.sectnamdel[0],
157 section,
158 self.sectnamdel[1],
159 self.deol)
160
161 def _dump_line(self, *args):
162 return u"".join(unicode(x) for x in args)
163
164 def dump(self, options, level=0):
165 output = []
166 if level >= len(self.indent):
167 level = len(self.indent) - 1
168
169 for o in options:
170 if o['type'] == "section":
171 output.append(self._dump_line(self.sectnamdel[0],
172 o['name'],
173 self.sectnamdel[1]))
174 output.append(self.dump(o['value'], (level + 1)))
175 continue
176 if o['type'] == "subsection":
177 output.append(self._dump_line(self.indent[level],
178 o['name'],
179 self.dassign,
180 self.subsectdel[0]))
181 output.append(self.dump(o['value'], (level + 1)))
182 output.append(self._dump_line(self.indent[level],
183 self.subsectdel[1]))
184 continue
185 if o['type'] == "option":
186 delim = o.get('delim', self.dassign)
187 if delim not in self.assign:
188 raise ValueError(
189 'Unknown delim "%s" must be one of "%s"' %
190 (delim, " ".join(list(self.assign)))
191 )
192 output.append(self._dump_line(self.indent[level],
193 o['name'],
194 delim,
195 o['value']))
196 continue
197 if o['type'] == "comment":
198 output.append(self._dump_line(self.dcomment, o['value']))
199 continue
200 if o['type'] == "empty":
201 output.append('')
202 continue
203 raise SyntaxError('Unknown type: [%s]' % o['type'])
204
205 # append an empty string to the output so that we add eol to the end
206 # of the file contents in a single join()
207 output.append('')
208 return self.deol.join(output)
209
210 def parseLine(self, line):
211
212 if self.matchEmpty(line):
213 return {'name': 'empty', 'type': 'empty'}
214
215 value = self.matchComment(line)
216 if value:
217 return {'name': 'comment',
218 'type': 'comment',
219 'value': value.rstrip()}
220
221 o = dict()
222 parts = line.split(self.dassign, 1)
223 if len(parts) < 2:
224 # The default assign didn't match, try the non-default
225 for d in self.assign[1:]:
226 parts = line.split(d, 1)
227 if len(parts) >= 2:
228 o['delim'] = d
229 break
230
231 if 'delim' not in o:
232 raise SyntaxError('Syntax Error: Unknown line format')
233
234 o.update({'name': parts[0].strip(), 'type': 'option',
235 'value': parts[1].rstrip()})
236 return o
237
238 def findOpts(self, opts, type, name, exclude_sections=False):
239
240 num = 0
241 for o in opts:
242 if o['type'] == type and o['name'] == name:
243 return (num, o)
244 if exclude_sections and (o['type'] == "section" or
245 o['type'] == "subsection"):
246 return (num, None)
247 num += 1
248 return (num, None)
249
250 def commentOpts(self, inopts, level=0):
251
252 opts = []
253
254 if level >= len(self.indent):
255 level = len(self.indent) - 1
256
257 for o in inopts:
258 if o['type'] == 'section':
259 no = self.commentOpts(o['value'], (level + 1))
260 val = self._dump_line(self.dcomment,
261 self.sectnamdel[0],
262 o['name'],
263 self.sectnamdel[1])
264 opts.append({'name': 'comment',
265 'type': 'comment',
266 'value': val})
267 for n in no:
268 opts.append(n)
269 continue
270 if o['type'] == 'subsection':
271 no = self.commentOpts(o['value'], (level + 1))
272 val = self._dump_line(self.indent[level],
273 o['name'],
274 self.dassign,
275 self.subsectdel[0])
276 opts.append({'name': 'comment',
277 'type': 'comment',
278 'value': val})
279 opts.extend(no)
280 val = self._dump_line(self.indent[level], self.subsectdel[1])
281 opts.append({'name': 'comment',
282 'type': 'comment',
283 'value': val})
284 continue
285 if o['type'] == 'option':
286 delim = o.get('delim', self.dassign)
287 if delim not in self.assign:
288 val = self._dump_line(self.indent[level],
289 o['name'],
290 delim,
291 o['value'])
292 opts.append({'name': 'comment', 'type': 'comment',
293 'value': val})
294 continue
295 if o['type'] == 'comment':
296 opts.append(o)
297 continue
298 if o['type'] == 'empty':
299 opts.append({'name': 'comment',
300 'type': 'comment',
301 'value': ''})
302 continue
303 raise SyntaxError('Unknown type: [%s]' % o['type'])
304
305 return opts
306
307 def mergeOld(self, oldopts, newopts):
308
309 opts = []
310
311 for o in oldopts:
312 if o['type'] == "section" or o['type'] == "subsection":
313 _num, no = self.findOpts(newopts, o['type'], o['name'])
314 if not no:
315 opts.append(o)
316 continue
317 if no['action'] == "set":
318 mo = self.mergeOld(o['value'], no['value'])
319 opts.append({'name': o['name'],
320 'type': o['type'],
321 'value': mo})
322 continue
323 if no['action'] == "comment":
324 co = self.commentOpts(o['value'])
325 for c in co:
326 opts.append(c)
327 continue
328 if no['action'] == "remove":
329 continue
330 raise SyntaxError('Unknown action: [%s]' % no['action'])
331
332 if o['type'] == "comment" or o['type'] == "empty":
333 opts.append(o)
334 continue
335
336 if o['type'] == "option":
337 _num, no = self.findOpts(newopts, 'option', o['name'], True)
338 if not no:
339 opts.append(o)
340 continue
341 if no['action'] == 'comment' or no['action'] == 'remove':
342 if (no['value'] is not None and
343 o['value'] is not no['value']):
344 opts.append(o)
345 continue
346 if no['action'] == 'comment':
347 value = self._dump_line(self.dcomment,
348 o['name'],
349 self.dassign,
350 o['value'])
351 opts.append({'name': 'comment',
352 'type': 'comment',
353 'value': value})
354 continue
355 if no['action'] == 'set':
356 opts.append(no)
357 continue
358 if no['action'] == 'addifnotset':
359 opts.append({
360 'name': 'comment',
361 'type': 'comment',
362 'value': self._dump_line(
363 ' ', no['name'], ' modified by IPA'
364 ),
365 })
366 opts.append({'name': 'comment', 'type': 'comment',
367 'value': self._dump_line(no['name'],
368 self.dassign,
369 no['value'],
370 )})
371 opts.append(o)
372 continue
373 raise SyntaxError('Unknown action: [%s]' % no['action'])
374
375 raise SyntaxError('Unknown type: [%s]' % o['type'])
376
377 return opts
378
379 def mergeNew(self, opts, newopts):
380
381 cline = 0
382
383 for no in newopts:
384
385 if no['type'] == "section" or no['type'] == "subsection":
386 (num, o) = self.findOpts(opts, no['type'], no['name'])
387 if not o:
388 if no['action'] == 'set':
389 opts.append(no)
390 continue
391 if no['action'] == "set":
392 self.mergeNew(o['value'], no['value'])
393 continue
394 cline = num + 1
395 continue
396
397 if no['type'] == "option":
398 (num, o) = self.findOpts(opts, no['type'], no['name'], True)
399 if not o:
400 if no['action'] == 'set' or no['action'] == 'addifnotset':
401 opts.append(no)
402 continue
403 cline = num + 1
404 continue
405
406 if no['type'] == "comment" or no['type'] == "empty":
407 opts.insert(cline, no)
408 cline += 1
409 continue
410
411 raise SyntaxError('Unknown type: [%s]' % no['type'])
412
413 def merge(self, oldopts, newopts):
414 """
415 Uses a two pass strategy:
416 First we create a new opts tree from oldopts removing/commenting
417 the options as indicated by the contents of newopts
418 Second we fill in the new opts tree with options as indicated
419 in the newopts tree (this is becaus eentire (sub)sections may
420 in the newopts tree (this is becaus entire (sub)sections may
421 exist in the newopts that do not exist in oldopts)
422 """
423 opts = self.mergeOld(oldopts, newopts)
424 self.mergeNew(opts, newopts)
425 return opts
426
427 # TODO: Make parse() recursive?
428 def parse(self, f):
429
430 opts = []
431 sectopts = []
432 section = None
433 subsectopts = []
434 subsection = None
435 curopts = opts
436 fatheropts = opts
437
438 # Read in the old file.
439 for line in f:
440
441 # It's a section start.
442 value = self.matchSection(line)
443 if value:
444 if section is not None:
445 opts.append({'name': section,
446 'type': 'section',
447 'value': sectopts})
448 sectopts = []
449 curopts = sectopts
450 fatheropts = sectopts
451 section = value
452 continue
453
454 # It's a subsection start.
455 value = self.matchSubSection(line)
456 if value:
457 if subsection is not None:
458 raise SyntaxError('nested subsections are not '
459 'supported yet')
460 subsectopts = []
461 curopts = subsectopts
462 subsection = value
463 continue
464
465 value = self.matchSubSectionEnd(line)
466 if value:
467 if subsection is None:
468 raise SyntaxError('Unmatched end subsection terminator '
469 'found')
470 fatheropts.append({'name': subsection,
471 'type': 'subsection',
472 'value': subsectopts})
473 subsection = None
474 curopts = fatheropts
475 continue
476
477 # Copy anything else as is.
478 try:
479 curopts.append(self.parseLine(line))
480 except SyntaxError as e:
481 raise SyntaxError('{error} in file {fname}: [{line}]'.format(
482 error=e, fname=f.name, line=line.rstrip()))
483
484 # Add last section if any
485 if len(sectopts) != 0:
486 opts.append({'name': section,
487 'type': 'section',
488 'value': sectopts})
489
490 return opts
491
492 def changeConf(self, file, newopts):
493 """
494 Write settings to configuration file
495 :param file: path to the file
496 :param options: set of dictionaries in the form:
497 {'name': 'foo', 'value': 'bar', 'action': 'set/comment'}
498 :param section: section name like 'global'
499 """
500 output = ""
501 f = None
502 try:
503 # Do not catch an unexisting file error
504 # we want to fail in that case
505 shutil.copy2(file, (file + ".ipabkp"))
506
507 f = openLocked(file, 0o644)
508
509 oldopts = self.parse(f)
510
511 options = self.merge(oldopts, newopts)
512
513 output = self.dump(options)
514
515 # Write it out and close it.
516 f.seek(0)
517 f.truncate(0)
518 f.write(output)
519 finally:
520 try:
521 if f:
522 f.close()
523 except IOError:
524 pass
525 logger.debug("Updating configuration file %s", file)
526 logger.debug(output)
527 return True
528
529 def newConf(self, file, options, file_perms=0o644):
530 """"
531 Write settings to a new file, backup the old
532 :param file: path to the file
533 :param options: a set of dictionaries in the form:
534 {'name': 'foo', 'value': 'bar', 'action': 'set/comment'}
535 :param file_perms: number defining the new file's permissions
536 """
537 output = ""
538 f = None
539 try:
540 try:
541 shutil.copy2(file, (file + ".ipabkp"))
542 except IOError as err:
543 if err.errno == 2:
544 # The orign file did not exist
545 pass
546
547 f = openLocked(file, file_perms)
548
549 # Trunkate
550 f.seek(0)
551 f.truncate(0)
552
553 output = self.dump(options)
554
555 f.write(output)
556 finally:
557 try:
558 if f:
559 f.close()
560 except IOError:
561 pass
562 logger.debug("Writing configuration file %s", file)
563 logger.debug(output)
564 return True
565
566 @staticmethod
567 def setOption(name, value):
568 return {'name': name,
569 'type': 'option',
570 'action': 'set',
571 'value': value}
572
573 @staticmethod
574 def rmOption(name):
575 return {'name': name,
576 'type': 'option',
577 'action': 'remove',
578 'value': None}
579
580 @staticmethod
581 def setSection(name, options):
582 return {'name': name,
583 'type': 'section',
584 'action': 'set',
585 'value': options}
586
587 @staticmethod
588 def emptyLine():
589 return {'name': 'empty',
590 'type': 'empty'}