removed some debugs
[citadel.git] / citadel / ldap.c
1 // These functions implement the portions of AUTHMODE_LDAP and AUTHMODE_LDAP_AD which
2 // actually speak to the LDAP server.
3 //
4 // Copyright (c) 2011-2022 by the citadel.org development team.
5 //
6 // This program is open source software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License, version 3.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13
14 // ldapsearch -D uid=admin,cn=users,cn=compat,dc=demo1,dc=freeipa,dc=org -w Secret123 -h ipa.demo1.freeipa.org
15
16 int ctdl_require_ldap_version = 3;
17
18 #define _GNU_SOURCE             // Needed to suppress warning about vasprintf() when running on Linux/Linux
19 #include <stdio.h>
20 #include <libcitadel.h>
21 #include "citserver.h"
22 #include "citadel_ldap.h"
23 #include "ctdl_module.h"
24 #include "user_ops.h"
25 #include "internet_addressing.h"
26 #include "config.h"
27 #include <ldap.h>
28
29
30 // Utility function, supply a search result and get back the fullname (display name, common name, etc) from the first result
31 //
32 // POSIX schema:        the display name will be found in "cn" (common name)
33 // Active Directory:    the display name will be found in "displayName"
34 //
35 void derive_fullname_from_ldap_result(char *fullname, int fullname_size, LDAP *ldserver, LDAPMessage *search_result) {
36         struct berval **values;
37
38         if (fullname == NULL) return;
39         if (search_result == NULL) return;
40         if (ldserver == NULL) return;
41
42         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
43                 values = ldap_get_values_len(ldserver, search_result, "displayName");
44                 if (values) {
45                         if (ldap_count_values_len(values) > 0) {
46                                 safestrncpy(fullname, values[0]->bv_val, fullname_size);
47                                 syslog(LOG_DEBUG, "ldap: displayName = %s", fullname);
48                         }
49                         ldap_value_free_len(values);
50                 }
51         }
52         else {
53                 values = ldap_get_values_len(ldserver, search_result, "cn");
54                 if (values) {
55                         if (ldap_count_values_len(values) > 0) {
56                                 safestrncpy(fullname, values[0]->bv_val, fullname_size);
57                                 syslog(LOG_DEBUG, "ldap: cn = %s", fullname);
58                         }
59                         ldap_value_free_len(values);
60                 }
61         }
62 }
63
64
65 // Utility function, supply a search result and get back the uid from the first result
66 //
67 // POSIX schema:        numeric user id will be in the "uidNumber" attribute
68 // Active Directory:    we make a uid hashed from "objectGUID"
69 //
70 uid_t derive_uid_from_ldap(LDAP *ldserver, LDAPMessage *entry) {
71         struct berval **values;
72         uid_t uid = (-1);
73
74         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
75                 values = ldap_get_values_len(ldserver, entry, "objectGUID");
76                 if (values) {
77                         if (ldap_count_values_len(values) > 0) {
78                                 uid = abs(HashLittle(values[0]->bv_val, values[0]->bv_len));
79                         }
80                         ldap_value_free_len(values);
81                 }
82         }
83         else {
84                 values = ldap_get_values_len(ldserver, entry, "uidNumber");
85                 if (values) {
86                         if (ldap_count_values_len(values) > 0) {
87                                 uid = atoi(values[0]->bv_val);
88                         }
89                         ldap_value_free_len(values);
90                 }
91         }
92
93         syslog(LOG_DEBUG, "ldap: uid = %d", uid);
94         return(uid);
95 }
96
97
98 // Wrapper function for ldap_initialize() that consistently fills in the correct fields
99 int ctdl_ldap_initialize(LDAP **ld) {
100
101         char server_url[256];
102         int ret;
103
104         snprintf(server_url, sizeof server_url, "ldap://%s:%d", CtdlGetConfigStr("c_ldap_host"), CtdlGetConfigInt("c_ldap_port"));
105         ret = ldap_initialize(ld, server_url);
106         if (ret != LDAP_SUCCESS) {
107                 syslog(LOG_ERR, "ldap: could not connect to %s : %m", server_url);
108                 *ld = NULL;
109                 return(errno);
110         }
111
112         return(ret);
113 }
114
115
116 // Bind to the LDAP server and return a working handle
117 LDAP *ctdl_ldap_bind(void) {
118         LDAP *ldserver = NULL;
119         int i;
120
121         if (ctdl_ldap_initialize(&ldserver) != LDAP_SUCCESS) {
122                 return(NULL);
123         }
124
125         ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
126         ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
127
128         striplt(CtdlGetConfigStr("c_ldap_bind_dn"));
129         striplt(CtdlGetConfigStr("c_ldap_bind_pw"));
130         i = ldap_simple_bind_s(ldserver,
131                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_dn")) ? CtdlGetConfigStr("c_ldap_bind_dn") : NULL),
132                 (!IsEmptyStr(CtdlGetConfigStr("c_ldap_bind_pw")) ? CtdlGetConfigStr("c_ldap_bind_pw") : NULL)
133         );
134         if (i != LDAP_SUCCESS) {
135                 syslog(LOG_ERR, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
136                 return(NULL);
137         }
138
139         return(ldserver);
140 }
141
142
143 // Look up a user in the directory to see if this is an account that can be authenticated
144 //
145 // POSIX schema:        Search all "inetOrgPerson" objects with "uid" set to the supplied username
146 // Active Directory:    Look for an account with "sAMAccountName" set to the supplied username
147 //
148 int CtdlTryUserLDAP(char *username, char *found_dn, int found_dn_size, char *fullname, int fullname_size, uid_t *uid) {
149         LDAP *ldserver = NULL;
150         LDAPMessage *search_result = NULL;
151         LDAPMessage *entry = NULL;
152         char searchstring[1024];
153         struct timeval tv;
154         char *user_dn = NULL;
155
156         ldserver = ctdl_ldap_bind();
157         if (!ldserver) return(-1);
158
159         if (fullname) safestrncpy(fullname, username, fullname_size);
160         tv.tv_sec = 10;
161         tv.tv_usec = 0;
162
163         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
164                 snprintf(searchstring, sizeof(searchstring), "(sAMAccountName=%s)", username);
165         }
166         else {
167                 snprintf(searchstring, sizeof(searchstring), "(&(objectclass=inetOrgPerson)(uid=%s))", username);
168         }
169
170         syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
171         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
172                 ldserver,                                       // ld
173                 CtdlGetConfigStr("c_ldap_base_dn"),             // base
174                 LDAP_SCOPE_SUBTREE,                             // scope
175                 searchstring,                                   // filter
176                 NULL,                                           // attrs (all attributes)
177                 0,                                              // attrsonly (attrs + values)
178                 NULL,                                           // serverctrls (none)
179                 NULL,                                           // clientctrls (none)
180                 &tv,                                            // timeout
181                 1,                                              // sizelimit (1 result max)
182                 &search_result                                  // put the result here
183         )));
184
185         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
186         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
187         if (search_result == NULL) {
188                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
189                 ldap_unbind(ldserver);
190                 return(2);
191         }
192
193         // At this point we've got at least one result from our query.  If there are multiple
194         // results, we still only look at the first one.
195         entry = ldap_first_entry(ldserver, search_result);
196         if (entry) {
197
198                 user_dn = ldap_get_dn(ldserver, entry);
199                 if (user_dn) {
200                         syslog(LOG_DEBUG, "ldap: dn = %s", user_dn);
201                 }
202
203                 derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, search_result);
204                 *uid = derive_uid_from_ldap(ldserver, search_result);
205         }
206
207         // free the results
208         ldap_msgfree(search_result);
209
210         // unbind so we can go back in as the authenticating user
211         ldap_unbind(ldserver);
212
213         if (!user_dn) {
214                 syslog(LOG_DEBUG, "ldap: No such user was found.");
215                 return(4);
216         }
217
218         if (found_dn) safestrncpy(found_dn, user_dn, found_dn_size);
219         ldap_memfree(user_dn);
220         return(0);
221 }
222
223
224 // This is an extension of CtdlTryPassword() which gets called when using LDAP authentication.
225 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
226         LDAP *ldserver = NULL;
227         int i = (-1);
228
229         if (IsEmptyStr(password)) {
230                 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
231                 return(1);
232         }
233
234         syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
235         i = ctdl_ldap_initialize(&ldserver);
236         if (i == LDAP_SUCCESS) {
237                 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
238                 i = ldap_simple_bind_s(ldserver, user_dn, password);
239                 if (i == LDAP_SUCCESS) {
240                         syslog(LOG_DEBUG, "ldap: bind succeeded");
241                 }
242                 else {
243                         syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
244                 }
245                 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
246                 ldap_unbind(ldserver);
247         }
248
249         if (i == LDAP_SUCCESS) {
250                 return(0);
251         }
252
253         return(1);
254 }
255
256
257 // set multiple properties
258 // returns nonzero only if property changed.
259 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
260         int i;
261         char *oldval = "";
262         for (i=0; i<numvals; i++) {
263                 oldval = vcard_get_prop(v, propname, 0, i, 0);
264                 if (oldval == NULL) break;
265                 if (strcmp(vals[i],oldval)) break;
266         }
267         if (i != numvals) {
268                 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
269                 for (i=0; i<numvals; i++) {
270                         vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
271                 }
272                 return 1;
273         }
274         return 0;
275 }
276
277
278 // set one property
279 // returns nonzero only if property changed.
280 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
281         va_list args;
282         char *newvalue;
283         int did_change = 0;
284         va_start(args,newfmt);
285         if (vasprintf(&newvalue, newfmt, args) < 0) {
286                 syslog(LOG_ERR, "ldap: out of memory");
287                 return 0;
288         }
289         did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
290         va_end(args);
291         free(newvalue);
292         return did_change;
293 }
294
295
296 // Learn LDAP attributes and stuff them into the vCard.
297 // Returns nonzero if we changed anything.
298 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
299         int changed_something = 0;
300         LDAP *ldserver = NULL;
301         struct timeval tv;
302         LDAPMessage *search_result = NULL;
303         LDAPMessage *entry = NULL;
304         struct berval **givenName;
305         struct berval **sn;
306         struct berval **cn;
307         struct berval **initials;
308         struct berval **o;
309         struct berval **street;
310         struct berval **l;
311         struct berval **st;
312         struct berval **postalCode;
313         struct berval **telephoneNumber;
314         struct berval **mobile;
315         struct berval **homePhone;
316         struct berval **facsimileTelephoneNumber;
317         struct berval **mail;
318         struct berval **uid;
319         struct berval **homeDirectory;
320         struct berval **uidNumber;
321         struct berval **loginShell;
322         struct berval **gidNumber;
323         struct berval **c;
324         struct berval **title;
325         struct berval **uuid;
326         char *attrs[] = { "*","+",NULL};
327
328         if (!ldap_dn) return(0);
329         if (!v) return(0);
330
331         ldserver = ctdl_ldap_bind();
332         if (!ldserver) return(-1);
333
334         tv.tv_sec = 10;
335         tv.tv_usec = 0;
336
337         syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
338         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
339                 ldserver,                               // ld
340                 ldap_dn,                                // base
341                 LDAP_SCOPE_SUBTREE,                     // scope
342                 NULL,                                   // filter
343                 attrs,                                  // attrs (all attributes)
344                 0,                                      // attrsonly (attrs + values)
345                 NULL,                                   // serverctrls (none)
346                 NULL,                                   // clientctrls (none)
347                 &tv,                                    // timeout
348                 1,                                      // sizelimit (1 result max)
349                 &search_result                          // res
350         )));
351         
352         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
353         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
354         if (search_result == NULL) {
355                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
356                 ldap_unbind(ldserver);
357                 return(0);
358         }
359
360         // At this point we've got at least one result from our query.  If there are multiple
361         // results, we still only look at the first one.
362         entry = ldap_first_entry(ldserver, search_result);
363         if (entry) {
364                 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
365                 givenName                       = ldap_get_values_len(ldserver, search_result, "givenName");
366                 sn                              = ldap_get_values_len(ldserver, search_result, "sn");
367                 cn                              = ldap_get_values_len(ldserver, search_result, "cn");
368                 initials                        = ldap_get_values_len(ldserver, search_result, "initials");
369                 title                           = ldap_get_values_len(ldserver, search_result, "title");
370                 o                               = ldap_get_values_len(ldserver, search_result, "o");
371                 street                          = ldap_get_values_len(ldserver, search_result, "street");
372                 l                               = ldap_get_values_len(ldserver, search_result, "l");
373                 st                              = ldap_get_values_len(ldserver, search_result, "st");
374                 postalCode                      = ldap_get_values_len(ldserver, search_result, "postalCode");
375                 telephoneNumber                 = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
376                 mobile                          = ldap_get_values_len(ldserver, search_result, "mobile");
377                 homePhone                       = ldap_get_values_len(ldserver, search_result, "homePhone");
378                 facsimileTelephoneNumber        = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
379                 mail                            = ldap_get_values_len(ldserver, search_result, "mail");
380                 uid                             = ldap_get_values_len(ldserver, search_result, "uid");
381                 homeDirectory                   = ldap_get_values_len(ldserver, search_result, "homeDirectory");
382                 uidNumber                       = ldap_get_values_len(ldserver, search_result, "uidNumber");
383                 loginShell                      = ldap_get_values_len(ldserver, search_result, "loginShell");
384                 gidNumber                       = ldap_get_values_len(ldserver, search_result, "gidNumber");
385                 c                               = ldap_get_values_len(ldserver, search_result, "c");
386                 uuid                            = ldap_get_values_len(ldserver, search_result, "entryUUID");
387
388                 if (street && l && st && postalCode && c) changed_something |= vcard_set_one_prop_iff_different(v,"adr",";;%s;%s;%s;%s;%s",street[0]->bv_val,l[0]->bv_val,st[0]->bv_val,postalCode[0]->bv_val,c[0]->bv_val);
389                 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
390                 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
391                 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
392                 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
393                 if (givenName && sn) {
394                         if (initials) {
395                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s;%s",sn[0]->bv_val,givenName[0]->bv_val,initials[0]->bv_val);
396                         }
397                         else {
398                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
399                         }
400                 }
401
402                 // FIXME we need a new way to do this.
403                 //if (mail) {
404                         //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
405                 //}
406
407                 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
408                 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
409                 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
410                 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
411                 
412                 if (givenName)                  ldap_value_free_len(givenName);
413                 if (initials)                   ldap_value_free_len(initials);
414                 if (sn)                         ldap_value_free_len(sn);
415                 if (cn)                         ldap_value_free_len(cn);
416                 if (o)                          ldap_value_free_len(o);
417                 if (street)                     ldap_value_free_len(street);
418                 if (l)                          ldap_value_free_len(l);
419                 if (st)                         ldap_value_free_len(st);
420                 if (postalCode)                 ldap_value_free_len(postalCode);
421                 if (telephoneNumber)            ldap_value_free_len(telephoneNumber);
422                 if (mobile)                     ldap_value_free_len(mobile);
423                 if (homePhone)                  ldap_value_free_len(homePhone);
424                 if (facsimileTelephoneNumber)   ldap_value_free_len(facsimileTelephoneNumber);
425                 if (mail)                       ldap_value_free_len(mail);
426                 if (uid)                        ldap_value_free_len(uid);
427                 if (homeDirectory)              ldap_value_free_len(homeDirectory);
428                 if (uidNumber)                  ldap_value_free_len(uidNumber);
429                 if (loginShell)                 ldap_value_free_len(loginShell);
430                 if (gidNumber)                  ldap_value_free_len(gidNumber);
431                 if (c)                          ldap_value_free_len(c);
432                 if (title)                      ldap_value_free_len(title);
433                 if (uuid)                       ldap_value_free_len(uuid);
434         }
435         // free the results
436         ldap_msgfree(search_result);
437
438         // unbind so we can go back in as the authenticating user
439         ldap_unbind(ldserver);
440         return(changed_something);      // tell the caller whether we made any changes
441 }
442
443
444 // Extract a user's Internet email addresses from LDAP.
445 // Returns zero if we got a valid set of addresses; nonzero for error.
446 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
447         LDAP *ldserver = NULL;
448         struct timeval tv;
449         LDAPMessage *search_result = NULL;
450         LDAPMessage *entry = NULL;
451         struct berval **mail;
452         char *attrs[] = { "*","+",NULL };
453
454         if (!ldap_dn) return(1);
455         if (!emailaddrs) return(1);
456
457         ldserver = ctdl_ldap_bind();
458         if (!ldserver) return(-1);
459
460         tv.tv_sec = 10;
461         tv.tv_usec = 0;
462
463         syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
464         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
465                 ldserver,                               // ld
466                 ldap_dn,                                // base
467                 LDAP_SCOPE_SUBTREE,                     // scope
468                 NULL,                                   // filter
469                 attrs,                                  // attrs (all attributes)
470                 0,                                      // attrsonly (attrs + values)
471                 NULL,                                   // serverctrls (none)
472                 NULL,                                   // clientctrls (none)
473                 &tv,                                    // timeout
474                 1,                                      // sizelimit (1 result max)
475                 &search_result                          // res
476         )));
477         
478         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
479         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
480         if (search_result == NULL) {
481                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
482                 ldap_unbind(ldserver);
483                 return(4);
484         }
485
486         // At this point we've got at least one result from our query.
487         // If there are multiple results, we still only look at the first one.
488         emailaddrs[0] = 0;                                                              // clear out any previous results
489         entry = ldap_first_entry(ldserver, search_result);
490         if (entry) {
491                 syslog(LOG_DEBUG, "ldap: search got user details");
492                 mail = ldap_get_values_len(ldserver, search_result, "mail");
493                 if (mail) {
494                         int q;
495                         for (q=0; q<ldap_count_values_len(mail); ++q) {
496                                 if (IsDirectory(mail[q]->bv_val, 0)) {
497                                         if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
498                                                 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
499                                         }
500                                         else {
501                                                 if (!IsEmptyStr(emailaddrs)) {
502                                                         strcat(emailaddrs, "|");
503                                                 }
504                                                 strcat(emailaddrs, mail[q]->bv_val);
505                                         }
506                                 }
507                         }
508                 }
509         }
510
511         // free the results
512         ldap_msgfree(search_result);
513
514         // unbind so we can go back in as the authenticating user
515         ldap_unbind(ldserver);
516         return(0);
517 }
518
519
520 // Remember that a particular user exists in the Citadel database.
521 // As we scan the LDAP tree we will remove users from this list when we find them.
522 // At the end of the scan, any users remaining in this list are stale and should be deleted.
523 void ldap_note_user_in_citadel(char *username, void *data) {
524         return;
525 }
526
527
528 // Scan LDAP for users and populate Citadel's user database with everyone
529 //
530 // POSIX schema:        All objects of class "inetOrgPerson"
531 // Active Directory:    Objects that are class "user" and class "person" but NOT class "computer"
532 //
533 void CtdlSynchronizeUsersFromLDAP(void) {
534         LDAP *ldserver = NULL;
535         LDAPMessage *search_result = NULL;
536         LDAPMessage *entry = NULL;
537         char *user_dn = NULL;
538         char searchstring[1024];
539         struct timeval tv;
540
541         if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
542                 return;                                         // If this site is not running LDAP, stop here.
543         }
544
545         syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
546
547         // first, scan the existing Citadel user list
548         // ForEachUser(ldap_note_user_in_citadel, NULL);        // FIXME finish this
549
550         ldserver = ctdl_ldap_bind();
551         if (!ldserver) return;
552
553         tv.tv_sec = 10;
554         tv.tv_usec = 0;
555
556         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
557                         snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
558         }
559         else {
560                         snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
561         }
562
563         syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
564         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
565                 ldserver,                                       // ld
566                 CtdlGetConfigStr("c_ldap_base_dn"),             // base
567                 LDAP_SCOPE_SUBTREE,                             // scope
568                 searchstring,                                   // filter
569                 NULL,                                           // attrs (all attributes)
570                 0,                                              // attrsonly (attrs + values)
571                 NULL,                                           // serverctrls (none)
572                 NULL,                                           // clientctrls (none)
573                 &tv,                                            // timeout
574                 INT_MAX,                                        // sizelimit (max)
575                 &search_result                                  // put the result here
576         )));
577
578         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
579         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
580         if (search_result == NULL) {
581                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
582                 ldap_unbind(ldserver);
583                 return;
584         }
585
586         syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
587         for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
588                 user_dn = ldap_get_dn(ldserver, entry);
589                 if (user_dn) {
590                         syslog(LOG_DEBUG, "ldap: found %s", user_dn);
591
592                         int fullname_size = 256;
593                         char fullname[256] = { 0 } ;
594                         uid_t uid = (-1);
595                         char new_emailaddrs[512] = { 0 } ;
596
597                         uid = derive_uid_from_ldap(ldserver, entry);
598                         derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
599                         syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
600
601                         // now create or update the user
602                         int found_user;
603                         struct ctdluser usbuf;
604
605                         found_user = getuserbyuid(&usbuf, uid);
606                         if (found_user != 0) {
607                                 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
608                                 found_user = getuserbyuid(&usbuf, uid);
609                                 strcpy(fullname, usbuf.fullname);
610                         }
611
612                         if (found_user == 0) {          // user record exists
613                                                         // now update the account email addresses if necessary
614                                 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
615                                         if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
616                                                 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) {                         // update only if changed
617                                                         CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
618                                                 }
619                                         }
620                                 }
621                         }
622                         ldap_memfree(user_dn);
623                 }
624         }
625
626         // free the results
627         ldap_msgfree(search_result);
628
629         // unbind so we can go back in as the authenticating user
630         ldap_unbind(ldserver);
631 }