changed encodings in mail service

py3_forced
parent 20d9fdefb8
commit b5fdbd082f

@ -37,7 +37,7 @@ import cl_utils
from cl_xml import firstChild
import importlib
##############################################################################
_ = lambda x : x
_expand_lang = gettext._expand_lang
def exit(codeExit):
@ -1096,7 +1096,7 @@ class DataVars():
def getVars(self, type_names=None):
ret = {}
for section, moduleVar, fillobj in self._importList:
dataVar=moduleVar.Data
dataVar = moduleVar.Data
dictVars = dir(dataVar)
for nameVar in dictVars:
if not "__" in nameVar:
@ -1117,14 +1117,14 @@ class DataVars():
#распечатать список переменных с значениями
def printVars(self,type_names=None):
var=None
var=self.getVars(type_names)
mlen_name=0
mlen_type=0
mlen_mode=0
var = None
var = self.getVars(type_names)
mlen_name = 0
mlen_type = 0
mlen_mode = 0
for i,j in var.items():
if len(i)>mlen_name:
mlen_name=len(i)
if len(i) > mlen_name:
mlen_name = len(i)
#if len(str(j.type))>mlen_type:
#mlen_type=len(str(j.type))
vtype=str(type(var[i].value)).split(" ")[1][1]
@ -1133,10 +1133,10 @@ class DataVars():
mode="[%s%s]"%(var[i].mode.lower(),vtype)
else:
mode="[%s]"%(var[i].mode.lower())
var[i].mode=mode
if len(mode)>mlen_mode:
mlen_mode=len(mode)
plist=var.keys()
var[i].mode = mode
if len(mode) > mlen_mode:
mlen_mode = len(mode)
plist = list(var.keys())
plist.sort()
br = cl_utils.fillstr("-",mlen_name) + " " +\
cl_utils.fillstr("-",mlen_mode) + " " + cl_utils.fillstr("-",10)
@ -1152,7 +1152,7 @@ class DataVars():
for i in plist:
#if var[i].value is None:
#continue
p_val=var[i].value
p_val = var[i].value
if var[i].official:
continue
cl_utils.columnWrite( i, mlen_name, var[i].mode.lower(),

@ -13,7 +13,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
_ = lambda x : x
import re
import os
import types

@ -52,7 +52,7 @@ import ctypes
from functools import reduce
Version = "calculate-server 2.1.20"
_ = lambda x : x
tr = cl_base.lang()
tr.setLanguage(sys.modules[__name__])
@ -1089,8 +1089,8 @@ in a sambaDomainName',
lenCryptStr = len(cryptStr)
pwd = re.sub("(\W)", r"\\\1", password)
pwdHash = self.execProg("slappasswd -s %s -h %s" %(pwd,cryptStr))
if pwdHash and len(pwdHash)>lenCryptStr and\
pwdHash[:lenCryptStr] == cryptStr.encode("UTF-8"):
if pwdHash and len(pwdHash) > lenCryptStr and\
pwdHash[:lenCryptStr] == cryptStr:
return pwdHash
self.printERROR(_("ERROR") + " getHashPasswd: " +\
_("create crypto password"))
@ -1421,7 +1421,7 @@ in a sambaDomainName',
if i == 3 and not self.isCorrectStringNet(strNet):
printW()
self.printERROR(_("You used four attempts, \
if you want to continue to run the program again"))
if you want to continue to run the program again"))
return False
return self.isCorrectStringNet(strNet)
@ -2232,7 +2232,7 @@ class servUnix(shareLdap):
groupErrors.append(groupName)
flagError = True
continue
userGroupNames[res[0][0][1]['cn'][0]]=\
userGroupNames[res[0][0][1]['cn'][0].decode("UTF-8")]=\
res[0][0][1]['gidNumber'][0].decode("UTF-8")
continue
gidNumber = gid
@ -2241,7 +2241,7 @@ class servUnix(shareLdap):
gidErrors.append(gidNumber)
flagError = True
continue
userGroupNames[res[0][0][1]['cn'][0]] =\
userGroupNames[res[0][0][1]['cn'][0].decode("UTF-8")] =\
res[0][0][1]['gidNumber'][0].decode("UTF-8")
if flagError:
errorMessage = ""
@ -2317,9 +2317,9 @@ class servUnix(shareLdap):
findUsers = []
if 'memberUid' in res[0][0][1]:
usersInGroup = res[0][0][1]['memberUid']
#TODO maybe we'll need to decode each username
for userName in usersNames:
if userName in usersInGroup:
userName_encoded = userName.encode("UTF-8")
if userName_encoded in usersInGroup:
findUsers.append(userName)
return findUsers
@ -2542,13 +2542,13 @@ class servUnix(shareLdap):
userGid = options['g']
retCondUnix, userGidNamesUnix, errMessUnix =\
self.searchGroupsUnix([userGid], False)
userGidNamesUnix = userGidNamesUnix.keys()
userGidNamesUnix = list(userGidNamesUnix.keys())
userGidNamesSamba = False
# В случае вызова из Samba объекта
if callSamba:
retCondSamba, userGidNamesSamba, errMessSamba =\
self.servSambaObj.searchGroupsSamba([userGid], False)
userGidNamesSamba = userGidNamesSamba.keys()
userGidNamesSamba = list(userGidNamesSamba.keys())
userGidNamesPasswd = self.searchGroupsGroups([userGid], False)
if userGidNamesUnix:
#Имя группы пользователя
@ -2802,6 +2802,7 @@ service"))
addUsers.append(user)
modAttrs = []
for userName in addUsers:
#TODO check userName encoding
modAttrs.append((ldap.MOD_ADD, 'memberUid', userName))
if modAttrs:
groupDN = self.addDN("cn="+groupName, self.relGroupsDN)
@ -2830,7 +2831,7 @@ service"))
if maxGid == 0:
return self.minGid
else:
return maxGid+1
return maxGid + 1
def getMaxGidGroupSystem(self):
"""Получаем максимальный добавленный gid из /etc/group
@ -3121,12 +3122,12 @@ service"))
if callSamba:
retCondUnix, userGroupNames, errMessUnix =\
self.searchGroupsUnix([newFirstGroup],False)
userGroupNames = userGroupNames.keys()
userGroupNames = list(userGroupNames.keys())
if not userGroupNames:
retCondSamba ,userGroupNames, errMessSamba =\
self.servSambaObj.searchGroupsSamba([newFirstGroup],
False)
userGroupNames = userGroupNames.keys()
userGroupNames = list(userGroupNames.keys())
if not userGroupNames:
self.printERROR(\
_("Group %s is not found in Unix and Samba services")%\
@ -3135,7 +3136,7 @@ service"))
else:
retCondUnix, userGroupNames, errMessUnix =\
self.searchGroupsUnix([newFirstGroup])
userGroupNames = userGroupNames.keys()
userGroupNames = list(userGroupNames.keys())
if not retCondUnix:
return False
groupName = userGroupNames[0]
@ -3273,10 +3274,10 @@ service"))
str(userName))
# Включаем пользователя
if 'u' in options:
modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', "-1")]
modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', b"-1")]
# Выключаем пользователя
elif 'l' in options:
modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', "1")]
modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', b"1")]
if not options:
optPasswd = {"p":""}
if pwd:
@ -3290,10 +3291,10 @@ service"))
return False
if 'userPassword' in res[0][0][1]:
modAttrs.append((ldap.MOD_REPLACE, 'userPassword',
userPwdHash))
userPwdHash.encode("UTF-8")))
else:
modAttrs.append((ldap.MOD_ADD, 'userPassword',
userPwdHash))
userPwdHash.encode("UTF-8")))
if modAttrs:
DN = self.addDN("uid="+userName, self.relUsersDN)
@ -3419,7 +3420,7 @@ service"))
"""Удаление пользователей из списка из группы Unix"""
def getPrimaryUsers():
gidNumber = res[0][0][1]["gidNumber"][0]
gidNumber = res[0][0][1]["gidNumber"][0].decode("UTF-8")
searchUsers = self.searchUnixUserPrimGroup(gidNumber)
foundUserNames = []
if searchUsers:
@ -3445,9 +3446,9 @@ service"))
return False
memberUsers = res[0][0][1]["memberUid"]
flagError =False
#TODO decode each member?
for user in users:
if not user in memberUsers:
user_encoded = user.encode("UTF-8")
if not user_encoded in memberUsers:
flagError = True
break
if flagError:
@ -3658,7 +3659,7 @@ class servMail(shareLdap):
return False
return userGroupNames
def delUserMailServer(self,userName,options,printSuccess=True,backup=True):
def delUserMailServer(self, userName, options, printSuccess=True, backup=True):
"""Удаляем Mail пользователя"""
# Проверим установлен ли сервис Mail
if not self.initialChecks("mail"):
@ -3688,8 +3689,8 @@ class servMail(shareLdap):
servReplObj = servRepl()
if not servReplObj.delReplMailAlias(userName):
self.printERROR (_("ERROR") + ": " +\
_("Cannot delete email alias \
for user %s in 'Replication/Mail' branch") %str(userName))
_("Cannot delete email alias \
for user %s in 'Replication/Mail' branch") %str(userName))
return False
# Удаляем пользователя из групп
if not self.delUserInGroup(userName):
@ -3744,10 +3745,10 @@ for user %s in 'Replication/Mail' branch") %str(userName))
return False
userMail = resSearch[0]
userInGroups = resSearch[1]
modAttrs = [(ldap.MOD_DELETE, 'rfc822member', userMail)]
modAttrs = [(ldap.MOD_DELETE, 'rfc822member', userMail.encode("UTF-8"))]
flagError = False
for group in userInGroups:
groupName = group[0][1]['cn'][0]
groupName = group[0][1]['cn'][0].decode("UTF-8")
groupDN = self.addDN("cn=" + groupName, self.relGroupsDN)
if not self.modAttrsDN(groupDN, modAttrs):
flagError = True
@ -3767,11 +3768,11 @@ for user %s in 'Replication/Mail' branch") %str(userName))
self.printERROR(\
_("Member list of group %s is empty")%str(groupName))
return False
memberMailUsers = res[0][0][1]["rfc822member"].decode("UTF-8")
memberMailUsers = res[0][0][1]["rfc822member"]
flagError = False
memberUsers = {}
for mailUser in memberMailUsers:
userName = mailUser.split("@")[0]
userName = mailUser.decode("UTF-8").split("@")[0]
memberUsers[userName] = mailUser
for user in users:
if not user in memberUsers.keys():
@ -3779,14 +3780,14 @@ for user %s in 'Replication/Mail' branch") %str(userName))
break
if flagError:
self.printERROR(\
_("User %s is not found in group")%str(user)+" "+\
_("User %s is not found in group") % str(user) + " " +\
str(groupName))
return False
modAttrs = []
for user in users:
mailUser = memberUsers[user]
modAttrs.append((ldap.MOD_DELETE, 'rfc822member', mailUser))
groupDN = self.addDN("cn="+groupName, self.relGroupsDN)
groupDN = self.addDN("cn=" + groupName, self.relGroupsDN)
return self.modAttrsDN(groupDN, modAttrs)
def delGroupMailServer(self, groupName, options):
@ -3799,7 +3800,7 @@ for user %s in 'Replication/Mail' branch") %str(userName))
self.printERROR(
_("Group %s is not found in Mail service")%groupName)
return False
delDN = self.addDN("cn="+groupName, self.relGroupsDN)
delDN = self.addDN("cn=" + groupName, self.relGroupsDN)
res = self.delDN(delDN)
if res:
# В случае почтовой репликации удаляем алиас в ветке
@ -3811,7 +3812,8 @@ for user %s in 'Replication/Mail' branch") %str(userName))
if not servReplObj.delReplMailAlias(groupName):
self.printERROR (_("ERROR") + ": " +\
_("Cannot delete email alias \
for group %s in 'Replication/Mail' branch") % str(groupName))
for group %s in 'Replication/Mail' branch") \
% str(groupName))
return False
self.printSUCCESS( _("Mail group %s is deleted")%groupName)
return True
@ -3844,11 +3846,11 @@ for group %s in 'Replication/Mail' branch") % str(groupName))
return False
if 'n' in options and 'e' in options:
self.printERROR(_("Command Line Options '-n' and '-e' are \
incompatible, use one of the options"))
incompatible, use one of the options"))
return False
if 'hide' in options and 'hide-off' in options:
self.printERROR(_("Command Line Options '--hide' and '--hide-off' \
are incompatible, use one of the options"))
are incompatible, use one of the options"))
return False
attrDelete = []
attrDeleteFirst = []
@ -3868,16 +3870,16 @@ are incompatible, use one of the options"))
# Если необходимо добавляем домен к именам хостов
fHosts = [(not '.' in x and x + "." + domain) or x for x in filterHosts]
for host in fHosts:
attrAppend.append((ldap.MOD_ADD, 'filtersender', host))
attrAppend.append((ldap.MOD_ADD, 'filtersender', host.encode("UTF-8")))
if 'hide-off' in options:
if 'filtersender' in searchGroup[0][0][1]:
attrDeleteFirst.append((ldap.MOD_DELETE, 'filtersender', None))
if 'e' in options:
altMails = options['e'].split(",")
email = searchGroup[0][0][1]["mail"][0].decode("UTF-8")
# в этот раз не трогаем кодировку
email = searchGroup[0][0][1]["mail"][0]
altEmails = searchGroup[0][0][1]["mailAlternateAddress"]
# Удаляем альтернативные адреса, кроме первого
#TODO decode each email
for altEmail in altEmails:
if email != altEmail:
attrDeleteFirst.append(
@ -3888,7 +3890,7 @@ are incompatible, use one of the options"))
if "@" in altMail:
if len(altMail.split("@")) != 2:
self.printERROR(_("Incorrect alternate adresses \
option '-e'"))
option '-e'"))
return False
mail = altMail
else:
@ -3898,22 +3900,23 @@ option '-e'"))
(not (mail in altEmails) and len(searchGroupMail) == 1 or\
len(searchGroupMail) != 1)):
self.printERROR(
_("Alternate email address %s is found in Mail service")%\
str(mail))
_("Alternate email address %s is found in Mail service")%\
str(mail))
return False
if i == 0:
attrAppend.append((ldap.MOD_REPLACE, 'mailAlternateAddress',
mail))
mail.encode("UTF-8")))
else:
attrAppend.append((ldap.MOD_ADD, 'mailAlternateAddress',
mail))
mail.encode("UTF-8")))
i += 1
if servReplObj:
if not altMails and filterHosts:
altMails = searchGroup[0][0][1]["mailAlternateAddress"]
#TODO decode each
altMails = [x.decode("UTF-8") for x in searchGroup[0][0][1]["mailAlternateAddress"]]
if altMails:
for mail in altMails:
#NOTE: there used to be a typo:
# for mail in altMails:
for altMail in altMails:
if "@" in altMail:
mail = altMail
else:
@ -3923,28 +3926,29 @@ option '-e'"))
if foundReplAlias:
flagError = False
foundReplUsers = foundReplAlias[0][0][1]['cn']
#TODO decode each
for foundReplUser in foundReplUsers:
if foundReplUser!=groupName:
foundReplUser_decoded = foundReplUser.decode("UTF-8")
if foundReplUser_decoded != groupName:
flagError = True
break
if flagError:
self.printERROR(_("Mail address %s is found in \
'Replication/Mail' branch")%mail)
'Replication/Mail' branch") % mail)
self.printERROR(_("The address belongs to \
mail user or group: %s")%foundReplUser)
mail user or group: %s") % foundReplUser_decoded)
return False
if not servReplObj.modReplMailAlias(groupName, altMails,
if not servReplObj.modReplMailAlias(groupName,
altMails,
filterHosts):
errorMsg = _("Can not set replication mail alias,") +\
" " + _("for name %s")%groupName + " " +\
"(%s)"%", ".join(altMails)
" " + _("for name %s") % groupName + " " +\
"(%s)" % ", ".join(altMails)
self.printERROR(errorMsg)
return False
if 'hide-off' in options:
if not servReplObj.deleteHideHosts(groupName):
errorMsg = _("Can not delete hide host in mail alias,") +\
" " + _("for name %s")%groupName
" " + _("for name %s") % groupName
self.printERROR(errorMsg)
return False
# Добавляем список пользователей в группу
@ -3984,13 +3988,13 @@ mail user or group: %s")%foundReplUser)
altEmails = searchGroup[0][0][1]["mailAlternateAddress"]
#todo decode each
for altEmail in altEmails:
splAltEmail = altEmail.split("@")
grName = splAltEmail[0]
splAltEmail = altEmail.split(b"@")
grName = splAltEmail[0].decode("UTF-8")
if groupName == grName:
altEmailDomen = ""
altEmailDomen = b""
if len(splAltEmail)==2:
altEmailDomen = splAltEmail[1]
newAltEmail = "%s@%s" %(newGroupName,altEmailDomen)
newAltEmail = b"%s@%s" %(newGroupName.encode("UTF-8"), altEmailDomen)
attrDelete.append(
(ldap.MOD_DELETE, 'mailAlternateAddress',
altEmail))
@ -3998,15 +4002,17 @@ mail user or group: %s")%foundReplUser)
(ldap.MOD_ADD, 'mailAlternateAddress',
newAltEmail))
break
email = searchGroup[0][0][1]["mail"][0].decode("UTF-8")
splEmail = email.split("@")
emailDomen = ""
#no decoding on purpose
email = searchGroup[0][0][1]["mail"][0]
splEmail = email.split(b"@")
emailDomen = b""
if len(splEmail)==2:
emailDomen = splEmail[1]
newEmail = "%s@%s" %(newGroupName,emailDomen)
newGroupName_encoded = newGroupName.encode("UTF-8")
newEmail = b"%s@%s" %(newGroupName_encoded, emailDomen)
attrAppend.append((ldap.MOD_REPLACE, 'mail', newEmail))
attrAppend.append((ldap.MOD_REPLACE, 'mailMessageStore',
newGroupName + "/"))
newGroupName_encoded + b"/"))
newFirstDn = "cn=" + newGroupName
oldDN = self.addDN("cn=" + groupName, self.relGroupsDN)
@ -4015,7 +4021,7 @@ mail user or group: %s")%foundReplUser)
if servReplObj:
if not servReplObj.renameReplMailAlias(groupName, newGroupName):
self.printERROR(_("Failed modify name '%s' mail alias \
in 'Replication/Mail' branch") %groupName)
in 'Replication/Mail' branch") %groupName)
return False
if res:
self.printSUCCESS(_("Group renamed to %s")\
@ -4028,7 +4034,7 @@ in 'Replication/Mail' branch") %groupName)
# Изменяем комментарий к группе
if 'c' in options:
gecos = options['c']
modAttrs.append((ldap.MOD_REPLACE, 'description', gecos))
modAttrs.append((ldap.MOD_REPLACE, 'description', gecos.encode("UTF-8")))
if not modAttrs:
if 'hide-off' in options:
self.printWARNING(\
@ -4108,14 +4114,14 @@ in 'Replication/Mail' branch") %groupName)
modAttrs = []
# Включаем пользователя
if 'U' in options:
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "active")]
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', b"active")]
# Выключаем пользователя
elif 'L' in options:
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "passive")]
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', b"passive")]
# Изменяем комментарий к пользователю
if 'c' in options:
comment = options['c']
comment = options['c'].encode("UTF-8")
modAttrs += [(ldap.MOD_REPLACE, 'sn', comment),
(ldap.MOD_REPLACE, 'cn', comment)]
# Изменяем пароль пользователя
@ -4128,10 +4134,10 @@ in 'Replication/Mail' branch") %groupName)
return False
if 'userPassword' in res[0][0][1]:
modAttrs.append((ldap.MOD_REPLACE, 'userPassword',
userPwdHash))
userPwdHash.encode("UTF-8")))
else:
modAttrs.append((ldap.MOD_ADD, 'userPassword',
userPwdHash))
userPwdHash.encode("UTF-8")))
# Заменяем альтернативные почтовые адреса
# Первичный почтовый адрес
primaryMail = ""
@ -4144,70 +4150,72 @@ in 'Replication/Mail' branch") %groupName)
if "@" in altMail:
if len(altMail.split("@")) != 2:
self.printERROR(_("Incorrect alternate adresses \
option '-e'"))
option '-e'"))
return False
mail = altMail
else:
mail = "%s@%s" %(altMail,self.clVars.Get("sr_mail_host"))
mail = "%s@%s" %(altMail, self.clVars.Get("sr_mail_host"))
if not primaryMail:
primaryMail = mail
searchUserMail = self.searchUserToMail(mail)
if self.searchGroupToMail(mail) or (searchUserMail and\
(not (mail in altEmails) and len(searchUserMail) == 1 or\
(not (mail.encode("UTF-8") in altEmails) and len(searchUserMail) == 1 or\
len(searchUserMail) != 1)):
self.printERROR(
_("Alternate email address %s is found in Mail service")%\
str(mail))
return False
modAttrs.append((ldap.MOD_ADD, 'mailAlternateAddress', mail))
modAttrs.append((ldap.MOD_ADD, 'mailAlternateAddress', mail.encode("UTF-8")))
# Удаляем предыдущие адреса
self.delAlternateAddress(userName)
# Изменяем основной почтовый адрес
if primaryMail:
if not self.servUnixObj.setUserMail(userName, primaryMail):
self.printERROR(_("Failed set primary email for user %s \
in Unix service") %str(primaryMail))
in Unix service") % str(primaryMail))
return False
# Если включена репликация почты
if self.clVars.Get("ld_repl_mail_set") == "on":
# Объект сервис репликации
servReplObj = servRepl()
if altMails:
for mail in altMails:
if "@" in altMail:
mail = altMail
#NOTE: there used to be a typo
# for mail in altMails:
for altMail in altMails:
if b"@" in altMail:
mail = altMail.decode("UTF-8")
else:
mail = "%s@%s" %(altMail,\
mail = "%s@%s" %(altMail.decode("UTF-8"),\
self.clVars.Get("sr_mail_host"))
foundReplAlias = servReplObj.searchMailAddress(mail)
if foundReplAlias:
flagError = False
foundReplUsers = foundReplAlias[0][0][1]['cn']
#TODO decode each
for foundReplUser in foundReplUsers:
if foundReplUser != userName:
foundReplUser_decoded = foundReplUser.decode("UTF-8")
if foundReplUser_decoded != userName:
flagError = True
break
if flagError:
self.printERROR(_("Mail address %s is found in \
'Replication/Mail' branch")%mail)
'Replication/Mail' branch") % mail)
self.printERROR(_("The address belongs to \
mail user or group: %s")%foundReplUser)
mail user or group: %s") % foundReplUser_decoded)
return False
if not servReplObj.modReplMailAlias(userName, altMails):
self.printERROR(_("Failed modify mail aliases \
for user %s in 'Replication/Mail' branch") %userName)
for user %s in 'Replication/Mail' branch") % userName)
return False
if modAttrs:
DN = self.addDN("uid="+userName, self.relUsersDN)
DN = self.addDN("uid=" + userName, self.relUsersDN)
if not self.modAttrsDN(DN, modAttrs):
return False
if 'c' in options:
self.printSUCCESS(_("Modified comment"))
if 'L' in options:
self.printSUCCESS(_("Locked Mail user %s")%str(userName))
self.printSUCCESS(_("Locked Mail user %s") % str(userName))
if 'U' in options:
self.printSUCCESS(_("Unlocked Mail user %s")%str(userName))
self.printSUCCESS(_("Unlocked Mail user %s") % str(userName))
if 'e' in options:
self.printSUCCESS(_("Modified Mail alternate addresses"))
if 'P' in options or 'p' in options:
@ -4227,7 +4235,7 @@ for user %s in 'Replication/Mail' branch") %userName)
servReplObj = servRepl()
if servReplObj.searchMailAlias(groupName):
self.printERROR(_("Mail group %s is found in \
'Replication/Mail' branch")%groupName)
'Replication/Mail' branch") % groupName)
return False
#Проверяем альтернативные почтовые адреса
modAttrs = []
@ -4238,46 +4246,46 @@ for user %s in 'Replication/Mail' branch") %userName)
if "@" in altMail:
if len(altMail.split("@")) != 2:
self.printERROR(_("Incorrect alternate adresses \
option '-e'"))
option '-e'"))
return False
mail = altMail
else:
mail = "%s@%s" %(altMail,self.clVars.Get("sr_mail_host"))
mail = "%s@%s" % (altMail, self.clVars.Get("sr_mail_host"))
if self.searchUserToMail(mail) or\
self.searchGroupToMail(mail):
self.printERROR(
_("Alternate email address %s is found in Mail service")%\
str(mail))
_("Alternate email address %s is found in Mail service")%\
str(mail))
return False
if servReplObj:
foundReplAlias = servReplObj.searchMailAddress(mail)
if foundReplAlias:
foundReplUser = foundReplAlias[0][0][1]['cn'][0].decode("UTF-8")
self.printERROR(_("Mail address %s is found in \
'Replication/Mail' branch")%mail)
'Replication/Mail' branch") % mail)
self.printERROR(_("The address belongs to \
mail user or group: %s")%foundReplUser)
mail user or group: %s") % foundReplUser)
return False
modAttrs.append('mailAlternateAddress: %s' %mail)
modAttrs.append('mailAlternateAddress: %s' % mail)
# Фильтр почты (hostname)
fHostNames = []
if 'hide' in options:
fHostNames = options['hide'].split(",")
for fHostName in fHostNames:
if not "." in fHostName:
fHostName = "%s.%s" %(fHostName,
self.clVars.Get('os_net_domain'))
modAttrs.append('filtersender: %s' %fHostName)
fHostName = "%s.%s" % (fHostName,
self.clVars.Get('os_net_domain'))
modAttrs.append('filtersender: %s' % fHostName)
if self.searchMailGroupToName(groupName):
self.printERROR(
_("group name %s is found in Mail service")%\
_("group name %s is found in Mail service")%\
str(groupName))
return False
mail = "%s@%s" %(groupName,self.clVars.Get("sr_mail_host"))
mail = "%s@%s" %(groupName, self.clVars.Get("sr_mail_host"))
if self.searchUserToMail(mail) or\
self.searchGroupToMail(mail):
self.printERROR(
_("Email address %s is found in Mail service")%\
_("Email address %s is found in Mail service")%\
str(mail))
return False
if servReplObj:
@ -4285,16 +4293,16 @@ mail user or group: %s")%foundReplUser)
if foundReplAlias:
foundReplUser = foundReplAlias[0][0][1]['cn'][0].decode("UTF-8")
self.printERROR(_("Mail address %s is found in \
'Replication/Mail' branch")%mail)
'Replication/Mail' branch") % mail)
self.printERROR(_("The address belongs to \
mail user or group: %s")%foundReplUser)
mail user or group: %s") % foundReplUser)
return False
self.clVars.Set("ur_group", groupName)
# Комментарий к группе
groupGecos = self.servUnixObj.groupGecos
if 'c' in options:
groupGecos = options['c']
self.clVars.Set("ur_group_comment",groupGecos)
self.clVars.Set("ur_group_comment", groupGecos)
ldifFile = self.ldifFileGroup
groupRawLdif = self.createLdif(ldifFile)
if not groupRawLdif:
@ -4334,10 +4342,10 @@ for user %s in 'Replication/Mail' branch") %str(mail))
modAttrs = []
# Включаем пользователя
if 'u' in options:
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "active")]
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', b"active")]
# Выключаем пользователя
elif 'l' in options:
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "passive")]
modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', b"passive")]
if not options:
optPasswd = {"p":""}
userPwd = self.getUserPassword(optPasswd, "p", False)
@ -4348,18 +4356,18 @@ for user %s in 'Replication/Mail' branch") %str(mail))
return False
if 'userPassword' in res[0][0][1]:
modAttrs.append((ldap.MOD_REPLACE, 'userPassword',
userPwdHash))
userPwdHash.encode("UTF-8")))
else:
modAttrs.append((ldap.MOD_ADD, 'userPassword',
userPwdHash))
userPwdHash.encode("UTF-8")))
if modAttrs:
DN = self.addDN("uid="+userName, self.relUsersDN)
DN = self.addDN("uid=" + userName, self.relUsersDN)
if not self.modAttrsDN(DN, modAttrs):
return False
if 'l' in options:
self.printSUCCESS(_("Locked Mail user %s")% str(userName))
self.printSUCCESS(_("Locked Mail user %s") % str(userName))
if 'u' in options:
self.printSUCCESS(_("Unlocked Mail user %s")% str(userName))
self.printSUCCESS(_("Unlocked Mail user %s") % str(userName))
if not options:
self.printSUCCESS(_("Changed Mail user password"))
return True
@ -4383,7 +4391,7 @@ for user %s in 'Replication/Mail' branch") %str(mail))
for userName in usersNames:
userMail = "%s@%s" %(userName,
self.clVars.Get("sr_mail_host"))
if userMail in usersInGroup:
if userMail.encode("UTF-8") in usersInGroup:
findUsers.append(userName)
return findUsers
@ -4466,7 +4474,7 @@ for user %s in 'Replication/Mail' branch") %str(mail))
for userName in users:
if not self.searchMailUserToName(userName):
self.printERROR(
_("User %s is not found in Mail service")%\
_("User %s is not found in Mail service")%\
str(userName))
flagFalse = True
break
@ -4483,9 +4491,9 @@ for user %s in 'Replication/Mail' branch") %str(mail))
modAttrs = []
for userName in addUsers:
userMail = "%s@%s" % (userName, self.clVars.Get("sr_mail_host"))
modAttrs.append((ldap.MOD_ADD, 'rfc822member', userMail))
modAttrs.append((ldap.MOD_ADD, 'rfc822member', userMail.encode("UTF-8")))
if modAttrs:
groupDN = self.addDN("cn="+groupName, self.relGroupsDN)
groupDN = self.addDN("cn=" + groupName, self.relGroupsDN)
return self.modAttrsDN(groupDN, modAttrs)
return True
@ -4515,7 +4523,7 @@ for user %s in 'Replication/Mail' branch") %str(mail))
servReplObj = servRepl()
if servReplObj.searchMailAlias(userName):
self.printERROR(_("Mail user %s is found in \
'Replication/Mail' branch")%userName)
'Replication/Mail' branch") % userName)
return False
#Проверяем альтернативные почтовые адреса
modAttrs = []
@ -4527,53 +4535,53 @@ for user %s in 'Replication/Mail' branch") %str(mail))
if "@" in altMail:
if len(altMail.split("@")) != 2:
self.printERROR(_("Incorrect alternate adresses option \
'-e'"))
'-e'"))
return False
mail = altMail
else:
mail = "%s@%s" %(altMail,self.clVars.Get("sr_mail_host"))
mail = "%s@%s" %(altMail, self.clVars.Get("sr_mail_host"))
if not primaryMail:
primaryMail = mail
if self.searchUserToMail(mail) or\
self.searchGroupToMail(mail):
self.printERROR(\
_("Alternate email address %s is found in Mail service")%\
str(mail))
_("Alternate email address %s is found in Mail service")%\
str(mail))
return False
if servReplObj:
foundReplAlias = servReplObj.searchMailAddress(mail)
if foundReplAlias:
foundReplUser = foundReplAlias[0][0][1]['cn'][0].decode("UTF-8")
self.printERROR(_("Mail address %s is found in \
'Replication/Mail' branch")%mail)
'Replication/Mail' branch")%mail)
self.printERROR(_("The address belongs to \
mail user or group: %s")%foundReplUser)
mail user or group: %s")%foundReplUser)
return False
modAttrs.append("mailAlternateAddress: %s" %mail)
modAttrs.append("mailAlternateAddress: %s" % mail)
else:
self.printERROR(\
_("Must be added one or more alternative addresses"))
_("Must be added one or more alternative addresses"))
self.printWARNING("cl-useradd -e gst@calculate.org guest mail")
return False
if self.searchMailUserToName(userName):
self.printERROR(_("User exists in Mail service"))
return False
else:
mail = "%s@%s" %(userName,self.clVars.Get("sr_mail_host"))
mail = "%s@%s" %(userName, self.clVars.Get("sr_mail_host"))
if self.searchUserToMail(mail) or\
self.searchGroupToMail(mail):
self.printERROR(
_("Email address %s is found in Mail service")%\
str(mail))
_("Email address %s is found in Mail service")%\
str(mail))
return False
if servReplObj:
foundReplAlias = servReplObj.searchMailAddress(mail)
if foundReplAlias:
foundReplUser = foundReplAlias[0][0][1]['cn'][0].decode("UTF-8")
self.printERROR(_("Mail address %s is found in \
'Replication/Mail' branch")%mail)
'Replication/Mail' branch") % mail)
self.printERROR(_("The address belongs to \
mail user or group: %s")%foundReplUser)
mail user or group: %s") % foundReplUser)
return False
# Почтовая директория пользователя
mailDir = os.path.join(self.clVars.Get("sr_mail_path"), userName)
@ -4637,7 +4645,7 @@ mail user or group: %s")%foundReplUser)
else:
if resUnix and 'cn' in resUnix[0][0][1]:
fullNameUser = resUnix[0][0][1]['cn'][0].decode("UTF-8")
self.clVars.Set("ur_fio",fullNameUser)
self.clVars.Set("ur_fio", fullNameUser)
if not userPwd:
userPwdHash = "crypt{xxx}"
else:
@ -4646,7 +4654,7 @@ mail user or group: %s")%foundReplUser)
if flagCreateUnixUser:
self.servUnixObj.delUserUnixServer(userName, {}, False, False)
return False
self.clVars.Set("ur_hash",userPwdHash)
self.clVars.Set("ur_hash", userPwdHash)
ldifFile = self.ldifFileUser
userRawLdif = self.createLdif(ldifFile)
if not userRawLdif:
@ -4677,7 +4685,7 @@ mail user or group: %s")%foundReplUser)
if not flagError:
# Востановим удаленного пользователя
message = _("Do you want to restore deleted user %s data?")\
%userName + "\n" + "'yes', 'no'"
% userName + "\n" + "'yes', 'no'"
resMailDir = self.restorePathDelUser(userName, mailDir,
"mail", message)
removeMailDirBack = False
@ -4695,14 +4703,14 @@ mail user or group: %s")%foundReplUser)
# Записываем основной почтовый адрес в ветку Unix
if not self.servUnixObj.setUserMail(userName, primaryMail):
self.printERROR(_("Failed set primary email for user %s in \
Unix service") %str(primaryMail))
Unix service") %str(primaryMail))
flagError = True
# Записываем почтовые алиасы в ветку
# репликации Replication/Mail
if not flagError and servReplObj:
if not servReplObj.addReplMailAlias(userName, altMails):
self.printERROR(_("Failed set mail aliases \
for user %s in 'Replication/Mail' branch") %userName)
for user %s in 'Replication/Mail' branch") %userName)
flagError = True
if not flagError and removeMailDirBack\
and os.path.exists(removeMailDirBack):
@ -4772,7 +4780,7 @@ for user %s in 'Replication/Mail' branch") %userName)
if i == 3 and not correctHostname(hostname):
printW()
self.printERROR(_("You used four attempts, \
if you want to continue to run the program again"))
if you want to continue to run the program again"))
return False
# Установка имени хоста
fullHostName = correctHostname(hostname)
@ -6459,7 +6467,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios)
rezultUnix, groupNamesUnix, errMessUnix =\
self.servUnixObj.searchGroupsUnix(userGroups, False)
grUnix = groupNamesUnix
groupNamesUnix = groupNamesUnix.keys()
groupNamesUnix = list(groupNamesUnix.keys())
# Если установлен сервис Samba
groupNamesSamba = []
gidNotFound = []
@ -6467,7 +6475,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios)
rezultSamba, groupNamesSamba, errMessSamba =\
self.searchGroupsSamba(userGroups, False)
grSamba = groupNamesSamba
groupNamesSamba = groupNamesSamba.keys()
groupNamesSamba = list(groupNamesSamba.keys())
userGroupNames = []
for userGr in userGroups:
try:
@ -6513,7 +6521,6 @@ Samba and Unix services") %", ".join(exclGroup)
resSearch = self.searchLdapDN(groupName, self.relGroupsDN, "cn")
return resSearch
def searchGroupsSamba(self, userGroups, printError=True):
"""Ищет список групп из списка userGroups в LDAP
@ -6528,13 +6535,13 @@ Samba and Unix services") %", ".join(exclGroup)
try:
int(gid)
except:
groupName = gid
groupName = gid.strip('\"').strip("\'")
res = self.searchSambaGroupName(groupName)
if not res:
groupErrors.append(groupName)
flagError = True
continue
userGroupNames[res[0][0][1]['cn'][0]]=\
userGroupNames[res[0][0][1]['cn'][0].decode("UTF-8")]=\
res[0][0][1]['gidNumber'][0].decode("UTF-8")
continue
gidNumber = gid
@ -6543,7 +6550,7 @@ Samba and Unix services") %", ".join(exclGroup)
gidErrors.append(gidNumber)
flagError = True
continue
userGroupNames[res[0][0][1]['cn'][0]] =\
userGroupNames[res[0][0][1]['cn'][0].decode("UTF-8")] =\
res[0][0][1]['gidNumber'][0].decode("UTF-8")
if flagError:
errorMessage = ""
@ -6562,6 +6569,7 @@ Samba and Unix services") %", ".join(exclGroup)
return (False, userGroupNames, errorMessage)
return (True, userGroupNames, "")
def searchSambaGid(self, groupId):
"""Находит группу сервиса Samba по ёе id"""
resSearch = self.searchLdapDN(str(groupId), self.relGroupsDN,
@ -13599,12 +13607,12 @@ remove user %s in the LDAP branch 'Worked'")%str(userName))
"""
varsData = ("unix_hash", "samba_lm_hash",
"samba_nt_hash", "samba_nt_hash_old")
if not set(varsData)<=set(varsDict.keys()):
if not set(varsData) <= set(varsDict.keys()):
notFoundVars = set(varsData) - set(varsDict.keys())
if len(notFoundVars)<len(varsData):
if len(notFoundVars) < len(varsData):
# Если какой либо ключ или ключи есть - выходим с ошибкой
self.printERROR(_("Variables (%s) are empty")\
%", ".join(notFoundVars) + ", "+\
%", ".join(notFoundVars) + ", " +\
_("file %s")%confFile)
return False
# Если нет всех ключей - выходим без ошибки
@ -17607,7 +17615,7 @@ class servDns(shareLdap):
# Проверим установлен ли сервис dns
if not self.isServiceSetup("dns"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
incompKeys = ["host","ip"]
if set(incompKeys)<=set(optKeys):
self.printERROR(_('Command line option "--host" (A-record) \
@ -17827,7 +17835,7 @@ incompatible with option "--ip" (PTR-record)'))
# Проверим установлен ли сервис dns
if not self.isServiceSetup("dns"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
minKeys = []
# Тип зоны по умолчанию
zoneType = "master"
@ -18515,7 +18523,7 @@ with option "--mxmod"')
locals()['update'],
locals()['expiry'],
locals()['minimum']]
optKeys = options.keys()
optKeys = list(options.keys())
if len(optKeys)>1:
sOARecord = " ".join(sOAList)
relZoneDN = self.getRelZoneDN(zoneName)
@ -18603,7 +18611,7 @@ with option "--mxmod"')
# Добавляем кавычки и --
addQ = lambda y: [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in y]
# Ключи опций
optKeys = options.keys()
optKeys = list(options.keys())
# Обязательные опции
requiredOpt = []
# Необязательные опции
@ -18640,8 +18648,8 @@ with option "--mxmod"')
return False
# Проверка обязательных опций
if not set(requiredOpt)<=set(optKeys):
notFoundReqOpt = list(set(requiredOpt)-set(optKeys))
if not set(requiredOpt) <= set(optKeys):
notFoundReqOpt = list(set(requiredOpt) - set(optKeys))
self.printERROR(_('Can not found required command line options %s')\
%", ".join(addQ(notFoundReqOpt)))
return False
@ -18663,7 +18671,7 @@ with option "--mxmod"')
% (" "+_("or")+" ").join(('"%s"' % x for x in value)))
return False
# Проверка лишних опций
unnecessaryOpt = list(set(optKeys)-set(requiredOpt+optionalOpt.keys()))
unnecessaryOpt = list(set(optKeys) - set(requiredOpt + list(optionalOpt.keys())))
if unnecessaryOpt:
self.printERROR(_("Exists unnecessary command line options %s")\
%",".join(addQ(unnecessaryOpt)))
@ -19503,7 +19511,7 @@ is incompatible with option "--ip"')
# Проверим установлен ли сервис dns
if not self.isServiceSetup("dns"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
# Опция force
if "f" in optKeys:
checkDHCPConfig = False
@ -20071,11 +20079,11 @@ class servDhcp(shareLdap, shareIP):
# Проверим установлен ли сервис dhcp
if checkSetup and not self.isServiceSetup("dhcp"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
minKeys = ["host", "ip", "mac"]
# Проверка на наличие всех нужных опций
if not set(minKeys)<=set(optKeys):
notFoundKeys = list(set(minKeys)-set(optKeys))
if not set(minKeys) <= set(optKeys):
notFoundKeys = list(set(minKeys) - set(optKeys))
notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys]
self.printERROR(_("Not enough command line options: %s") % ", ".join(notFoundKeys))
return False
@ -20484,11 +20492,11 @@ eth0, eth1, ... etc."%net)
# Проверим установлен ли сервис dhcp
if not self.isServiceSetup("dhcp"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
minKeys = ["host"]
# Проверка на наличие всех нужных опций
if not set(minKeys)<=set(optKeys):
notFoundKeys = list(set(minKeys)-set(optKeys))
if not set(minKeys) <= set(optKeys):
notFoundKeys = list(set(minKeys) - set(optKeys))
notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x
for x in notFoundKeys]
self.printERROR(_("Not enough command line options: %s")\
@ -20567,7 +20575,7 @@ eth0, eth1, ... etc."%net)
# Проверим установлен ли сервис dhcp
if not self.isServiceSetup("dhcp"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
minKeys = ["net"]
# Проверка на наличие всех нужных опций
if not set(minKeys)<=set(optKeys):
@ -20686,7 +20694,7 @@ eth0, eth1, ... etc."%net)
# Проверим установлен ли сервис dhcp
if checkSetup and not self.isServiceSetup("dhcp"):
return False
optKeys = options.keys()
optKeys = list(options.keys())
minKeys = ["net", "router", "range", "dnames", "dnsip"]
# Проверка на наличие всех нужных опций
if not set(minKeys)<=set(optKeys):
@ -20955,7 +20963,7 @@ eth0, eth1, ... etc."%net)
self.printERROR = printERROR
self.servDnsObj.printERROR = printERROR
optKeys = options.keys()
optKeys = list(options.keys())
minKeys = ["ip", "domain", "host", "s", "b"]
# Проверка на наличие всех нужных опций
if not set(minKeys) <= set(optKeys):
@ -21932,11 +21940,11 @@ network %s") % net)
set(bakupObj.notLdapServices))
if listServicesLDAP:
flagLdap = True
optKeys = options.keys()
optKeys = list(options.keys())
minKeys += ["net", "router", "range", "dnames", "dnsip"]
# Проверка на наличие всех нужных опций
if not set(minKeys)<=set(optKeys):
notFoundKeys = list(set(minKeys)-set(optKeys))
if not set(minKeys) <= set(optKeys):
notFoundKeys = list(set(minKeys) - set(optKeys))
notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys]
self.printERROR(_("Not enough command line options: %s")\
%", ".join(notFoundKeys))

@ -40,6 +40,7 @@ import string
import time
from copy import deepcopy
from collections.abc import Iterable
_ = lambda x : x
tr = cl_base.lang()
tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__])

@ -159,7 +159,8 @@ class Letter:
resent_to = self.getResentTo()
delivered_to = self.getDeliveredTo()
if resent_to and delivered_to:
order_field = self.mail.keys()
order_field = list(self.mail.keys())
#TODO probably will be bugged in py3: order of keys in dict changed
if order_field.index("Delivered-To") < order_field.index("Resent-To"):
receiver_emails = delivered_to
else:

Loading…
Cancel
Save