]> git.decadent.org.uk Git - dak.git/blob - dak/import_ldap_fingerprints.py
Stop using silly names, and migrate to a saner directory structure.
[dak.git] / dak / import_ldap_fingerprints.py
1 #!/usr/bin/env python
2
3 # Sync fingerprint and uid tables with a debian.org LDAP DB
4 # Copyright (C) 2003, 2004  James Troup <james@nocrew.org>
5 # $Id: emilie,v 1.3 2004-11-27 13:25:35 troup Exp $
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 2 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, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 # <elmo>  ping@debian.org ?
24 # <aj>    missing@ ? wtfru@ ?
25 # <elmo>  giggle
26 # <elmo>  I like wtfru
27 # <aj>    all you have to do is retrofit wtfru into an acronym and no one
28 #         could possibly be offended!
29 # <elmo>  aj: worried terriers for russian unity ?
30 # <aj>    uhhh
31 # <aj>    ooookkkaaaaay
32 # <elmo>  wthru is a little less offensive maybe?  but myabe that's
33 #         just because I read h as heck, not hell
34 # <elmo>  ho hum
35 # <aj>    (surely the "f" stands for "freedom" though...)
36 # <elmo>  where the freedom are you?
37 # <aj>    'xactly
38 # <elmo>  or worried terriers freed (of) russian unilateralism ?
39 # <aj>    freedom -- it's the "foo" of the 21st century
40 # <aj>    oo, how about "wat@" as in wherefore art thou?
41 # <neuro> or worried attack terriers
42 # <aj>    Waning Trysts Feared - Return? Unavailable?
43 # <aj>    (i find all these terriers more worrying, than worried)
44 # <neuro> worrying attack terriers, then
45
46 ################################################################################
47
48 import commands, ldap, pg, re, sys, time;
49 import apt_pkg;
50 import db_access, utils;
51
52 ################################################################################
53
54 Cnf = None;
55 projectB = None;
56
57 re_gpg_fingerprint = re.compile(r"^\s+Key fingerprint = (.*)$", re.MULTILINE);
58 re_debian_address = re.compile(r"^.*<(.*)@debian\.org>$", re.MULTILINE);
59
60 ################################################################################
61
62 def usage(exit_code=0):
63     print """Usage: emilie
64 Syncs fingerprint and uid tables with a debian.org LDAP DB
65
66   -h, --help                show this help and exit."""
67     sys.exit(exit_code)
68
69 ################################################################################
70
71 def get_ldap_value(entry, value):
72     ret = entry.get(value);
73     if not ret:
74         return "";
75     else:
76         # FIXME: what about > 0 ?
77         return ret[0];
78
79 def main():
80     global Cnf, projectB;
81
82     Cnf = utils.get_conf()
83     Arguments = [('h',"help","Emilie::Options::Help")];
84     for i in [ "help" ]:
85         if not Cnf.has_key("Emilie::Options::%s" % (i)):
86             Cnf["Emilie::Options::%s" % (i)] = "";
87
88     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv);
89
90     Options = Cnf.SubTree("Emilie::Options")
91     if Options["Help"]:
92         usage();
93
94     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
95     db_access.init(Cnf, projectB);
96
97     #before = time.time();
98     #sys.stderr.write("[Getting info from the LDAP server...");
99     LDAPDn = Cnf["Emilie::LDAPDn"];
100     LDAPServer = Cnf["Emilie::LDAPServer"];
101     l = ldap.open(LDAPServer);
102     l.simple_bind_s("","");
103     Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
104                        "(&(keyfingerprint=*)(gidnumber=%s))" % (Cnf["Julia::ValidGID"]),
105                        ["uid", "keyfingerprint"]);
106     #sys.stderr.write("done. (%d seconds)]\n" % (int(time.time()-before)));
107
108
109     projectB.query("BEGIN WORK");
110
111
112     # Sync LDAP with DB
113     db_fin_uid = {};
114     ldap_fin_uid_id = {};
115     q = projectB.query("""
116 SELECT f.fingerprint, f.id, u.uid FROM fingerprint f, uid u WHERE f.uid = u.id
117  UNION SELECT f.fingerprint, f.id, null FROM fingerprint f where f.uid is null""");
118     for i in q.getresult():
119         (fingerprint, fingerprint_id, uid) = i;
120         db_fin_uid[fingerprint] = (uid, fingerprint_id);
121
122     for i in Attrs:
123         entry = i[1];
124         fingerprints = entry["keyFingerPrint"];
125         uid = entry["uid"][0];
126         uid_id = db_access.get_or_set_uid_id(uid);
127         for fingerprint in fingerprints:
128             ldap_fin_uid_id[fingerprint] = (uid, uid_id);
129             if db_fin_uid.has_key(fingerprint):
130                 (existing_uid, fingerprint_id) = db_fin_uid[fingerprint];
131                 if not existing_uid:
132                     q = projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id));
133                     print "Assigning %s to 0x%s." % (uid, fingerprint);
134                 else:
135                     if existing_uid != uid:
136                         utils.fubar("%s has %s in LDAP, but projectB says it should be %s." % (uid, fingerprint, existing_uid));
137
138     # Try to update people who sign with non-primary key
139     q = projectB.query("SELECT fingerprint, id FROM fingerprint WHERE uid is null");
140     for i in q.getresult():
141         (fingerprint, fingerprint_id) = i;
142         cmd = "gpg --no-default-keyring --keyring=%s --keyring=%s --fingerprint %s" \
143               % (Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"],
144                  fingerprint);
145         (result, output) = commands.getstatusoutput(cmd);
146         if result == 0:
147             m = re_gpg_fingerprint.search(output);
148             if not m:
149                 print output
150                 utils.fubar("0x%s: No fingerprint found in gpg output but it returned 0?\n%s" % (fingerprint, utils.prefix_multi_line_string(output, " [GPG output:] ")));
151             primary_key = m.group(1);
152             primary_key = primary_key.replace(" ","");
153             if not ldap_fin_uid_id.has_key(primary_key):
154                 utils.fubar("0x%s (from 0x%s): no UID found in LDAP" % (primary_key, fingerprint));
155             (uid, uid_id) = ldap_fin_uid_id[primary_key];
156             q = projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id));
157             print "Assigning %s to 0x%s." % (uid, fingerprint);
158         else:
159             extra_keyrings = "";
160             for keyring in Cnf.ValueList("Emilie::ExtraKeyrings"):
161                 extra_keyrings += " --keyring=%s" % (keyring);
162             cmd = "gpg --keyring=%s --keyring=%s %s --list-key %s" \
163                   % (Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"],
164                      extra_keyrings, fingerprint);
165             (result, output) = commands.getstatusoutput(cmd);
166             if result != 0:
167                 cmd = "gpg --keyserver=%s --allow-non-selfsigned-uid --recv-key %s" % (Cnf["Emilie::KeyServer"], fingerprint);
168                 (result, output) = commands.getstatusoutput(cmd);
169                 if result != 0:
170                     print "0x%s: NOT found on keyserver." % (fingerprint);
171                     print cmd
172                     print result
173                     print output
174                     continue;
175                 else:
176                     cmd = "gpg --list-key %s" % (fingerprint);
177                     (result, output) = commands.getstatusoutput(cmd);
178                     if result != 0:
179                         print "0x%s: --list-key returned error after --recv-key didn't." % (fingerprint);
180                         print cmd
181                         print result
182                         print output
183                         continue;
184             m = re_debian_address.search(output);
185             if m:
186                 guess_uid = m.group(1);
187             else:
188                 guess_uid = "???";
189             name = " ".join(output.split('\n')[0].split()[3:]);
190             print "0x%s -> %s -> %s" % (fingerprint, name, guess_uid);
191             # FIXME: make me optionally non-interactive
192             # FIXME: default to the guessed ID
193             uid = None;
194             while not uid:
195                 uid = utils.our_raw_input("Map to which UID ? ");
196                 Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(uid=%s)" % (uid), ["cn","mn","sn"])
197                 if not Attrs:
198                     print "That UID doesn't exist in LDAP!"
199                     uid = None;
200                 else:
201                     entry = Attrs[0][1];
202                     name = " ".join([get_ldap_value(entry, "cn"),
203                                      get_ldap_value(entry, "mn"),
204                                      get_ldap_value(entry, "sn")]);
205                     prompt = "Map to %s - %s (y/N) ? " % (uid, name.replace("  "," "));
206                     yn = utils.our_raw_input(prompt).lower();
207                     if yn == "y":
208                         uid_id = db_access.get_or_set_uid_id(uid);
209                         projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id));
210                         print "Assigning %s to 0x%s." % (uid, fingerprint);
211                     else:
212                         uid = None;
213     projectB.query("COMMIT WORK");
214
215 ############################################################
216
217 if __name__ == '__main__':
218     main()