* src/codeconv.c
[claws.git] / src / syldap.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2001-2002 Match Grun
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Functions necessary to access LDAP servers.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #ifdef USE_LDAP
29
30 #include <glib.h>
31 #include <gdk/gdk.h>
32 #include <gtk/gtkmain.h>
33 #include <sys/time.h>
34 #include <string.h>
35 #include <ldap.h>
36 #include <lber.h>
37 #include <pthread.h>
38
39 #include "mgutils.h"
40 #include "addritem.h"
41 #include "addrcache.h"
42 #include "syldap.h"
43 #include "utils.h"
44 #include "adbookbase.h"
45
46 /*
47 * Create new LDAP server interface object.
48 */
49 SyldapServer *syldap_create() {
50         SyldapServer *ldapServer;
51
52         debug_print("Creating LDAP server interface object\n");
53
54         ldapServer = g_new0( SyldapServer, 1 );
55         ldapServer->type = ADBOOKTYPE_LDAP;
56         ldapServer->addressCache = addrcache_create();
57         ldapServer->accessFlag = FALSE;
58         ldapServer->retVal = MGU_SUCCESS;
59         ldapServer->hostName = NULL;
60         ldapServer->port = SYLDAP_DFL_PORT;
61         ldapServer->baseDN = NULL;
62         ldapServer->bindDN = NULL;
63         ldapServer->bindPass = NULL;
64         ldapServer->searchCriteria = NULL;
65         ldapServer->searchValue = NULL;
66         ldapServer->entriesRead = 0;
67         ldapServer->maxEntries = SYLDAP_MAX_ENTRIES;
68         ldapServer->timeOut = SYLDAP_DFL_TIMEOUT;
69         ldapServer->newSearch = TRUE;
70         ldapServer->thread = NULL;
71         ldapServer->busyFlag = FALSE;
72         ldapServer->callBack = NULL;
73         ldapServer->idleId = 0;
74         return ldapServer;
75 }
76
77 /*
78 * Specify name to be used.
79 */
80 void syldap_set_name( SyldapServer* ldapServer, const gchar *value ) {
81         g_return_if_fail( ldapServer != NULL );
82         addrcache_set_name( ldapServer->addressCache, value );
83 }
84
85 /*
86 * Specify hostname to be used.
87 */
88 void syldap_set_host( SyldapServer* ldapServer, const gchar *value ) {
89         addrcache_refresh( ldapServer->addressCache );
90         ldapServer->hostName = mgu_replace_string( ldapServer->hostName, value );
91         g_strstrip( ldapServer->hostName );
92 }
93
94 /*
95 * Specify port to be used.
96 */
97 void syldap_set_port( SyldapServer* ldapServer, const gint value ) {
98         addrcache_refresh( ldapServer->addressCache );
99         if( value > 0 ) {
100                 ldapServer->port = value;
101         }
102         else {
103                 ldapServer->port = SYLDAP_DFL_PORT;
104         }
105 }
106
107 /*
108 * Specify base DN to be used.
109 */
110 void syldap_set_base_dn( SyldapServer* ldapServer, const gchar *value ) {
111         addrcache_refresh( ldapServer->addressCache );
112         ldapServer->baseDN = mgu_replace_string( ldapServer->baseDN, value );
113         g_strstrip( ldapServer->baseDN );
114 }
115
116 /*
117 * Specify bind DN to be used.
118 */
119 void syldap_set_bind_dn( SyldapServer* ldapServer, const gchar *value ) {
120         addrcache_refresh( ldapServer->addressCache );
121         ldapServer->bindDN = mgu_replace_string( ldapServer->bindDN, value );
122         g_strstrip( ldapServer->bindDN );
123 }
124
125 /*
126 * Specify bind password to be used.
127 */
128 void syldap_set_bind_password( SyldapServer* ldapServer, const gchar *value ) {
129         addrcache_refresh( ldapServer->addressCache );
130         ldapServer->bindPass = mgu_replace_string( ldapServer->bindPass, value );
131         g_strstrip( ldapServer->bindPass );
132 }
133
134 /*
135 * Specify search criteria to be used.
136 */
137 void syldap_set_search_criteria( SyldapServer* ldapServer, const gchar *value ) {
138         addrcache_refresh( ldapServer->addressCache );
139         ldapServer->searchCriteria = mgu_replace_string( ldapServer->searchCriteria, value );
140         g_strstrip( ldapServer->searchCriteria );
141         ldapServer->newSearch = TRUE;
142 }
143
144 /*
145 * Specify search value to be searched for.
146 */
147 void syldap_set_search_value( SyldapServer* ldapServer, const gchar *value ) {
148         addrcache_refresh( ldapServer->addressCache );
149         ldapServer->searchValue = mgu_replace_string( ldapServer->searchValue, value );
150         g_strstrip( ldapServer->searchValue );
151         ldapServer->newSearch = TRUE;
152 }
153
154 /*
155 * Specify maximum number of entries to retrieve.
156 */
157 void syldap_set_max_entries( SyldapServer* ldapServer, const gint value ) {
158         addrcache_refresh( ldapServer->addressCache );
159         if( value > 0 ) {
160                 ldapServer->maxEntries = value;
161         }
162         else {
163                 ldapServer->maxEntries = SYLDAP_MAX_ENTRIES;
164         }
165 }
166
167 /*
168 * Specify timeout value for LDAP operation (in seconds).
169 */
170 void syldap_set_timeout( SyldapServer* ldapServer, const gint value ) {
171         addrcache_refresh( ldapServer->addressCache );
172         if( value > 0 ) {
173                 ldapServer->timeOut = value;
174         }
175         else {
176                 ldapServer->timeOut = SYLDAP_DFL_TIMEOUT;
177         }
178 }
179
180 /*
181 * Register a callback function. When called, the function will be passed
182 * this object as an argument.
183 */
184 void syldap_set_callback( SyldapServer *ldapServer, void *func ) {
185         ldapServer->callBack = func;
186 }
187
188 void syldap_set_accessed( SyldapServer *ldapServer, const gboolean value ) {
189         g_return_if_fail( ldapServer != NULL );
190         ldapServer->accessFlag = value;
191 }
192
193 /*
194 * Refresh internal variables to force a file read.
195 */
196 void syldap_force_refresh( SyldapServer *ldapServer ) {
197         addrcache_refresh( ldapServer->addressCache );
198         ldapServer->newSearch = TRUE;
199 }
200
201 gint syldap_get_status( SyldapServer *ldapServer ) {
202         g_return_val_if_fail( ldapServer != NULL, -1 );
203         return ldapServer->retVal;
204 }
205
206 ItemFolder *syldap_get_root_folder( SyldapServer *ldapServer ) {
207         g_return_val_if_fail( ldapServer != NULL, NULL );
208         return addrcache_get_root_folder( ldapServer->addressCache );
209 }
210
211 gchar *syldap_get_name( SyldapServer *ldapServer ) {
212         g_return_val_if_fail( ldapServer != NULL, NULL );
213         return addrcache_get_name( ldapServer->addressCache );
214 }
215
216 gboolean syldap_get_accessed( SyldapServer *ldapServer ) {
217         g_return_val_if_fail( ldapServer != NULL, FALSE );
218         return ldapServer->accessFlag;
219 }
220
221 /*
222 * Free up LDAP server interface object by releasing internal memory.
223 */
224 void syldap_free( SyldapServer *ldapServer ) {
225         g_return_if_fail( ldapServer != NULL );
226
227         debug_print("Freeing LDAP server interface object\n");
228
229         ldapServer->callBack = NULL;
230
231         /* Clear cache */
232         addrcache_clear( ldapServer->addressCache );
233         addrcache_free( ldapServer->addressCache );
234
235         /* Free internal stuff */
236         g_free( ldapServer->hostName );
237         g_free( ldapServer->baseDN );
238         g_free( ldapServer->bindDN );
239         g_free( ldapServer->bindPass );
240         g_free( ldapServer->searchCriteria );
241         g_free( ldapServer->searchValue );
242         g_free( ldapServer->thread );
243
244
245         /* Clear pointers */
246         ldapServer->hostName = NULL;
247         ldapServer->port = 0;
248         ldapServer->baseDN = NULL;
249         ldapServer->bindDN = NULL;
250         ldapServer->bindPass = NULL;
251         ldapServer->searchCriteria = NULL;
252         ldapServer->searchValue = NULL;
253         ldapServer->entriesRead = 0;
254         ldapServer->maxEntries = 0;
255         ldapServer->timeOut = 0;
256         ldapServer->newSearch = FALSE;
257         ldapServer->thread = NULL;
258         ldapServer->busyFlag = FALSE;
259         ldapServer->callBack = NULL;
260         ldapServer->idleId = 0;
261
262         ldapServer->type = ADBOOKTYPE_NONE;
263         ldapServer->addressCache = NULL;
264         ldapServer->accessFlag = FALSE;
265         ldapServer->retVal = MGU_SUCCESS;
266
267         /* Now release LDAP object */
268         g_free( ldapServer );
269 }
270
271 /*
272 * Display object to specified stream.
273 */
274 void syldap_print_data( SyldapServer *ldapServer, FILE *stream ) {
275         g_return_if_fail( ldapServer != NULL );
276
277         fprintf( stream, "SyldapServer:\n" );
278         fprintf( stream, "host name: '%s'\n", ldapServer->hostName );
279         fprintf( stream, "     port: %d\n",   ldapServer->port );
280         fprintf( stream, "  base dn: '%s'\n", ldapServer->baseDN );
281         fprintf( stream, "  bind dn: '%s'\n", ldapServer->bindDN );
282         fprintf( stream, "bind pass: '%s'\n", ldapServer->bindPass );
283         fprintf( stream, " criteria: '%s'\n", ldapServer->searchCriteria );
284         fprintf( stream, "searchval: '%s'\n", ldapServer->searchValue );
285         fprintf( stream, "max entry: %d\n",   ldapServer->maxEntries );
286         fprintf( stream, " num read: %d\n",   ldapServer->entriesRead );
287         fprintf( stream, "  ret val: %d\n",   ldapServer->retVal );
288         addrcache_print( ldapServer->addressCache, stream );
289         addritem_print_item_folder( ldapServer->addressCache->rootFolder, stream );
290 }
291
292 /*
293 * Display object to specified stream.
294 */
295 void syldap_print_short( SyldapServer *ldapServer, FILE *stream ) {
296         g_return_if_fail( ldapServer != NULL );
297
298         fprintf( stream, "SyldapServer:\n" );
299         fprintf( stream, "host name: '%s'\n", ldapServer->hostName );
300         fprintf( stream, "     port: %d\n",   ldapServer->port );
301         fprintf( stream, "  base dn: '%s'\n", ldapServer->baseDN );
302         fprintf( stream, "  bind dn: '%s'\n", ldapServer->bindDN );
303         fprintf( stream, "bind pass: '%s'\n", ldapServer->bindPass );
304         fprintf( stream, " criteria: '%s'\n", ldapServer->searchCriteria );
305         fprintf( stream, "searchval: '%s'\n", ldapServer->searchValue );
306         fprintf( stream, "max entry: %d\n",   ldapServer->maxEntries );
307         fprintf( stream, " num read: %d\n",   ldapServer->entriesRead );
308         fprintf( stream, "  ret val: %d\n",   ldapServer->retVal );
309 }
310
311 /*
312 * Build an address list entry and append to list of address items. Name is formatted
313 * as it appears in the common name (cn) attribute.
314 */
315 static void syldap_build_items_cn( SyldapServer *ldapServer, GSList *listName, GSList *listAddr ) {
316         ItemPerson *person;
317         ItemEMail *email;
318         GSList *nodeName = listName;
319
320         while( nodeName ) {
321                 GSList *nodeAddress = listAddr;
322                 person = addritem_create_item_person();
323                 addritem_person_set_common_name( person, nodeName->data );
324                 addrcache_id_person( ldapServer->addressCache, person );
325                 addrcache_add_person( ldapServer->addressCache, person );
326
327                 while( nodeAddress ) {
328                         email = addritem_create_item_email();
329                         addritem_email_set_address( email, nodeAddress->data );
330                         addrcache_id_email( ldapServer->addressCache, email );
331                         addrcache_person_add_email( ldapServer->addressCache, person, email );
332                         nodeAddress = g_slist_next( nodeAddress );
333                         ldapServer->entriesRead++;
334                 }
335                 nodeName = g_slist_next( nodeName );
336         }
337 }
338
339 /*
340 * Build an address list entry and append to list of address items. Name is formatted
341 * as "<first-name> <last-name>".
342 */
343 static void syldap_build_items_fl( SyldapServer *ldapServer, GSList *listAddr, GSList *listFirst, GSList *listLast  ) {
344         GSList *nodeFirst = listFirst;
345         GSList *nodeAddress = listAddr;
346         gchar *firstName = NULL, *lastName = NULL, *fullName = NULL;
347         gint iLen = 0, iLenT = 0;
348         ItemPerson *person;
349         ItemEMail *email;
350
351         /* Find longest first name in list */
352         while( nodeFirst ) {
353                 if( firstName == NULL ) {
354                         firstName = nodeFirst->data;
355                         iLen = strlen( firstName );
356                 }
357                 else {
358                         if( ( iLenT = strlen( nodeFirst->data ) ) > iLen ) {
359                                 firstName = nodeFirst->data;
360                                 iLen = iLenT;
361                         }
362                 }
363                 nodeFirst = g_slist_next( nodeFirst );
364         }
365
366         /* Format name */
367         if( listLast ) {
368                 lastName = listLast->data;
369         }
370
371         if( firstName ) {
372                 if( lastName ) {
373                         fullName = g_strdup_printf( "%s %s", firstName, lastName );
374                 }
375                 else {
376                         fullName = g_strdup_printf( "%s", firstName );
377                 }
378         }
379         else {
380                 if( lastName ) {
381                         fullName = g_strdup_printf( "%s", lastName );
382                 }
383         }
384         if( fullName ) {
385                 g_strchug( fullName ); g_strchomp( fullName );
386         }
387
388         if( nodeAddress ) {
389                 person = addritem_create_item_person();
390                 addritem_person_set_common_name( person, fullName );
391                 addritem_person_set_first_name( person, firstName );
392                 addritem_person_set_last_name( person, lastName );
393                 addrcache_id_person( ldapServer->addressCache, person );
394                 addrcache_add_person( ldapServer->addressCache, person );
395         }
396
397         /* Add address item */
398         while( nodeAddress ) {
399                 email = addritem_create_item_email();
400                 addritem_email_set_address( email, nodeAddress->data );
401                 addrcache_id_email( ldapServer->addressCache, email );
402                 addrcache_person_add_email( ldapServer->addressCache, person, email );
403                 nodeAddress = g_slist_next( nodeAddress );
404                 ldapServer->entriesRead++;
405         }
406         g_free( fullName );
407         fullName = firstName = lastName = NULL;
408
409 }
410
411 /*
412 * Add all attribute values to a list.
413 */
414 static GSList *syldap_add_list_values( LDAP *ld, LDAPMessage *entry, char *attr ) {
415         GSList *list = NULL;
416         gint i;
417         gchar **vals;
418
419         if( ( vals = ldap_get_values( ld, entry, attr ) ) != NULL ) {
420                 for( i = 0; vals[i] != NULL; i++ ) {
421                         /* printf( "lv\t%s: %s\n", attr, vals[i] ); */
422                         list = g_slist_append( list, g_strdup( vals[i] ) );
423                 }
424         }
425         ldap_value_free( vals );
426         return list;
427 }
428
429 /*
430 * Add a single attribute value to a list.
431 */
432 static GSList *syldap_add_single_value( LDAP *ld, LDAPMessage *entry, char *attr ) {
433         GSList *list = NULL;
434         gchar **vals;
435
436         if( ( vals = ldap_get_values( ld, entry, attr ) ) != NULL ) {
437                 if( vals[0] != NULL ) {
438                         /* printf( "sv\t%s: %s\n", attr, vals[0] ); */
439                         list = g_slist_append( list, g_strdup( vals[0] ) );
440                 }
441         }
442         ldap_value_free( vals );
443         return list;
444 }
445
446 /*
447 * Free linked lists of character strings.
448 */
449 static void syldap_free_lists( GSList *listName, GSList *listAddr, GSList *listID, GSList *listDN, GSList *listFirst, GSList *listLast ) {
450         mgu_free_list( listName );
451         mgu_free_list( listAddr );
452         mgu_free_list( listID );
453         mgu_free_list( listDN );
454         mgu_free_list( listFirst );
455         mgu_free_list( listLast );
456 }
457
458 /*
459 * Check parameters that are required for a search. This should
460 * be called before performing a search.
461 * Return: TRUE if search criteria appear OK.
462 */
463 gboolean syldap_check_search( SyldapServer *ldapServer ) {
464         g_return_val_if_fail( ldapServer != NULL, FALSE );
465
466         ldapServer->retVal = MGU_LDAP_CRITERIA;
467
468         /* Test search criteria */
469         if( ldapServer->searchCriteria == NULL ) {
470                 return FALSE;
471         }
472         if( strlen( ldapServer->searchCriteria ) < 1 ) {
473                 return FALSE;
474         }
475
476         if( ldapServer->searchValue == NULL ) {
477                 return FALSE;
478         }
479         if( strlen( ldapServer->searchValue ) < 1 ) {
480                 return FALSE;
481         }
482
483         ldapServer->retVal = MGU_SUCCESS;
484         return TRUE;
485 }
486
487 /*
488 * Perform the LDAP search, reading LDAP entries into cache.
489 * Note that one LDAP entry can have multiple values for many of its
490 * attributes. If these attributes are E-Mail addresses; these are
491 * broken out into separate address items. For any other attribute,
492 * only the first occurrence is read.
493 */
494 gint syldap_search( SyldapServer *ldapServer ) {
495         LDAP *ld;
496         LDAPMessage *result, *e;
497         char *attribs[10];
498         char *attribute;
499         gchar *criteria;
500         BerElement *ber;
501         gint rc;
502         GSList *listName = NULL, *listAddress = NULL, *listID = NULL;
503         GSList *listFirst = NULL, *listLast = NULL, *listDN = NULL;
504         struct timeval timeout;
505         gboolean entriesFound = FALSE;
506
507         g_return_val_if_fail( ldapServer != NULL, -1 );
508
509         ldapServer->retVal = MGU_SUCCESS;
510         if( ! syldap_check_search( ldapServer ) ) {
511                 return ldapServer->retVal;
512         }
513
514         /* Set timeout */
515         timeout.tv_sec = ldapServer->timeOut;
516         timeout.tv_usec = 0L;
517
518         ldapServer->entriesRead = 0;
519         if( ( ld = ldap_init( ldapServer->hostName, ldapServer->port ) ) == NULL ) {
520                 ldapServer->retVal = MGU_LDAP_INIT;
521                 return ldapServer->retVal;
522         }
523
524         /* printf( "connected to LDAP host %s on port %d\n", ldapServer->hostName, ldapServer->port ); */
525
526         /* Bind to the server, if required */
527         if( ldapServer->bindDN ) {
528                 if( * ldapServer->bindDN != '\0' ) {
529                         /* printf( "binding...\n" ); */
530                         rc = ldap_simple_bind_s( ld, ldapServer->bindDN, ldapServer->bindPass );
531                         /* printf( "rc=%d\n", rc ); */
532                         if( rc != LDAP_SUCCESS ) {
533                                 /* printf( "LDAP Error: ldap_simple_bind_s: %s\n", ldap_err2string( rc ) ); */
534                                 ldap_unbind( ld );
535                                 ldapServer->retVal = MGU_LDAP_BIND;
536                                 return ldapServer->retVal;
537                         }
538                 }
539         }
540
541         /* Define all attributes we are interested in. */
542         attribs[0] = SYLDAP_ATTR_DN;
543         attribs[1] = SYLDAP_ATTR_COMMONNAME;
544         attribs[2] = SYLDAP_ATTR_GIVENNAME;
545         attribs[3] = SYLDAP_ATTR_SURNAME;
546         attribs[4] = SYLDAP_ATTR_EMAIL;
547         attribs[5] = SYLDAP_ATTR_UID;
548         attribs[6] = NULL;
549
550         /* Create LDAP search string and apply search criteria */
551         criteria = g_strdup_printf( ldapServer->searchCriteria, ldapServer->searchValue );
552         rc = ldap_search_ext_s( ld, ldapServer->baseDN, LDAP_SCOPE_SUBTREE, criteria, attribs, 0, NULL, NULL,
553                        &timeout, 0, &result );
554         g_free( criteria );
555         criteria = NULL;
556         if( rc == LDAP_TIMEOUT ) {
557                 ldap_unbind( ld );
558                 ldapServer->retVal = MGU_LDAP_TIMEOUT;
559                 return ldapServer->retVal;
560         }
561         if( rc != LDAP_SUCCESS ) {
562                 /* printf( "LDAP Error: ldap_search_st: %s\n", ldap_err2string( rc ) ); */
563                 ldap_unbind( ld );
564                 ldapServer->retVal = MGU_LDAP_SEARCH;
565                 return ldapServer->retVal;
566         }
567
568         /* printf( "Total results are: %d\n", ldap_count_entries( ld, result ) ); */
569
570         /* Clear the cache if we have new entries, otherwise leave untouched. */
571         if( ldap_count_entries( ld, result ) > 0 ) {
572                 addrcache_clear( ldapServer->addressCache );
573         }
574
575         /* Process results */
576         ldapServer->entriesRead = 0;
577         for( e = ldap_first_entry( ld, result ); e != NULL; e = ldap_next_entry( ld, e ) ) {
578                 entriesFound = TRUE;
579                 if( ldapServer->entriesRead >= ldapServer->maxEntries ) break;          
580                 /* printf( "DN: %s\n", ldap_get_dn( ld, e ) ); */
581
582                 /* Process all attributes */
583                 for( attribute = ldap_first_attribute( ld, e, &ber ); attribute != NULL;
584                                attribute = ldap_next_attribute( ld, e, ber ) ) {
585                         if( strcasecmp( attribute, SYLDAP_ATTR_COMMONNAME ) == 0 ) {
586                                 listName = syldap_add_list_values( ld, e, attribute );
587                         }
588                         if( strcasecmp( attribute, SYLDAP_ATTR_EMAIL ) == 0 ) {
589                                 listAddress = syldap_add_list_values( ld, e, attribute );
590                         }
591                         if( strcasecmp( attribute, SYLDAP_ATTR_UID ) == 0 ) {
592                                 listID = syldap_add_single_value( ld, e, attribute );
593                         }
594                         if( strcasecmp( attribute, SYLDAP_ATTR_GIVENNAME ) == 0 ) {
595                                 listFirst = syldap_add_list_values( ld, e, attribute );
596                         }
597                         if( strcasecmp( attribute, SYLDAP_ATTR_SURNAME ) == 0 ) {
598                                 listLast = syldap_add_single_value( ld, e, attribute );
599                         }
600                         if( strcasecmp( attribute, SYLDAP_ATTR_DN ) == 0 ) {
601                                 listDN = syldap_add_single_value( ld, e, attribute );
602                         }
603                 }
604
605                 /* Free memory used to store attribute */
606                 ldap_memfree( attribute );
607
608                 /* Format and add items to cache */
609                 syldap_build_items_fl( ldapServer, listAddress, listFirst, listLast );
610
611                 /* Free up */
612                 syldap_free_lists( listName, listAddress, listID, listDN, listFirst, listLast );
613                 listName = listAddress = listID = listFirst = listLast = listDN = NULL;
614
615                 if( ber != NULL ) {
616                         ber_free( ber, 0 );
617                 }
618         }
619
620         syldap_free_lists( listName, listAddress, listID, listDN, listFirst, listLast );
621         listName = listAddress = listID = listFirst = listLast = listDN = NULL;
622         
623         /* Free up and disconnect */
624         ldap_msgfree( result );
625         ldap_unbind( ld );
626         ldapServer->newSearch = FALSE;
627         if( entriesFound ) {
628                 ldapServer->retVal = MGU_SUCCESS;
629         }
630         else {
631                 ldapServer->retVal = MGU_LDAP_NOENTRIES;
632         }
633         return ldapServer->retVal;
634 }
635
636 /* syldap_display_search_results() - updates the ui. this function is called from the
637  * main thread (the thread running the GTK event loop). */
638 static gint syldap_display_search_results(SyldapServer *ldapServer)
639 {
640         /* NOTE: when this function is called the accompanying thread should
641          * already be terminated. */
642         gtk_idle_remove(ldapServer->idleId);
643         ldapServer->callBack(ldapServer);
644         /* FIXME:  match should know whether to free this SyldapServer stuff. */
645         g_free(ldapServer->thread);
646         ldapServer->thread = NULL;
647         return TRUE;
648 }
649
650 /* ============================================================================================ */
651 /*
652 * Read data into list. Main entry point
653 * Return: TRUE if file read successfully.
654 */
655 /* ============================================================================================ */
656 gint syldap_read_data( SyldapServer *ldapServer ) {
657         g_return_val_if_fail( ldapServer != NULL, -1 );
658
659         ldapServer->accessFlag = FALSE;
660         pthread_detach( pthread_self() );
661         if( ldapServer->newSearch ) {
662                 /* Read data into the list */
663                 syldap_search( ldapServer );
664
665                 /* Mark cache */
666                 ldapServer->addressCache->modified = FALSE;
667                 ldapServer->addressCache->dataRead = TRUE;
668                 ldapServer->accessFlag = FALSE;
669         }
670
671         /* Callback */
672         ldapServer->busyFlag = FALSE;
673         if( ldapServer->callBack ) {
674                 /* make the ui thread update the search results */
675                 /* TODO: really necessary to call gdk_threads_XXX()??? gtk_idle_add()
676                  * should do this - could someone check the GTK sources please? */
677                 gdk_threads_enter();
678                 ldapServer->idleId = gtk_idle_add((GtkFunction)syldap_display_search_results,
679                                 ldapServer);
680                 gdk_threads_leave();
681         }
682
683         return ldapServer->retVal;
684 }
685
686 /* ============================================================================================ */
687 /*
688 * Cancel read with thread.
689 */
690 /* ============================================================================================ */
691 void syldap_cancel_read( SyldapServer *ldapServer ) {
692         g_return_if_fail( ldapServer != NULL );
693
694         /* DELETEME: this is called from inside UI thread so it's OK, Christoph! */
695         if( ldapServer->thread ) {
696                 /* printf( "thread cancelled\n" ); */
697                 pthread_cancel( *ldapServer->thread );
698         }
699         g_free(ldapServer->thread);
700         ldapServer->thread = NULL;
701         ldapServer->busyFlag = FALSE;
702 }
703
704 /* ============================================================================================ */
705 /*
706 * Read data into list using a background thread.
707 * Return: TRUE if file read successfully. Callback function will be
708 * notified when search is complete.
709 */
710 /* ============================================================================================ */
711 gint syldap_read_data_th( SyldapServer *ldapServer ) {
712         g_return_val_if_fail( ldapServer != NULL, -1 );
713
714         ldapServer->busyFlag = FALSE;
715         syldap_check_search( ldapServer );
716         if( ldapServer->retVal == MGU_SUCCESS ) {
717                 /* debug_print("Staring LDAP read thread\n"); */
718
719                 ldapServer->busyFlag = TRUE;
720                 ldapServer->thread = g_new0(pthread_t, 1);
721                 pthread_create( ldapServer->thread, NULL, (void *) syldap_read_data, (void *) ldapServer );
722         }
723         return ldapServer->retVal;
724 }
725
726 /*
727 * Return link list of persons.
728 */
729 GList *syldap_get_list_person( SyldapServer *ldapServer ) {
730         g_return_val_if_fail( ldapServer != NULL, NULL );
731         return addrcache_get_list_person( ldapServer->addressCache );
732 }
733
734 /*
735 * Return link list of folders. This is always NULL since there are
736 * no folders in GnomeCard.
737 * Return: NULL.
738 */
739 GList *syldap_get_list_folder( SyldapServer *ldapServer ) {
740         g_return_val_if_fail( ldapServer != NULL, NULL );
741         return NULL;
742 }
743
744 #define SYLDAP_TEST_FILTER   "(objectclass=*)"
745 #define SYLDAP_SEARCHBASE_V2 "cn=config"
746 #define SYLDAP_SEARCHBASE_V3 ""
747 #define SYLDAP_V2_TEST_ATTR  "database"
748 #define SYLDAP_V3_TEST_ATTR  "namingcontexts"
749
750 /*
751 * Attempt to discover the base DN for the server.
752 * Enter:
753 *       host    Host name
754 *       port    Port number
755 *       bindDN  Bind DN (optional).
756 *       bindPW  Bind PW (optional).
757 *       tov     Timeout value (seconds), or 0 for none, default 30 secs.
758 * Return: List of Base DN's, or NULL if could not read. Base DN should
759 * be g_free() when done.
760 */
761 GList *syldap_read_basedn_s( const gchar *host, const gint port, const gchar *bindDN, const gchar *bindPW, const gint tov ) {
762         GList *baseDN = NULL;
763         LDAP *ld;
764         gint rc, i;
765         LDAPMessage *result, *e;
766         gchar *attribs[10];
767         BerElement *ber;
768         gchar *attribute;
769         gchar **vals;
770         struct timeval timeout;
771
772         if( host == NULL ) return baseDN;
773         if( port < 1 ) return baseDN;
774
775         /* Set timeout */
776         timeout.tv_usec = 0L;
777         if( tov > 0 ) {
778                 timeout.tv_sec = tov;
779         }
780         else {
781                 timeout.tv_sec = 30L;
782         }
783
784         /* Connect to server. */
785         if( ( ld = ldap_init( host, port ) ) == NULL ) {
786                 return baseDN;
787         }
788
789         /* Bind to the server, if required */
790         if( bindDN ) {
791                 if( *bindDN != '\0' ) {
792                         rc = ldap_simple_bind_s( ld, bindDN, bindPW );
793                         if( rc != LDAP_SUCCESS ) {
794                                 /* printf( "LDAP Error: ldap_simple_bind_s: %s\n", ldap_err2string( rc ) ); */
795                                 ldap_unbind( ld );
796                                 return baseDN;
797                         }
798                 }
799         }
800
801         /* Test for LDAP version 3 */
802         attribs[0] = SYLDAP_V3_TEST_ATTR;
803         attribs[1] = NULL;
804         rc = ldap_search_ext_s( ld, SYLDAP_SEARCHBASE_V3, LDAP_SCOPE_BASE, SYLDAP_TEST_FILTER, attribs,
805                        0, NULL, NULL, &timeout, 0, &result );
806         if( rc == LDAP_SUCCESS ) {
807                 /* Process entries */
808                 for( e = ldap_first_entry( ld, result ); e != NULL; e = ldap_next_entry( ld, e ) ) {
809                         /* printf( "DN: %s\n", ldap_get_dn( ld, e ) ); */
810
811                         /* Process attributes */
812                         for( attribute = ldap_first_attribute( ld, e, &ber ); attribute != NULL;
813                                         attribute = ldap_next_attribute( ld, e, ber ) ) {
814                                 if( strcasecmp( attribute, SYLDAP_V3_TEST_ATTR ) == 0 ) {
815                                         if( ( vals = ldap_get_values( ld, e, attribute ) ) != NULL ) {
816                                                 for( i = 0; vals[i] != NULL; i++ ) {
817                                                         /* printf( "\t%s: %s\n", attribute, vals[i] ); */
818                                                         baseDN = g_list_append( baseDN, g_strdup( vals[i] ) );
819                                                 }
820                                         }
821                                         ldap_value_free( vals );
822                                 }
823                         }
824                         ldap_memfree( attribute );
825                         if( ber != NULL ) {
826                                 ber_free( ber, 0 );
827                         }
828                 }
829                 ldap_msgfree( result );
830         }
831         else {
832         }
833
834         if( baseDN == NULL ) {
835                 /* Test for LDAP version 2 */
836                 attribs[0] = NULL;
837                 rc = ldap_search_ext_s( ld, SYLDAP_SEARCHBASE_V2, LDAP_SCOPE_BASE, SYLDAP_TEST_FILTER, attribs,
838                                0, NULL, NULL, &timeout, 0, &result );
839                 if( rc == LDAP_SUCCESS ) {
840                         /* Process entries */
841                         for( e = ldap_first_entry( ld, result ); e != NULL; e = ldap_next_entry( ld, e ) ) {
842                                 /* if( baseDN ) break;                   */
843                                 /* printf( "DN: %s\n", ldap_get_dn( ld, e ) ); */
844
845                                 /* Process attributes */
846                                 for( attribute = ldap_first_attribute( ld, e, &ber ); attribute != NULL;
847                                                attribute = ldap_next_attribute( ld, e, ber ) ) {
848                                         /* if( baseDN ) break;                   */
849                                         if( strcasecmp( attribute, SYLDAP_V2_TEST_ATTR ) == 0 ) {
850                                                 if( ( vals = ldap_get_values( ld, e, attribute ) ) != NULL ) {
851                                                         for( i = 0; vals[i] != NULL; i++ ) {
852                                                                 char *ch;
853                                                                 /* Strip the 'ldb:' from the front of the value */
854                                                                 ch = ( char * ) strchr( vals[i], ':' );
855                                                                 if( ch ) {
856                                                                         gchar *bn = g_strdup( ++ch );
857                                                                         g_strchomp( bn );
858                                                                         g_strchug( bn );
859                                                                         baseDN = g_list_append( baseDN, g_strdup( bn ) );
860                                                                 }
861                                                         }
862                                                 }
863                                                 ldap_value_free( vals );
864                                         }
865                                 }
866                                 ldap_memfree( attribute );
867                                 if( ber != NULL ) {
868                                         ber_free( ber, 0 );
869                                 }
870                         }
871                         ldap_msgfree( result );
872                 }
873         }
874         ldap_unbind( ld );
875         return baseDN;
876 }
877
878 /*
879 * Attempt to discover the base DN for the server.
880 * Enter:  ldapServer Server to test.
881 * Return: List of Base DN's, or NULL if could not read. Base DN should
882 * be g_free() when done. Return code set in ldapServer.
883 */
884 GList *syldap_read_basedn( SyldapServer *ldapServer ) {
885         GList *baseDN = NULL;
886         LDAP *ld;
887         gint rc, i;
888         LDAPMessage *result, *e;
889         gchar *attribs[10];
890         BerElement *ber;
891         gchar *attribute;
892         gchar **vals;
893         struct timeval timeout;
894
895         ldapServer->retVal = MGU_BAD_ARGS;
896         if( ldapServer == NULL ) return baseDN;
897         if( ldapServer->hostName == NULL ) return baseDN;
898         if( ldapServer->port < 1 ) return baseDN;
899
900         /* Set timeout */
901         timeout.tv_usec = 0L;
902         if( ldapServer->timeOut > 0 ) {
903                 timeout.tv_sec = ldapServer->timeOut;
904         }
905         else {
906                 timeout.tv_sec = 30L;
907         }
908
909         /* Connect to server. */
910         if( ( ld = ldap_init( ldapServer->hostName, ldapServer->port ) ) == NULL ) {
911                 ldapServer->retVal = MGU_LDAP_INIT;
912                 return baseDN;
913         }
914
915         /* Bind to the server, if required */
916         if( ldapServer->bindDN ) {
917                 if( *ldapServer->bindDN != '\0' ) {
918                         rc = ldap_simple_bind_s( ld, ldapServer->bindDN, ldapServer->bindPass );
919                         if( rc != LDAP_SUCCESS ) {
920                                 /* printf( "LDAP Error: ldap_simple_bind_s: %s\n", ldap_err2string( rc ) ); */
921                                 ldap_unbind( ld );
922                                 ldapServer->retVal = MGU_LDAP_BIND;
923                                 return baseDN;
924                         }
925                 }
926         }
927
928         ldapServer->retVal = MGU_LDAP_SEARCH;
929
930         /* Test for LDAP version 3 */
931         attribs[0] = SYLDAP_V3_TEST_ATTR;
932         attribs[1] = NULL;
933         rc = ldap_search_ext_s( ld, SYLDAP_SEARCHBASE_V3, LDAP_SCOPE_BASE, SYLDAP_TEST_FILTER, attribs,
934                        0, NULL, NULL, &timeout, 0, &result );
935         if( rc == LDAP_SUCCESS ) {
936                 /* Process entries */
937                 for( e = ldap_first_entry( ld, result ); e != NULL; e = ldap_next_entry( ld, e ) ) {
938                         /* printf( "DN: %s\n", ldap_get_dn( ld, e ) ); */
939
940                         /* Process attributes */
941                         for( attribute = ldap_first_attribute( ld, e, &ber ); attribute != NULL;
942                                         attribute = ldap_next_attribute( ld, e, ber ) ) {
943                                 if( strcasecmp( attribute, SYLDAP_V3_TEST_ATTR ) == 0 ) {
944                                         if( ( vals = ldap_get_values( ld, e, attribute ) ) != NULL ) {
945                                                 for( i = 0; vals[i] != NULL; i++ ) {
946                                                         /* printf( "\t%s: %s\n", attribute, vals[i] ); */
947                                                         baseDN = g_list_append( baseDN, g_strdup( vals[i] ) );
948                                                 }
949                                         }
950                                         ldap_value_free( vals );
951                                 }
952                         }
953                         ldap_memfree( attribute );
954                         if( ber != NULL ) {
955                                 ber_free( ber, 0 );
956                         }
957                 }
958                 ldap_msgfree( result );
959                 ldapServer->retVal = MGU_SUCCESS;
960         }
961         else if( rc == LDAP_TIMEOUT ) {
962                 ldapServer->retVal = MGU_LDAP_TIMEOUT;
963         }
964
965         if( baseDN == NULL ) {
966                 /* Test for LDAP version 2 */
967                 attribs[0] = NULL;
968                 rc = ldap_search_ext_s( ld, SYLDAP_SEARCHBASE_V2, LDAP_SCOPE_BASE, SYLDAP_TEST_FILTER, attribs,
969                                0, NULL, NULL, &timeout, 0, &result );
970                 if( rc == LDAP_SUCCESS ) {
971                         /* Process entries */
972                         for( e = ldap_first_entry( ld, result ); e != NULL; e = ldap_next_entry( ld, e ) ) {
973                                 /* if( baseDN ) break;                   */
974                                 /* printf( "DN: %s\n", ldap_get_dn( ld, e ) ); */
975
976                                 /* Process attributes */
977                                 for( attribute = ldap_first_attribute( ld, e, &ber ); attribute != NULL;
978                                                attribute = ldap_next_attribute( ld, e, ber ) ) {
979                                         /* if( baseDN ) break;                   */
980                                         if( strcasecmp( attribute, SYLDAP_V2_TEST_ATTR ) == 0 ) {
981                                                 if( ( vals = ldap_get_values( ld, e, attribute ) ) != NULL ) {
982                                                         for( i = 0; vals[i] != NULL; i++ ) {
983                                                                 char *ch;
984                                                                 /* Strip the 'ldb:' from the front of the value */
985                                                                 ch = ( char * ) strchr( vals[i], ':' );
986                                                                 if( ch ) {
987                                                                         gchar *bn = g_strdup( ++ch );
988                                                                         g_strchomp( bn );
989                                                                         g_strchug( bn );
990                                                                         baseDN = g_list_append( baseDN, g_strdup( bn ) );
991                                                                 }
992                                                         }
993                                                 }
994                                                 ldap_value_free( vals );
995                                         }
996                                 }
997                                 ldap_memfree( attribute );
998                                 if( ber != NULL ) {
999                                         ber_free( ber, 0 );
1000                                 }
1001                         }
1002                         ldap_msgfree( result );
1003                         ldapServer->retVal = MGU_SUCCESS;
1004                 }
1005                 else if( rc == LDAP_TIMEOUT ) {
1006                         ldapServer->retVal = MGU_LDAP_TIMEOUT;
1007                 }
1008         }
1009         ldap_unbind( ld );
1010
1011         return baseDN;
1012 }
1013
1014 /*
1015 * Attempt to connect to the server.
1016 * Enter:
1017 *       host    Host name
1018 *       port    Port number
1019 * Return: TRUE if connected successfully.
1020 */
1021 gboolean syldap_test_connect_s( const gchar *host, const gint port ) {
1022         gboolean retVal = FALSE;
1023         LDAP *ld;
1024
1025         if( host == NULL ) return retVal;
1026         if( port < 1 ) return retVal;
1027         if( ( ld = ldap_open( host, port ) ) != NULL ) {
1028                 retVal = TRUE;
1029         }
1030         if( ld != NULL ) {
1031                 ldap_unbind( ld );
1032         }
1033         return retVal;
1034 }
1035
1036 /*
1037 * Attempt to connect to the server.
1038 * Enter:  ldapServer Server to test.
1039 * Return: TRUE if connected successfully. Return code set in ldapServer.
1040 */
1041 gboolean syldap_test_connect( SyldapServer *ldapServer ) {
1042         gboolean retVal = FALSE;
1043         LDAP *ld;
1044
1045         ldapServer->retVal = MGU_BAD_ARGS;
1046         if( ldapServer == NULL ) return retVal;
1047         if( ldapServer->hostName == NULL ) return retVal;
1048         if( ldapServer->port < 1 ) return retVal;
1049         ldapServer->retVal = MGU_LDAP_INIT;
1050         if( ( ld = ldap_open( ldapServer->hostName, ldapServer->port ) ) != NULL ) {
1051                 ldapServer->retVal = MGU_SUCCESS;
1052                 retVal = TRUE;
1053         }
1054         if( ld != NULL ) {
1055                 ldap_unbind( ld );
1056         }
1057         return retVal;
1058 }
1059
1060 /*
1061 * Test whether LDAP libraries installed.
1062 * Return: TRUE if library available.
1063 */
1064 gboolean syldap_test_ldap_lib() {
1065         return TRUE;
1066 }
1067
1068 #endif  /* USE_LDAP */
1069
1070 /*
1071 * End of Source.
1072 */