def check_config(self, val=None): """ Checks self.config_file or the filename passed using 'val' and returns a SafeConfigParser instance if everything is OK. """ if not val == None: config_file = val else: config_file = self.config_file if not os.access(config_file, os.R_OK): log.error(_("Configuration file %s not readable") % config_file) config = SafeConfigParser() log.debug(_("Reading configuration file %s") % config_file, level=8) try: config.read(config_file) except: log.error(_("Invalid configuration file %s") % config_file) if not config.has_section("kolab"): log.warning( _("No master configuration section [kolab] in configuration file %s" ) % config_file) return config
def run(self): if os.path.isfile('/sys/fs/selinux/enforce'): if os.access('/sys/fs/selinux/enforce', os.R_OK): # Set a gentle default because strictly speaking, # setup won't fail (run-time does) enforce = "0" with open('/sys/fs/selinux/enforce', 'r') as f: enforce = f.read() if enforce.strip() == "1": log.fatal( _("SELinux currently enforcing. Read " + \ "https://git.kolab.org/u/1") ) sys.exit(1) if os.path.isfile('/etc/selinux/config'): if os.access('/etc/selinux/config', os.R_OK): with open('/etc/selinux/config', 'r') as f: for line in f: if line.strip() == "SELINUX=enforcing": log.fatal( _("SELinux configured to enforce a " + \ "policy on startup. Read " + \ "https://git.kolab.org/u/1") ) sys.exit(1) components.execute('_'.join(to_execute)) if os.path.exists('/tmp/kolab-setup-my.cnf'): os.unlink('/tmp/kolab-setup-my.cnf')
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--dry-run', dest = "dry_run", action = "store_true", default = False, help = _("Do not actually execute, but state what would have been executed."))
def execute(*args, **kw): auth = Auth() log.debug(_("Listing domains..."), level=5) start_time = time.time() domains = auth.list_domains() end_time = time.time() log.debug( _("Found %d domains in %d seconds") % ( len(domains), (end_time-start_time) ), level=8 ) all_folders = [] for primary_domain,secondary_domains in domains: log.debug(_("Running for domain %s") % (primary_domain), level=8) auth.connect(primary_domain) start_time = time.time() auth.synchronize() end_time = time.time() log.info(_("Synchronizing users for %s took %d seconds") % (primary_domain, (end_time-start_time)) )
def set_classification(self, classification): if classification in self.classification_map.keys(): self.setClassification(self.classification_map[classification]) elif classification in self.classification_map.values(): self.setClassification(status) else: raise ValueError, _("Invalid classification %r") % (classification)
def set_classification(self, classification): if classification in self.classification_map.keys(): self.event.setClassification(self.classification_map[classification]) elif classification in self.classification_map.values(): self.event.setClassification(status) else: raise ValueError, _("Invalid classification %r") % (classification)
def add_custom_property(self, name, value): if not name.upper().startswith('X-'): raise ValueError, _("Invalid custom property name %r") % (name) props = self.event.customProperties() props.append(kolabformat.CustomProperty(name.upper(), value)) self.event.setCustomProperties(props)
def set_ical_status(self, status): if status in self.status_map.keys(): self.event.setStatus(self.status_map[status]) elif status in self.status_map.values(): self.event.setStatus(status) else: raise ValueError, _("Invalid status %r") % (status)
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("List Options")) my_option_group.add_option('--since', dest="since", action="store", default=0, help=_("Display sessions since ..."))
def set_status(self, status): if status in self.status_map.keys(): self.event.setStatus(self.status_map[status]) elif status in self.status_map.values(): self.event.setStatus(status) else: raise InvalidEventStatusError, _("Invalid status set: %r") % (status)
def cb_action_ACCEPT(module, filepath): log.info(_("Accepting message in %s (by module %s)") % (filepath, module)) log.debug(_("Accepting message in: %r") % (filepath), level=8) # parse message headers message = Parser().parse(open(filepath, 'r'), True) sender = [ formataddr(x) for x in getaddresses(message.get_all('X-Kolab-From', [])) ] recipients = [ formataddr(x) for x in getaddresses(message.get_all('X-Kolab-To', [])) ] log.debug(_("recipients: %r") % (recipients)) # delete X-Kolab-* headers del message['X-Kolab-From'] del message['X-Kolab-To'] result = _sendmail( sender, recipients, # - Make sure we do not send this as binary. # - Second, strip NUL characters - I don't know where they # come from (TODO) # - Third, a character return is inserted somewhere. It # divides the body from the headers - and we don't like (TODO) # @TODO: check if we need Parser().parse() to load the whole message message.as_string()) if result: os.unlink(filepath)
def command_set(self, *args, **kw): """ Set a configuration option. Pass me a section, key and value please. Note that the section should already exist. TODO: Add a strict parameter TODO: Add key value checking """ if not self.cfg_parser: self.read_config() if not len(args) == 3: log.error(_("Insufficient options. Need section, key and value -in that order.")) if not self.cfg_parser.has_section(args[0]): log.error(_("No section '%s' exists.") % (args[0])) if '%' in args[2]: value = args[2].replace('%', '%%') else: value = args[2] self.cfg_parser.set(args[0], args[1], value) if hasattr(self, 'cli_keywords') and hasattr(self.cli_keywords, 'config_file'): fp = open(self.cli_keywords.config_file, "w+") self.cfg_parser.write(fp) fp.close() else: fp = open(self.config_file, "w+") self.cfg_parser.write(fp) fp.close()
def set_options_from_testing_section(self): """ Go through the options in the [testing] section if it exists. """ config = self.check_config() if not config.has_section('testing'): return for key in config.options('testing'): retval = False if isinstance(self.defaults.__dict__['testing'][key], int): value = config.getint('testing',key) elif isinstance(self.defaults.__dict__['testing'][key], bool): value = config.getboolean('testing',key) elif isinstance(self.defaults.__dict__['testing'][key], str): value = config.get('testing',key) elif isinstance(self.defaults.__dict__['testing'][key], list): value = eval(config.get('testing',key)) elif isinstance(self.defaults.__dict__['testing'][key], dict): value = eval(config.get('testing',key)) if hasattr(self,"check_setting_%s_%s" % ('testing',key)): exec("retval = self.check_setting_%s_%s(%r)" % ('testing',key,value)) if not retval: # We just don't set it, check_setting_%s should have # taken care of the error messages continue setattr(self,"%s_%s" % ('testing',key),value) if key.count('password') >= 1: log.debug(_("Setting %s_%s to '****' (from configuration file)") % ('testing',key), level=8) else: log.debug(_("Setting %s_%s to %r (from configuration file)") % ('testing',key,value), level=8)
def set_role(self, role): if role in self.role_map.keys(): self.setRole(self.role_map[role]) elif role in self.role_map.values(): self.setRole(role) else: raise InvalidAttendeeRoleError, _("Invalid role %r") % (role)
def set_participant_status(self, participant_status): if participant_status in self.participant_status_map.keys(): self.setPartStat(self.participant_status_map[participant_status]) elif participant_status in self.participant_status_map.values(): self.setPartStat(participant_status) else: raise InvalidAttendeeParticipantStatusError, _("Invalid participant status %r") % (participant_status)
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("List Options")) my_option_group.add_option( '--since', dest = "since", action = "store", default = 0, help = _("Display sessions since ..."))
def check_setting_test_suites(self, value): # Attempt to load the suite, # Get the suite's options, # Set them here. if not hasattr(self, 'test_suites'): self.test_suites = [] if "zpush" in value: selectively = False for item in ['calendar', 'contacts', 'mail']: if self.cli_keywords.__dict__[item]: log.debug(_( "Found you specified a specific set of items to test: %s" ) % (item), level=8) selectively = item if not selectively: self.calendar = True self.contacts = True self.mail = True else: log.debug(_("Selectively selecting: %s") % (selectively), level=8) setattr(self, selectively, True) self.test_suites.append('zpush')
def run(self): """Run Forest, RUN!""" exitcode = 0 utils.ensure_directory(os.path.dirname(conf.pidfile), conf.process_username, conf.process_groupname) try: try: (ruid, euid, suid) = os.getresuid() (rgid, egid, sgid) = os.getresgid() except AttributeError, errmsg: ruid = os.getuid() rgid = os.getgid() if ruid == 0: # Means we can setreuid() / setregid() / setgroups() if rgid == 0: # Get group entry details try: (group_name, group_password, group_gid, group_members) = grp.getgrnam(conf.process_groupname) except KeyError: print >> sys.stderr, _("Group %s does not exist") % ( conf.process_groupname) sys.exit(1) # Set real and effective group if not the same as current. if not group_gid == rgid: log.debug( _("Switching real and effective group id to %d") % (group_gid), level=8) os.setregid(group_gid, group_gid) if ruid == 0: # Means we haven't switched yet. try: (user_name, user_password, user_uid, user_gid, user_gecos, user_homedir, user_shell) = pwd.getpwnam(conf.process_username) except KeyError: print >> sys.stderr, _("User %s does not exist") % ( conf.process_username) sys.exit(1) # Set real and effective user if not the same as current. if not user_uid == ruid: log.debug( _("Switching real and effective user id to %d") % (user_uid), level=8) os.setreuid(user_uid, user_uid)
def execute(*args, **kw): global imap, pool auth = Auth() log.debug(_("Listing domains..."), level=5) start_time = time.time() domains = auth.list_domains() end_time = time.time() log.debug( _("Found %d domains in %d seconds") % ( len(domains), (end_time-start_time) ), level=8 ) if version.StrictVersion(sys.version[:3]) >= version.StrictVersion("2.7"): pool = multiprocessing.Pool(conf.threads, worker_process, (), 1) else: pool = multiprocessing.Pool(conf.threads, worker_process, ()) for primary_domain in list(set(domains.values())): log.debug(_("Running for domain %s") % (primary_domain), level=8) auth = Auth(primary_domain) auth.connect(primary_domain) start_time = time.time() auth.synchronize(mode='_paged_search', callback=queue_add) end_time = time.time() log.info(_("Synchronizing users for %s took %d seconds") % (primary_domain, (end_time-start_time)) ) while not pool._taskqueue.empty(): time.sleep(1)
def set_cutype(self, cutype): if cutype in self.cutype_map.keys(): self.setCutype(self.cutype_map[cutype]) elif cutype in self.cutype_map.values(): self.setCutype(cutype) else: raise InvalidAttendeeCutypeError, _("Invalid cutype %r") % (cutype)
def user_delete(self, *args, **kw): """ The arguments passed to the 'user_delete' hook: user - full user entry from LDAP domain - domain name """ log.debug(_("user_delete: %r") % (kw), level=9) if os.path.isdir('/usr/share/roundcubemail'): rcpath = '/usr/share/roundcubemail/' elif os.path.isdir('/usr/share/roundcube'): rcpath = '/usr/share/roundcube/' else: log.error(_("Roundcube installation path not found.")) return False result_attribute = conf.get('cyrus-sasl', 'result_attribute') # execute Roundcube's bin/deluser.sh script to do the work if kw.has_key('user') and kw['user'].has_key(result_attribute) and os.path.exists(rcpath + 'bin/deluser.sh'): proc = subprocess.Popen([ 'sudo -u apache', rcpath + 'bin/deluser.sh', kw['user'][result_attribute] ], stderr=subprocess.PIPE, stdout=subprocess.PIPE) procout, procerr = proc.communicate() if proc.returncode != 0: log.error(rcpath + "bin/deluser.sh exited with error %d: %r" % (proc.returncode, procerr)) else: log.debug(rcpath + "bin/deluser.sh success: %r; %r" % (procout, procerr), level=9) return None
def expire_sessions(retention=7): """ Expire sessions older then 'retention' days """ start_max = ((int)(time.time()) - (retention * 24 * 60 * 60)) #start_max = (int)(time.time()) log.info(_("Expiring sessions that started before or on %d") % (start_max)) db = init_db() sessions = db.query(TelemetrySession).filter( telemetry_session_table.c.start <= start_max).order_by( telemetry_session_table.c.start) for session in sessions: log.debug(_("Expiring session ID: %d") % (session.id), level=8) # Expire related information command_issue_ids = db.query(TelemetryCommandIssue).filter_by( session_id=session.id) for command_issue_id in command_issue_ids: # Expire server reponses server_responses = db.query(TelemetryServerResponse).filter_by( command_issue_id=command_issue_id.id).delete() db.delete(command_issue_id) db.commit() log.debug(_("Session with ID %d expired from database") % (session.id), level=8) db.delete(session) db.commit()
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--raw', dest = "raw", action = "store_true", default = False, help = _("Display raw IMAP UTF-7 folder names"))
def process_itip_cancel(itip_event, policy, recipient_email, sender_email, receiving_user): """ Process an iTip CANCEL message according to the given policy """ # if invitation policy is set to MANUAL, pass message along if policy & ACT_MANUAL: log.info(_("Pass cancellation for manual processing")) return MESSAGE_FORWARD # auto-update the local copy with STATUS=CANCELLED if policy & ACT_UPDATE: # find existing object in user's folders existing = find_existing_object(itip_event['uid'], itip_event['type'], receiving_user, True) if existing: existing.set_status('CANCELLED') existing.set_transparency(True) if update_object(existing, receiving_user): # send cancellation notification if policy & ACT_UPDATE_AND_NOTIFY: send_cancel_notification(existing, receiving_user) return MESSAGE_PROCESSED else: log.error(_("The object referred by this reply was not found in the user's folders. Forwarding to Inbox.")) return MESSAGE_FORWARD return None
def find_existing_object(uid, type, user_rec, lock=False): """ Search user's private folders for the given object (by UID+type) """ global imap lock_key = None if lock: lock_key = get_lock_key(user_rec, uid) set_write_lock(lock_key) event = None for folder in list_user_folders(user_rec, type): log.debug(_("Searching folder %r for %s %r") % (folder, type, uid), level=8) imap.imap.m.select(imap.folder_utf7(folder)) typ, data = imap.imap.m.search(None, '(UNDELETED HEADER SUBJECT "%s")' % (uid)) for num in reversed(data[0].split()): typ, data = imap.imap.m.fetch(num, '(RFC822)') try: if type == 'task': event = todo_from_message(message_from_string(data[0][1])) else: event = event_from_message(message_from_string(data[0][1])) setattr(event, '_imap_folder', folder) setattr(event, '_lock_key', lock_key) except Exception, e: log.error(_("Failed to parse %s from message %s/%s: %s") % (type, folder, num, traceback.format_exc())) continue if event and event.uid == uid: return event
def execute(*args, **kw): """ Delete a message from a mail folder """ try: folder = conf.cli_args.pop(0) try: uid = conf.cli_args.pop(0) except: log.error(_("Specify a UID")) sys.exit(1) except: log.error(_("Specify a folder")) sys.exit(1) imap = IMAP() imap.connect() _folder = imap.lm(folder) if _folder == None or _folder == []: log.error(_("No such folder")) sys.exit(1) imap.set_acl(folder, 'cyrus-admin', 'lrswt') imap.select(folder) imap.store(uid, '+FLAGS', '\\Deleted')
def check_config(self, val=None): """ Checks self.config_file or the filename passed using 'val' and returns a SafeConfigParser instance if everything is OK. """ if not val == None: config_file = val else: config_file = self.config_file if not os.access(config_file, os.R_OK): log.error(_("Configuration file %s not readable") % config_file) config = SafeConfigParser() log.debug(_("Reading configuration file %s") % config_file, level=8) try: config.read(config_file) except: log.error(_("Invalid configuration file %s") % config_file) if not config.has_section("kolab"): log.warning(_("No master configuration section [kolab] in configuration file %s") % config_file) return config
def execute(*args, **kw): """ Delete mailbox """ if len(conf.cli_args) < 1: print >> sys.stderr, _("No mailbox specified") sys.exit(1) imap = IMAP() imap.connect() delete_folders = [] while len(conf.cli_args) > 0: folder = conf.cli_args.pop(0) folders = imap.list_folders(folder) if len(folders) < 1: print >> sys.stderr, _("No such folder(s): %s") % (folder) delete_folders.extend(folders) if len(delete_folders) == 0: print >> sys.stderr, _("No folders to delete.") sys.exit(1) for delete_folder in delete_folders: try: imap.delete_mailfolder(delete_folder) except Exception, errmsg: log.error(_("Could not delete mailbox '%s'") % (delete_folder))
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--all', dest = "all", action = "store_true", default = False, help = _("All folders this user has access to"))
def test_014_owner_confirmation_decline(self): self.purge_mailbox(self.john['mailbox']) self.purge_mailbox(self.jane['mailbox']) uid = self.send_itip_invitation(self.room3['mail'], datetime.datetime(2014,9,14, 9,0,0)) # requester (john) gets a TENTATIVE confirmation response = self.check_message_received(self.itip_reply_subject % { 'summary':'test', 'status':participant_status_label('TENTATIVE') }, self.room3['mail']) self.assertIsInstance(response, email.message.Message) # check confirmation message sent to resource owner (jane) notify = self.check_message_received(_('Booking request for %s requires confirmation') % (self.room3['cn']), mailbox=self.jane['mailbox']) self.assertIsInstance(notify, email.message.Message) itip_event = events_from_message(notify)[0] # resource owner declines reservation request itip_reply = itip_event['xml'].to_message_itip(self.jane['mail'], method="REPLY", participant_status='DECLINED', message_text="Request declined", subject=_('Booking for %s has been %s') % (self.room3['cn'], participant_status_label('DECLINED')) ) smtp = smtplib.SMTP('localhost', 10026) smtp.sendmail(self.jane['mail'], str(itip_event['organizer']), str(itip_reply)) smtp.quit() # requester (john) now gets the DECLINED response response = self.check_message_received(self.itip_reply_subject % { 'summary':'test', 'status':participant_status_label('DECLINED') }, self.room3['mail']) self.assertIsInstance(response, email.message.Message) # tentative reservation was set to cancelled event = self.check_resource_calendar_event(self.room3['kolabtargetfolder'], uid) self.assertEqual(event, None)
def test_012_owner_notification(self): self.purge_mailbox(self.john['mailbox']) self.purge_mailbox(self.jane['mailbox']) self.send_itip_invitation(self.room1['mail'], datetime.datetime(2014,8,4, 13,0,0)) # check notification message sent to resource owner (jane) notify = self.check_message_received(_('Booking for %s has been %s') % (self.room1['cn'], participant_status_label('ACCEPTED')), self.room1['mail'], self.jane['mailbox']) self.assertIsInstance(notify, email.message.Message) notification_text = str(notify.get_payload()) self.assertIn(self.john['mail'], notification_text) self.assertIn(participant_status_label('ACCEPTED'), notification_text) self.purge_mailbox(self.john['mailbox']) # check notification sent to collection owner (jane) self.send_itip_invitation(self.rooms['mail'], datetime.datetime(2014,8,4, 12,30,0)) # one of the collection members accepted the reservation accepted = self.check_message_received(self.itip_reply_subject % { 'summary':'test', 'status':participant_status_label('ACCEPTED') }) delegatee = self.find_resource_by_email(accepted['from']) notify = self.check_message_received(_('Booking for %s has been %s') % (delegatee['cn'], participant_status_label('ACCEPTED')), delegatee['mail'], self.jane['mailbox']) self.assertIsInstance(notify, email.message.Message) self.assertIn(self.john['mail'], notification_text)
def translate(mystring, locale_name='en_US'): import locale import subprocess log.debug(_("Transliterating string %r with locale %r") % (mystring, locale_name), level=8) if len(locale.normalize(locale_name).split('.')) > 1: (locale_name,locale_charset) = locale.normalize(locale_name).split('.') else: locale_charset = 'utf-8' try: log.debug(_("Attempting to set locale"), level=8) locale.setlocale(locale.LC_ALL, (locale_name,locale_charset)) log.debug(_("Success setting locale"), level=8) except: log.debug(_("Failure to set locale"), level=8) pass command = [ '/usr/bin/iconv', '-f', 'UTF-8', '-t', 'ASCII//TRANSLIT', '-s' ] log.debug(_("Executing '%s | %s'") % (r"%s" % (mystring), ' '.join(command)), level=8) process = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env={'LANG': locale.normalize(locale_name)}) try: print >> process.stdin, r"%s" % mystring except UnicodeEncodeError, errmsg: pass
def propagate_changes_to_attendees_accounts(object): """ Find and update copies of this object in all attendee's personal folders """ for attendee in object.get_attendees(): attendee_user_dn = user_dn_from_email_address(attendee.get_email()) if attendee_user_dn: attendee_user = auth.get_entry_attributes(None, attendee_user_dn, ['*']) attendee_object = find_existing_object(object.uid, object.type, attendee_user, True) # does IMAP authenticate if attendee_object: try: attendee_entry = attendee_object.get_attendee_by_email(attendee_user['mail']) except: attendee_entry = None # copy all attendees from master object (covers additions and removals) new_attendees = kolabformat.vectorattendee(); for a in object.get_attendees(): # keep my own entry intact if attendee_entry is not None and attendee_entry.get_email() == a.get_email(): new_attendees.append(attendee_entry) else: new_attendees.append(a) attendee_object.event.setAttendees(new_attendees) success = update_object(attendee_object, attendee_user) log.debug(_("Updated %s's copy of %r: %r") % (attendee_user['mail'], object.uid, success), level=8) else: log.debug(_("Attendee %s's copy of %r not found") % (attendee_user['mail'], object.uid), level=8) else: log.debug(_("Attendee %r not found in LDAP") % (attendee.get_email()), level=8)
def cache_init(): global cache, cache_expire, session if conf.has_section('kolab_smtp_access_policy'): if conf.has_option('kolab_smtp_access_policy', 'cache_uri'): cache_uri = conf.get('kolab_smtp_access_policy', 'cache_uri') cache = True if conf.has_option('kolab_smtp_access_policy', 'retention'): cache_expire = (int)( conf.get( 'kolab_smtp_access_policy', 'retention' ) ) elif conf.has_option('kolab_smtp_access_policy', 'uri'): log.warning(_("The 'uri' setting in the kolab_smtp_access_policy section is soon going to be deprecated in favor of 'cache_uri'")) cache_uri = conf.get('kolab_smtp_access_policy', 'uri') cache = True else: return False else: return False if conf.debuglevel > 8: engine = create_engine(cache_uri, echo=True) else: engine = create_engine(cache_uri, echo=False) try: metadata.create_all(engine) except sqlalchemy.exc.OperationalError, e: log.error(_("Operational Error in caching: %s" % (e))) return False
def invitation_response_text(type): footer = "\n\n" + _("*** This is an automated message. Please do not reply. ***") if type == 'task': return _("%(name)s has %(status)s your assignment for %(summary)s.") + footer else: return _("%(name)s has %(status)s your invitation for %(summary)s.") + footer
def read_request_input(): """ Read a single policy request from sys.stdin, and return a dictionary containing the request. """ start_time = time.time() log.debug(_("Starting to loop for new request")) policy_request = {} end_of_request = False while not end_of_request: if (time.time()-start_time) >= conf.timeout: log.warning(_("Timeout for policy request reading exceeded")) sys.exit(0) request_line = sys.stdin.readline() if request_line.strip() == '': if policy_request.has_key('request'): log.debug(_("End of current request"), level=8) end_of_request = True else: request_line = request_line.strip() log.debug(_("Getting line: %s") % (request_line), level=8) policy_request[request_line.split('=')[0]] = \ '='.join(request_line.split('=')[1:]).lower() log.debug(_("Returning request")) return policy_request
def imap_proxy_auth(user_rec): """ Perform IMAP login using proxy authentication with admin credentials """ global imap mail_attribute = conf.get('cyrus-sasl', 'result_attribute') if mail_attribute == None: mail_attribute = 'mail' mail_attribute = mail_attribute.lower() if not user_rec.has_key(mail_attribute): log.error(_("User record doesn't have the mailbox attribute %r set" % (mail_attribute))) return False # do IMAP prox auth with the given user backend = conf.get('kolab', 'imap_backend') admin_login = conf.get(backend, 'admin_login') admin_password = conf.get(backend, 'admin_password') try: imap.disconnect() imap.connect(login=False) imap.login_plain(admin_login, admin_password, user_rec[mail_attribute]) except Exception, errmsg: log.error(_("IMAP proxy authentication failed: %r") % (errmsg)) return False
def _setquota(self, mailfolder, quota): # Removed server reconnection for dovecot, we only have one server log.debug(_("Setting quota for folder %s to %s") % (mailfolder,quota), level=8) try: self.m.setquota(mailfolder, quota) except: log.error(_("Could not set quota for mailfolder %s") % (mailfolder))
def store_object(object, user_rec, targetfolder=None): """ Append the given object to the user's default calendar/tasklist """ # find default calendar folder to save object to if targetfolder is None: targetfolder = list_user_folders(user_rec, object.type)[0] if user_rec.has_key('_default_folder'): targetfolder = user_rec['_default_folder'] # use *.confidential folder for invitations classified as confidential if object.get_classification() == kolabformat.ClassConfidential and user_rec.has_key('_confidential_folder'): targetfolder = user_rec['_confidential_folder'] if not targetfolder: log.error(_("Failed to save %s: no target folder found for user %r") % (object.type, user_rec['mail'])) return Fasle log.debug(_("Save %s %r to user folder %r") % (object.type, object.uid, targetfolder), level=8) try: imap.imap.m.select(imap.folder_utf7(targetfolder)) result = imap.imap.m.append( imap.folder_utf7(targetfolder), None, None, object.to_message(creator="Kolab Server <wallace@localhost>").as_string() ) return result except Exception, e: log.error(_("Failed to save %s to user folder at %r: %r") % ( object.type, targetfolder, e ))
def owner_notification_text(resource, owner, event, success): organizer = event.get_organizer() status = event.get_attendee_by_email(resource['mail']).get_participant_status(True) if success: message_text = _(""" The resource booking for %(resource)s by %(orgname)s <%(orgemail)s> has been %(status)s for %(date)s. *** This is an automated message, sent to you as the resource owner. *** """) else: message_text = _(""" A reservation request for %(resource)s could not be processed automatically. Please contact %(orgname)s <%(orgemail)s> who requested this resource for %(date)s. Subject: %(summary)s. *** This is an automated message, sent to you as the resource owner. *** """) return message_text % { 'resource': resource['cn'], 'summary': event.get_summary(), 'date': event.get_date_text(), 'status': participant_status_label(status), 'orgname': organizer.name(), 'orgemail': organizer.email() }
def ask_menu(question, options={}, default=''): if not default == '' and conf.cli_keywords.answer_default: if not conf.cli_keywords.quiet: print question + " [" + default + "]:" return default if not default == '': print question + " [" + default + "]:" else: print question answer_correct = False max_key_length = 0 if isinstance(options, list): _options = options options = {} for key in _options: options[key] = key keys = options.keys() keys.sort() while not answer_correct: for key in keys: key_length = len("%s" % key) if key_length > max_key_length: max_key_length = key_length str_format = "%%%ds" % max_key_length if default == '' or not default in options.keys(): for key in keys: if options[key] == key: print " - " + key else: print " - " + eval("str_format % key") + ": " + options[key] answer = raw_input(_("Choice") + ": ") else: answer = raw_input(_("Choice (type '?' for options)") + ": ") if answer == '?': for key in keys: if options[key] == key: print " - " + key else: print " - " + eval("str_format % key") + ": " + options[key] continue if answer == '' and default in options.keys(): answer = default if answer in [str(x) for x in options.keys()]: answer_correct = True return answer
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--server', dest = "connect_server", action = "store", default = None, metavar = "SERVER", help = _("List mailboxes on server SERVER only."))
def _rename(self, from_mailfolder, to_mailfolder, partition=None): # Removed server reconnection for dovecot, we only have one server if not partition == None: log.debug(_("Moving INBOX folder %s to %s on partition %s") % (from_mailfolder,to_mailfolder, partition), level=8) else: log.debug(_("Moving INBOX folder %s to %s") % (from_mailfolder,to_mailfolder), level=8) self.m.rename(self.folder_utf7(from_mailfolder), self.folder_utf7(to_mailfolder), '"%s"' % (partition))
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option('--user', dest="user", action="store", default=None, metavar="USER", help=_("Set annotation as user USER"))
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--force', dest="force", action="store_true", default=False, help=_("Force deleting the domain even if it contains user accounts"))
def cli_options(): ldap_group = conf.add_cli_parser_option_group(_("MySQL Options")) ldap_group.add_option( "--mysqlserver", dest = "mysqlserver", action = "store", help = _("Specify whether to use an (existing) or (new) MySQL server.") )
def ensure_directory(_dir, _user='******', _group='root'): if not os.path.isdir(_dir): os.makedirs(_dir) try: try: (ruid, euid, suid) = os.getresuid() (rgid, egid, sgid) = os.getresgid() except AttributeError, errmsg: ruid = os.getuid() rgid = os.getgid() if ruid == 0: # Means we can setreuid() / setregid() / setgroups() if rgid == 0: # Get group entry details try: ( group_name, group_password, group_gid, group_members ) = grp.getgrnam(_group) except KeyError: print >> sys.stderr, _("Group %s does not exist") % ( _group ) sys.exit(1) # Set real and effective group if not the same as current. if not group_gid == rgid: os.chown(_dir, -1, group_gid) if ruid == 0: # Means we haven't switched yet. try: ( user_name, user_password, user_uid, user_gid, user_gecos, user_homedir, user_shell ) = pwd.getpwnam(_user) except KeyError: print >> sys.stderr, _("User %s does not exist") % (_user) sys.exit(1) # Set real and effective user if not the same as current. if not user_uid == ruid: os.chown(_dir, user_uid, -1)
def execute(*args, **kw): if not os.path.isfile('/etc/manticore/local.env.js'): log.error(_("Manticore is not installed on this system")) return manticore_settings = { 'fqdn': hostname + '.' + domainname, 'secret': re.sub( r'[^a-zA-Z0-9]', "", "%s%s" % (hashlib.md5("%s" % random.random()).digest().encode("base64"), hashlib.md5( "%s" % random.random()).digest().encode("base64")))[:24], 'server_host': utils.parse_ldap_uri(conf.get('ldap', 'ldap_uri'))[1], 'auth_key': re.sub( r'[^a-zA-Z0-9]', "", "%s%s" % (hashlib.md5("%s" % random.random()).digest().encode("base64"), hashlib.md5( "%s" % random.random()).digest().encode("base64")))[:24], 'service_bind_dn': conf.get('ldap', 'service_bind_dn'), 'service_bind_pw': conf.get('ldap', 'service_bind_pw'), 'user_base_dn': conf.get('ldap', 'user_base_dn') } if os.path.isfile('/etc/kolab/templates/manticore.js.tpl'): fp = open('/etc/kolab/templates/manticore.js.tpl', 'r') else: fp = open('/usr/share/kolab/templates/manticore.js.tpl', 'r') template_definition = fp.read() fp.close() t = Template(template_definition, searchList=[manticore_settings]) fp = open('/etc/manticore/local.env.js', 'w') fp.write(t.__str__()) fp.close() if os.path.isfile('/bin/systemctl'): subprocess.call(['/bin/systemctl', 'restart', 'mongod']) time.sleep(5) subprocess.call(['/bin/systemctl', 'restart', 'manticore']) else: log.error(_("Could not start the manticore service.")) if os.path.isfile('/bin/systemctl'): subprocess.call(['/bin/systemctl', 'enable', 'mongod']) subprocess.call(['/bin/systemctl', 'enable', 'manticore']) else: log.error( _("Could not configure the manticore service to start on boot"))
def execute(component_name, *args, **kw): if component_name == '': log.debug(_("No component selected, continuing for all components"), level=8) while 1: for component in _list_components(): execute_this = True if component in executed_components: execute_this = False if component == "help": execute_this = False if execute_this: if components[component].has_key('after'): for _component in components[component]['after']: if not _component in executed_components: execute_this = False if execute_this: execute(component) executed_components.append(component) executed_all = True for component in _list_components(): if not component in executed_components and not component == "help": executed_all = False if executed_all: break return else: for component in _list_components(): cli_options_from_component(component) if not components.has_key(component_name): log.error(_("No such component.")) sys.exit(1) if not components[component_name].has_key('function') and \ not components[component_name].has_key('group'): log.error(_("No such component.")) sys.exit(1) conf.finalize_conf() if len(conf.cli_args) >= 1: _component_name = conf.cli_args.pop(0) else: _component_name = component_name components[component_name]['function'](conf.cli_args, kw)
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--dry-run', dest="dryrun", action="store_true", default=False, help= _("Do not actually delete mailboxes, but report what mailboxes would have been deleted." ))
def __getattr__(self, name): if hasattr(self.imap, name): return getattr(self.imap, name) elif hasattr(self.imap, 'm'): if hasattr(self.imap.m, name): return getattr(self.imap.m, name) else: raise AttributeError, _("%r has no attribute %s") % (self,name) else: raise AttributeError, _("%r has no attribute %s") % (self,name)
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--alias', dest="domains", action="append", default=[], help=_("Add alias domain."), metavar="DOMAIN", )
def cli_options(): my_option_group = conf.add_cli_parser_option_group(_("CLI Options")) my_option_group.add_option( '--dry-run', dest="dry_run", action="store_true", default=False, help=_( "Do not actually execute, but state what would have been executed." ))
def execute(*args, **kw): try: folder = conf.cli_args.pop(0) try: identifier = conf.cli_args.pop(0) except IndexError, errmsg: identifier = utils.ask_question(_("ACI Subject")) except IndexError, errmsg: folder = utils.ask_question(_("Folder name")) quota = utils.ask_question(_("ACI Subject"))
def execute(*args, **kw): try: folder = conf.cli_args.pop(0) try: quota = conf.cli_args.pop(0) except IndexError, errmsg: quota = utils.ask_question(_("New quota")) except IndexError, errmsg: folder = utils.ask_question(_("Folder name")) quota = utils.ask_question(_("New quota"))
def check_setting_config_file(self, value): if os.path.isfile(value): if os.access(value, os.R_OK): self.read_config(value=value) self.config_file = value return True else: log.error(_("Configuration file %s not readable.") % (value)) return False else: log.error(_("Configuration file %s does not exist.") % (value)) return False
def execute(*args, **kw): db = telemetry.init_db() sessions = db.query(telemetry.TelemetrySession).order_by( telemetry.telemetry_session_table.c.start) for session in sessions: user = db.query( telemetry.TelemetryUser).filter_by(id=session.user_id).first() print _("Session for user %s started at %s with ID %s") % ( user.sasl_username, session.start, session.id)
def execute(*args, **kw): if conf.has_section('example.org'): primary_domain = conf.get('kolab', 'primary_domain') if not primary_domain == 'example.org': utils.multiline_message( _(""" Copying the configuration section for 'example.org' over to a section applicable to your domain '%s'. """) % (primary_domain)) conf.cfg_parser._sections[primary_domain] = \ conf.cfg_parser._sections['example.org'] conf.cfg_parser._sections.pop('example.org') fp = open(conf.cli_keywords.config_file, "w+") conf.cfg_parser.write(fp) fp.close() if os.path.isfile('/etc/default/kolab-server'): myaugeas = Augeas() setting = os.path.join('/files/etc/default/kolab-server', 'START') if not myaugeas.get(setting) == 'yes': myaugeas.set(setting, 'yes') myaugeas.save() myaugeas.close() if os.path.isfile('/bin/systemctl'): if os.path.isfile('/etc/debian_version'): subprocess.call( ['/bin/systemctl', 'restart', 'kolab-server.service']) else: subprocess.call(['/bin/systemctl', 'restart', 'kolabd.service']) elif os.path.isfile('/sbin/service'): subprocess.call(['/sbin/service', 'kolabd', 'restart']) elif os.path.isfile('/usr/sbin/service'): subprocess.call(['/usr/sbin/service', 'kolab-server', 'restart']) else: log.error(_("Could not start the kolab server service.")) if os.path.isfile('/bin/systemctl'): if os.path.isfile('/etc/debian_version'): subprocess.call( ['/bin/systemctl', 'enable', 'kolab-server.service']) else: subprocess.call(['/bin/systemctl', 'enable', 'kolabd.service']) elif os.path.isfile('/sbin/chkconfig'): subprocess.call(['/sbin/chkconfig', 'kolabd', 'on']) elif os.path.isfile('/usr/sbin/update-rc.d'): subprocess.call(['/usr/sbin/update-rc.d', 'kolab-server', 'defaults']) else: log.error(_("Could not configure to start on boot, the " + \ "kolab server service."))