eab3cabbf2a6c2c41cf6378a4af921737b6bc8bd
[mirror/userdir-ldap.git] / userdir_ldap.py
1 # Some routines and configuration that are used by the ldap progams
2 import termios, TERMIOS, re, string, imp, ldap, sys, whrandom, crypt;
3
4 try:
5    File = open("/etc/userdir-ldap/userdir-ldap.conf");
6 except:
7    File = open("userdir-ldap.conf");
8 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
9 File.close();
10
11 BaseDn = ConfModule.basedn;
12 BaseDn = ConfModule.basedn;
13 LDAPServer = ConfModule.ldaphost;
14 EmailAppend = ConfModule.emailappend;
15 AdminUser = ConfModule.adminuser;
16 GenerateDir = ConfModule.generatedir;
17 GenerateConf = ConfModule.generateconf;
18 DefaultGID = ConfModule.defaultgid;
19 TemplatesDir = ConfModule.templatesdir;
20 PassDir = ConfModule.passdir;
21
22 # This is a list of common last-name prefixes
23 LastNamesPre = {"van": None, "le": None, "de": None, "di": None};
24    
25 # Safely get an attribute from a tuple representing a dn and an attribute
26 # list. It returns the first attribute if there are multi.
27 def GetAttr(DnRecord,Attribute,Default = ""):
28    try:
29       return DnRecord[1][Attribute][0];
30    except IndexError:
31       return Default;
32    except KeyError:
33       return Default;
34    return Default;
35
36 # Return a printable email address from the attributes.
37 def EmailAddress(DnRecord):
38    cn = GetAttr(DnRecord,"cn");
39    sn = GetAttr(DnRecord,"sn");
40    uid = GetAttr(DnRecord,"uid");
41    if cn == "" and sn == "":
42       return "<" + uid + "@" + EmailAppend + ">";
43    return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
44
45 # Show a dump like ldapsearch
46 def PrettyShow(DnRecord):
47    Result = "";
48    List = DnRecord[1].keys();
49    List.sort();
50    for x in List:
51       Rec = DnRecord[1][x];
52       for i in Rec:
53          Result = Result + "%s: %s\n" % (x,i);
54    return Result[:-1];
55
56 # Function to prompt for a password 
57 def getpass(prompt = "Password: "):
58    import termios, TERMIOS, sys;
59    fd = sys.stdin.fileno();
60    old = termios.tcgetattr(fd);
61    new = termios.tcgetattr(fd);
62    new[3] = new[3] & ~TERMIOS.ECHO;          # lflags
63    try:
64       termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new);
65       passwd = raw_input(prompt);
66    finally:
67       termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old);
68    print;
69    return passwd;
70
71 # Split up a name into multiple components. This tries to best guess how
72 # to split up a name
73 def NameSplit(Name):
74    Words = re.split(" ",string.strip(Name));
75
76    # Insert an empty middle name
77    if (len(Words) == 2):
78       Words.insert(1,"");
79    if (len(Words) < 2):
80       Words.append("");
81
82    # Put a dot after any 1 letter words, must be an initial
83    for x in range(0,len(Words)):
84       if len(Words[x]) == 1:
85          Words[x] = Words[x] + '.';
86
87    # If a word starts with a -, ( or [ we assume it marks the start of some
88    # Non-name information and remove the remainder of the string
89    for x in range(0,len(Words)):
90       if len(Words[x]) != 0 and (Words[x][0] == '-' or \
91           Words[x][0] == '(' or Words[x][0] == '['):
92          Words = Words[0:x];
93          break;
94          
95    # Merge any of the middle initials
96    if len(Words) > 2:
97       while len(Words[2]) == 2 and Words[2][1] == '.':
98          Words[1] = Words[1] +  Words[2];
99          del Words[2];
100
101    while len(Words) < 2:
102       Words.append('');
103    
104    # Merge any of the last name prefixes into one big last name
105    while LastNamesPre.has_key(string.lower(Words[-2])):
106       Words[-1] = Words[-2] + " " + Words[-1];
107       del Words[-2];
108
109    # Fix up a missing middle name after lastname globbing
110    if (len(Words) == 2):
111       Words.insert(1,"");
112
113    # If the name is multi-word then we glob them all into the last name and
114    # do not worry about a middle name
115    if (len(Words) > 3):
116       Words[2] = string.join(Words[1:]);
117       Words[1] = "";
118
119    return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
120
121 # Compute a random password using /dev/urandom
122 def GenPass():   
123    # Generate a 10 character random string
124    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
125    Rand = open("/dev/urandom");
126    Password = "";
127    for i in range(0,10):
128       Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
129    return Password;
130
131 # Compute the MD5 crypted version of the given password
132 def HashPass(Password):
133    # Hash it telling glibc to use the MD5 algorithm - if you dont have
134    # glibc then just change Salt = "$1$" to Salt = "";
135    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
136    Salt  = "$1$";
137    for x in range(0,10):
138       Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
139    Pass = crypt.crypt(Password,Salt);
140    if len(Pass) < 14:
141       raise "Password Error", "MD5 password hashing failed, not changing the password!";
142    return Pass;
143
144 # Sync with the server, we count the number of async requests that are pending
145 # and make sure result has been called that number of times
146 def FlushOutstanding(l,Outstanding,Fast=0):
147    # Sync with the remote end
148    if Fast == 0:
149       print "Waiting for",Outstanding,"requests:",
150    while (Outstanding > 0):
151       try:
152          if Fast == 0 or Outstanding > 50:
153             sys.stdout.write(".",);
154             sys.stdout.flush();
155             if (l.result(ldap.RES_ANY,1) != (None,None)):
156                Outstanding = Outstanding - 1;
157          else:
158             if (l.result(ldap.RES_ANY,1,0) != (None,None)):
159                Outstanding = Outstanding - 1;
160             else:
161                break;
162       except ldap.TYPE_OR_VALUE_EXISTS:
163          Outstanding = Outstanding - 1;
164       except ldap.NO_SUCH_ATTRIBUTE:
165          Outstanding = Outstanding - 1;
166       except ldap.NO_SUCH_OBJECT:
167          Outstanding = Outstanding - 1;
168    if Fast == 0:
169       print;
170    return Outstanding;