349cadfe79cd5cb864d44f88f3cae9aea3fd93aa
[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                                  // res
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 int CtdlTryPasswordLDAP(char *user_dn, const char *password) {
225         LDAP *ldserver = NULL;
226         int i = (-1);
227
228         if (IsEmptyStr(password)) {
229                 syslog(LOG_DEBUG, "ldap: empty passwords are not permitted");
230                 return(1);
231         }
232
233         syslog(LOG_DEBUG, "ldap: trying to bind as %s", user_dn);
234         i = ctdl_ldap_initialize(&ldserver);
235         if (i == LDAP_SUCCESS) {
236                 ldap_set_option(ldserver, LDAP_OPT_PROTOCOL_VERSION, &ctdl_require_ldap_version);
237                 i = ldap_simple_bind_s(ldserver, user_dn, password);
238                 if (i == LDAP_SUCCESS) {
239                         syslog(LOG_DEBUG, "ldap: bind succeeded");
240                 }
241                 else {
242                         syslog(LOG_DEBUG, "ldap: Cannot bind: %s (%d)", ldap_err2string(i), i);
243                 }
244                 ldap_set_option(ldserver, LDAP_OPT_REFERRALS, (void *)LDAP_OPT_OFF);
245                 ldap_unbind(ldserver);
246         }
247
248         if (i == LDAP_SUCCESS) {
249                 return(0);
250         }
251
252         return(1);
253 }
254
255
256 // set multiple properties
257 // returns nonzero only if property changed.
258 int vcard_set_props_iff_different(struct vCard *v, char *propname, int numvals, char **vals) {
259         int i;
260         char *oldval = "";
261         for (i=0; i<numvals; i++) {
262                 oldval = vcard_get_prop(v, propname, 0, i, 0);
263                 if (oldval == NULL) break;
264                 if (strcmp(vals[i],oldval)) break;
265         }
266         if (i != numvals) {
267                 syslog(LOG_DEBUG, "ldap: vcard property %s, element %d of %d changed from %s to %s", propname, i, numvals, oldval, vals[i]);
268                 for (i=0; i<numvals; i++) {
269                         vcard_set_prop(v,propname,vals[i],(i==0) ? 0 : 1);
270                 }
271                 return 1;
272         }
273         return 0;
274 }
275
276
277 // set one property
278 // returns nonzero only if property changed.
279 int vcard_set_one_prop_iff_different(struct vCard *v,char *propname, char *newfmt, ...) {
280         va_list args;
281         char *newvalue;
282         int did_change = 0;
283         va_start(args,newfmt);
284         if (vasprintf(&newvalue, newfmt, args) < 0) {
285                 syslog(LOG_ERR, "ldap: out of memory");
286                 return 0;
287         }
288         did_change = vcard_set_props_iff_different(v, propname, 1, &newvalue);
289         va_end(args);
290         free(newvalue);
291         return did_change;
292 }
293
294
295 // Learn LDAP attributes and stuff them into the vCard.
296 // Returns nonzero if we changed anything.
297 int Ctdl_LDAP_to_vCard(char *ldap_dn, struct vCard *v) {
298         int changed_something = 0;
299         LDAP *ldserver = NULL;
300         struct timeval tv;
301         LDAPMessage *search_result = NULL;
302         LDAPMessage *entry = NULL;
303         struct berval **givenName;
304         struct berval **sn;
305         struct berval **cn;
306         struct berval **initials;
307         struct berval **o;
308         struct berval **street;
309         struct berval **l;
310         struct berval **st;
311         struct berval **postalCode;
312         struct berval **telephoneNumber;
313         struct berval **mobile;
314         struct berval **homePhone;
315         struct berval **facsimileTelephoneNumber;
316         struct berval **mail;
317         struct berval **uid;
318         struct berval **homeDirectory;
319         struct berval **uidNumber;
320         struct berval **loginShell;
321         struct berval **gidNumber;
322         struct berval **c;
323         struct berval **title;
324         struct berval **uuid;
325         char *attrs[] = { "*","+",NULL};
326
327         if (!ldap_dn) return(0);
328         if (!v) return(0);
329
330         ldserver = ctdl_ldap_bind();
331         if (!ldserver) return(-1);
332
333         tv.tv_sec = 10;
334         tv.tv_usec = 0;
335
336         syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
337         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
338                 ldserver,                               // ld
339                 ldap_dn,                                // base
340                 LDAP_SCOPE_SUBTREE,                     // scope
341                 NULL,                                   // filter
342                 attrs,                                  // attrs (all attributes)
343                 0,                                      // attrsonly (attrs + values)
344                 NULL,                                   // serverctrls (none)
345                 NULL,                                   // clientctrls (none)
346                 &tv,                                    // timeout
347                 1,                                      // sizelimit (1 result max)
348                 &search_result                          // res
349         )));
350         
351         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
352         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
353         if (search_result == NULL) {
354                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
355                 ldap_unbind(ldserver);
356                 return(0);
357         }
358
359         // At this point we've got at least one result from our query.  If there are multiple
360         // results, we still only look at the first one.
361         entry = ldap_first_entry(ldserver, search_result);
362         if (entry) {
363                 syslog(LOG_DEBUG, "ldap: search got user details for vcard.");
364                 givenName                       = ldap_get_values_len(ldserver, search_result, "givenName");
365                 sn                              = ldap_get_values_len(ldserver, search_result, "sn");
366                 cn                              = ldap_get_values_len(ldserver, search_result, "cn");
367                 initials                        = ldap_get_values_len(ldserver, search_result, "initials");
368                 title                           = ldap_get_values_len(ldserver, search_result, "title");
369                 o                               = ldap_get_values_len(ldserver, search_result, "o");
370                 street                          = ldap_get_values_len(ldserver, search_result, "street");
371                 l                               = ldap_get_values_len(ldserver, search_result, "l");
372                 st                              = ldap_get_values_len(ldserver, search_result, "st");
373                 postalCode                      = ldap_get_values_len(ldserver, search_result, "postalCode");
374                 telephoneNumber                 = ldap_get_values_len(ldserver, search_result, "telephoneNumber");
375                 mobile                          = ldap_get_values_len(ldserver, search_result, "mobile");
376                 homePhone                       = ldap_get_values_len(ldserver, search_result, "homePhone");
377                 facsimileTelephoneNumber        = ldap_get_values_len(ldserver, search_result, "facsimileTelephoneNumber");
378                 mail                            = ldap_get_values_len(ldserver, search_result, "mail");
379                 uid                             = ldap_get_values_len(ldserver, search_result, "uid");
380                 homeDirectory                   = ldap_get_values_len(ldserver, search_result, "homeDirectory");
381                 uidNumber                       = ldap_get_values_len(ldserver, search_result, "uidNumber");
382                 loginShell                      = ldap_get_values_len(ldserver, search_result, "loginShell");
383                 gidNumber                       = ldap_get_values_len(ldserver, search_result, "gidNumber");
384                 c                               = ldap_get_values_len(ldserver, search_result, "c");
385                 uuid                            = ldap_get_values_len(ldserver, search_result, "entryUUID");
386
387                 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);
388                 if (telephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;work","%s",telephoneNumber[0]->bv_val);
389                 if (facsimileTelephoneNumber) changed_something |= vcard_set_one_prop_iff_different(v,"tel;fax","%s",facsimileTelephoneNumber[0]->bv_val);
390                 if (mobile) changed_something |= vcard_set_one_prop_iff_different(v,"tel;cell","%s",mobile[0]->bv_val);
391                 if (homePhone) changed_something |= vcard_set_one_prop_iff_different(v,"tel;home","%s",homePhone[0]->bv_val);
392                 if (givenName && sn) {
393                         if (initials) {
394                                 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);
395                         }
396                         else {
397                                 changed_something |= vcard_set_one_prop_iff_different(v,"n","%s;%s",sn[0]->bv_val,givenName[0]->bv_val);
398                         }
399                 }
400
401                 // FIXME we need a new way to do this.
402                 //if (mail) {
403                         //changed_something |= vcard_set_props_iff_different(v,"email;internet",ldap_count_values_len(mail),mail);
404                 //}
405
406                 if (uuid) changed_something |= vcard_set_one_prop_iff_different(v,"X-uuid","%s",uuid[0]->bv_val);
407                 if (o) changed_something |= vcard_set_one_prop_iff_different(v,"org","%s",o[0]->bv_val);
408                 if (cn) changed_something |= vcard_set_one_prop_iff_different(v,"fn","%s",cn[0]->bv_val);
409                 if (title) changed_something |= vcard_set_one_prop_iff_different(v,"title","%s",title[0]->bv_val);
410                 
411                 if (givenName)                  ldap_value_free_len(givenName);
412                 if (initials)                   ldap_value_free_len(initials);
413                 if (sn)                         ldap_value_free_len(sn);
414                 if (cn)                         ldap_value_free_len(cn);
415                 if (o)                          ldap_value_free_len(o);
416                 if (street)                     ldap_value_free_len(street);
417                 if (l)                          ldap_value_free_len(l);
418                 if (st)                         ldap_value_free_len(st);
419                 if (postalCode)                 ldap_value_free_len(postalCode);
420                 if (telephoneNumber)            ldap_value_free_len(telephoneNumber);
421                 if (mobile)                     ldap_value_free_len(mobile);
422                 if (homePhone)                  ldap_value_free_len(homePhone);
423                 if (facsimileTelephoneNumber)   ldap_value_free_len(facsimileTelephoneNumber);
424                 if (mail)                       ldap_value_free_len(mail);
425                 if (uid)                        ldap_value_free_len(uid);
426                 if (homeDirectory)              ldap_value_free_len(homeDirectory);
427                 if (uidNumber)                  ldap_value_free_len(uidNumber);
428                 if (loginShell)                 ldap_value_free_len(loginShell);
429                 if (gidNumber)                  ldap_value_free_len(gidNumber);
430                 if (c)                          ldap_value_free_len(c);
431                 if (title)                      ldap_value_free_len(title);
432                 if (uuid)                       ldap_value_free_len(uuid);
433         }
434         // free the results
435         ldap_msgfree(search_result);
436
437         // unbind so we can go back in as the authenticating user
438         ldap_unbind(ldserver);
439         return(changed_something);      // tell the caller whether we made any changes
440 }
441
442
443 // Extract a user's Internet email addresses from LDAP.
444 // Returns zero if we got a valid set of addresses; nonzero for error.
445 int extract_email_addresses_from_ldap(char *ldap_dn, char *emailaddrs) {
446         LDAP *ldserver = NULL;
447         struct timeval tv;
448         LDAPMessage *search_result = NULL;
449         LDAPMessage *entry = NULL;
450         struct berval **mail;
451         char *attrs[] = { "*","+",NULL };
452
453         if (!ldap_dn) return(1);
454         if (!emailaddrs) return(1);
455
456         ldserver = ctdl_ldap_bind();
457         if (!ldserver) return(-1);
458
459         tv.tv_sec = 10;
460         tv.tv_usec = 0;
461
462         syslog(LOG_DEBUG, "ldap: search: %s", ldap_dn);
463         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
464                 ldserver,                               // ld
465                 ldap_dn,                                // base
466                 LDAP_SCOPE_SUBTREE,                     // scope
467                 NULL,                                   // filter
468                 attrs,                                  // attrs (all attributes)
469                 0,                                      // attrsonly (attrs + values)
470                 NULL,                                   // serverctrls (none)
471                 NULL,                                   // clientctrls (none)
472                 &tv,                                    // timeout
473                 1,                                      // sizelimit (1 result max)
474                 &search_result                          // res
475         )));
476         
477         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
478         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
479         if (search_result == NULL) {
480                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
481                 ldap_unbind(ldserver);
482                 return(4);
483         }
484
485         // At this point we've got at least one result from our query.
486         // If there are multiple results, we still only look at the first one.
487         emailaddrs[0] = 0;                                                              // clear out any previous results
488         entry = ldap_first_entry(ldserver, search_result);
489         if (entry) {
490                 syslog(LOG_DEBUG, "ldap: search got user details");
491                 mail = ldap_get_values_len(ldserver, search_result, "mail");
492                 if (mail) {
493                         int q;
494                         for (q=0; q<ldap_count_values_len(mail); ++q) {
495                                 if (IsDirectory(mail[q]->bv_val, 0)) {
496                                         if ((strlen(emailaddrs) + mail[q]->bv_len + 2) > 512) {
497                                                 syslog(LOG_ERR, "ldap: can't fit all email addresses into user record");
498                                         }
499                                         else {
500                                                 if (!IsEmptyStr(emailaddrs)) {
501                                                         strcat(emailaddrs, "|");
502                                                 }
503                                                 strcat(emailaddrs, mail[q]->bv_val);
504                                         }
505                                 }
506                         }
507                 }
508         }
509
510         // free the results
511         ldap_msgfree(search_result);
512
513         // unbind so we can go back in as the authenticating user
514         ldap_unbind(ldserver);
515         return(0);
516 }
517
518
519 // Scan LDAP for users and populate Citadel's user database with everyone
520 //
521 // POSIX schema:        All objects of class "inetOrgPerson"
522 // Active Directory:    Objects that are class "user" and class "person" but NOT class "computer"
523 //
524 void CtdlSynchronizeUsersFromLDAP(void) {
525         LDAP *ldserver = NULL;
526         LDAPMessage *search_result = NULL;
527         LDAPMessage *entry = NULL;
528         char *user_dn = NULL;
529         char searchstring[1024];
530         struct timeval tv;
531
532         if ((CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP) && (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_LDAP_AD)) {
533                 return;                                         // This site is not running LDAP.  Stop here.
534         }
535
536         syslog(LOG_INFO, "ldap: synchronizing Citadel user database from LDAP");
537
538         ldserver = ctdl_ldap_bind();
539         if (!ldserver) return;
540
541         tv.tv_sec = 10;
542         tv.tv_usec = 0;
543
544         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_LDAP_AD) {
545                         snprintf(searchstring, sizeof(searchstring), "(&(objectClass=user)(objectClass=person)(!(objectClass=computer)))");
546         }
547         else {
548                         snprintf(searchstring, sizeof(searchstring), "(objectClass=inetOrgPerson)");
549         }
550
551         syslog(LOG_DEBUG, "ldap: search: %s", searchstring);
552         syslog(LOG_DEBUG, "ldap: search results: %s", ldap_err2string(ldap_search_ext_s(
553                 ldserver,                                       // ld
554                 CtdlGetConfigStr("c_ldap_base_dn"),             // base
555                 LDAP_SCOPE_SUBTREE,                             // scope
556                 searchstring,                                   // filter
557                 NULL,                                           // attrs (all attributes)
558                 0,                                              // attrsonly (attrs + values)
559                 NULL,                                           // serverctrls (none)
560                 NULL,                                           // clientctrls (none)
561                 &tv,                                            // timeout
562                 INT_MAX,                                        // sizelimit (max)
563                 &search_result                                  // result
564         )));
565
566         // Ignore the return value of ldap_search_ext_s().  Sometimes it returns an error even when
567         // the search succeeds.  Instead, we check to see whether search_result is still NULL.
568         if (search_result == NULL) {
569                 syslog(LOG_DEBUG, "ldap: zero search results were returned");
570                 ldap_unbind(ldserver);
571                 return;
572         }
573
574         syslog(LOG_DEBUG, "ldap: %d entries returned", ldap_count_entries(ldserver, search_result));
575         for (entry=ldap_first_entry(ldserver, search_result); entry!=NULL; entry=ldap_next_entry(ldserver, entry)) {
576                 TRACE;
577                 user_dn = ldap_get_dn(ldserver, entry);
578                 if (user_dn) {
579                         syslog(LOG_DEBUG, "ldap: found %s", user_dn);
580
581                         int fullname_size = 256;
582                         char fullname[256] = { 0 } ;
583                         uid_t uid = (-1);
584                         char new_emailaddrs[512] = { 0 } ;
585
586                         uid = derive_uid_from_ldap(ldserver, entry);
587                         derive_fullname_from_ldap_result(fullname, fullname_size, ldserver, entry);
588                         syslog(LOG_DEBUG, "ldap: display name: <%s> , uid = <%d>", fullname, uid);
589
590                         // now create or update the user
591                         int found_user;
592                         struct ctdluser usbuf;
593
594                         found_user = getuserbyuid(&usbuf, uid);
595                         if (found_user != 0) {
596                                 create_user(fullname, CREATE_USER_DO_NOT_BECOME_USER, uid);
597                                 found_user = getuserbyuid(&usbuf, uid);
598                                 strcpy(fullname, usbuf.fullname);
599                         }
600
601                         if (found_user == 0) {          // user record exists
602                                                         // now update the account email addresses if necessary
603                                 if (CtdlGetConfigInt("c_ldap_sync_email_addrs") > 0) {
604                                         if (extract_email_addresses_from_ldap(user_dn, new_emailaddrs) == 0) {
605                                                 if (strcmp(usbuf.emailaddrs, new_emailaddrs)) {                         // update only if changed
606                                                         CtdlSetEmailAddressesForUser(usbuf.fullname, new_emailaddrs);
607                                                 }
608                                         }
609                                 }
610                         }
611                         ldap_memfree(user_dn);
612                 }
613                 TRACE;
614         }
615
616         // free the results
617         ldap_msgfree(search_result);
618
619         // unbind so we can go back in as the authenticating user
620         ldap_unbind(ldserver);
621 }