1 # Some routines and configuration that are used by the ldap progams
2 import termios, TERMIOS, re, string, imp, ldap, sys, whrandom, crypt, rfc822;
5 File = open("/etc/userdir-ldap/userdir-ldap.conf");
7 File = open("userdir-ldap.conf");
8 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
12 BaseDn = ConfModule.basedn;
13 BaseDn = ConfModule.basedn;
14 LDAPServer = ConfModule.ldaphost;
15 EmailAppend = ConfModule.emailappend;
16 AdminUser = ConfModule.adminuser;
17 GenerateDir = ConfModule.generatedir;
18 GenerateConf = ConfModule.generateconf;
19 DefaultGID = ConfModule.defaultgid;
20 TemplatesDir = ConfModule.templatesdir;
21 PassDir = ConfModule.passdir;
22 Ech_ErrorLog = ConfModule.ech_errorlog;
23 Ech_MainLog = ConfModule.ech_mainlog;
25 # This is a list of common last-name prefixes
26 LastNamesPre = {"van": None, "le": None, "de": None, "di": None};
28 # SSH Key splitting. The result is:
29 # (options,size,modulous,exponent,comment)
30 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
31 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
33 # Safely get an attribute from a tuple representing a dn and an attribute
34 # list. It returns the first attribute if there are multi.
35 def GetAttr(DnRecord,Attribute,Default = ""):
37 return DnRecord[1][Attribute][0];
44 # Return a printable email address from the attributes.
45 def EmailAddress(DnRecord):
46 cn = GetAttr(DnRecord,"cn");
47 sn = GetAttr(DnRecord,"sn");
48 uid = GetAttr(DnRecord,"uid");
49 if cn == "" and sn == "":
50 return "<" + uid + "@" + EmailAppend + ">";
51 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
53 # Show a dump like ldapsearch
54 def PrettyShow(DnRecord):
56 List = DnRecord[1].keys();
61 Result = Result + "%s: %s\n" % (x,i);
64 # Function to prompt for a password
65 def getpass(prompt = "Password: "):
66 import termios, TERMIOS, sys;
67 fd = sys.stdin.fileno();
68 old = termios.tcgetattr(fd);
69 new = termios.tcgetattr(fd);
70 new[3] = new[3] & ~TERMIOS.ECHO; # lflags
72 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new);
73 passwd = raw_input(prompt);
75 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old);
79 # Split up a name into multiple components. This tries to best guess how
82 Words = re.split(" ",string.strip(Name));
84 # Insert an empty middle name
90 # Put a dot after any 1 letter words, must be an initial
91 for x in range(0,len(Words)):
92 if len(Words[x]) == 1:
93 Words[x] = Words[x] + '.';
95 # If a word starts with a -, ( or [ we assume it marks the start of some
96 # Non-name information and remove the remainder of the string
97 for x in range(0,len(Words)):
98 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
99 Words[x][0] == '(' or Words[x][0] == '['):
103 # Merge any of the middle initials
105 while len(Words[2]) == 2 and Words[2][1] == '.':
106 Words[1] = Words[1] + Words[2];
109 while len(Words) < 2:
112 # Merge any of the last name prefixes into one big last name
113 while LastNamesPre.has_key(string.lower(Words[-2])):
114 Words[-1] = Words[-2] + " " + Words[-1];
117 # Fix up a missing middle name after lastname globbing
118 if (len(Words) == 2):
121 # If the name is multi-word then we glob them all into the last name and
122 # do not worry about a middle name
124 Words[2] = string.join(Words[1:]);
127 return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
129 # Compute a random password using /dev/urandom
131 # Generate a 10 character random string
132 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
133 Rand = open("/dev/urandom");
135 for i in range(0,10):
136 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
139 # Compute the MD5 crypted version of the given password
140 def HashPass(Password):
141 # Hash it telling glibc to use the MD5 algorithm - if you dont have
142 # glibc then just change Salt = "$1$" to Salt = "";
143 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
145 for x in range(0,10):
146 Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
147 Pass = crypt.crypt(Password,Salt);
149 raise "Password Error", "MD5 password hashing failed, not changing the password!";
152 # Sync with the server, we count the number of async requests that are pending
153 # and make sure result has been called that number of times
154 def FlushOutstanding(l,Outstanding,Fast=0):
155 # Sync with the remote end
157 print "Waiting for",Outstanding,"requests:",
158 while (Outstanding > 0):
160 if Fast == 0 or Outstanding > 50:
161 sys.stdout.write(".",);
163 if (l.result(ldap.RES_ANY,1) != (None,None)):
164 Outstanding = Outstanding - 1;
166 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
167 Outstanding = Outstanding - 1;
170 except ldap.TYPE_OR_VALUE_EXISTS:
171 Outstanding = Outstanding - 1;
172 except ldap.NO_SUCH_ATTRIBUTE:
173 Outstanding = Outstanding - 1;
174 except ldap.NO_SUCH_OBJECT:
175 Outstanding = Outstanding - 1;
180 # Convert a lat/long attribute into Decimal degrees
181 def DecDegree(Posn,Anon=0):
182 Parts = re.match('[+-]?(\d*)\\.?(\d*)?',Posn).groups();
183 Val = string.atof(Posn);
185 if (abs(Val) >= 1806060.0):
186 raise ValueError,"Too Big";
189 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
191 Secs = Val - long(Val);
192 Val = long(Val)/100.0;
193 Min = Val - long(Val);
194 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
197 elif abs(Val) >= 180 or len(Parts[0]) > 3:
199 Min = Val - long(Val);
200 Val = long(Val) + Min*100.0/60.0;
210 def FormatSSHAuth(Str):
211 Match = SSHAuthSplit.match(Str);
213 return "<unknown format>";
218 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
219 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
221 def FormatPGPKey(Str):
227 while (I < len(Str)):
229 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
231 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
233 elif (len(Str) == 40):
236 while (I < len(Str)):
238 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
240 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
244 return string.strip(Res);
246 # Take an email address and split it into 3 parts, (Name,UID,Domain)
247 def SplitEmail(Addr):
248 Res1 = rfc822.AddrlistClass(Addr).getaddress();
253 return (Res1[0],"","");
254 Res2 = string.split(Res1[1],"@");
256 return (Res1[0],"",Res1[1]);
257 return (Res1[0],Res2[0],Res2[1]);