2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 2003-2018 Match Grun and the Claws Mail team
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 3 of the License, or
8 * (at your option) any later version.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * Functions necessary to define and perform LDAP queries.
25 #include "claws-features.h"
31 #include <glib/gi18n.h>
37 #include "ldapquery.h"
39 #include "ldapserver.h"
41 #include "file-utils.h"
44 #include "addrcache.h"
45 #include "common/utils.h"
49 * Key for thread specific data.
51 static pthread_key_t _queryThreadKey_
;
52 static gboolean _queryThreadInit_
= FALSE
;
54 static gboolean
callbackend (gpointer data
)
56 LdapQuery
*qry
= (LdapQuery
*)data
;
57 qry
->callBackEnd( qry
, ADDRQUERY_ID(qry
), ADDRQUERY_RETVAL(qry
), qry
->data
);
63 * Create new LDAP query object.
64 * \return Initialized query object.
66 LdapQuery
*ldapqry_create( void ) {
69 qry
= g_new0( LdapQuery
, 1 );
70 ADDRQUERY_TYPE(qry
) = ADDRQUERY_LDAP
;
71 ADDRQUERY_ID(qry
) = 0;
72 ADDRQUERY_SEARCHTYPE(qry
) = ADDRSEARCH_NONE
;
73 ADDRQUERY_NAME(qry
) = NULL
;
74 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
75 ADDRQUERY_FOLDER(qry
) = NULL
;
76 ADDRQUERY_SEARCHVALUE(qry
) = NULL
;
81 qry
->stopFlag
= FALSE
;
82 qry
->busyFlag
= FALSE
;
83 qry
->agedFlag
= FALSE
;
84 qry
->completed
= FALSE
;
86 qry
->callBackEntry
= NULL
;
87 qry
->callBackEnd
= NULL
;
91 /* Mutex to protect stop and busy flags */
92 qry
->mutexStop
= g_malloc0( sizeof( pthread_mutex_t
) );
93 pthread_mutex_init( qry
->mutexStop
, NULL
);
94 qry
->mutexBusy
= g_malloc0( sizeof( pthread_mutex_t
) );
95 pthread_mutex_init( qry
->mutexBusy
, NULL
);
97 /* Mutex to protect critical section */
98 qry
->mutexEntry
= g_malloc0( sizeof( pthread_mutex_t
) );
99 pthread_mutex_init( qry
->mutexEntry
, NULL
);
105 * Specify the reference to control data that will be used for the query. The calling
106 * module should be responsible for creating and destroying this control object.
107 * \param qry Query object.
108 * \param ctl Control object.
110 void ldapqry_set_control( LdapQuery
*qry
, LdapControl
*ctl
) {
111 cm_return_if_fail( qry
!= NULL
);
116 * Specify query name to be used.
117 * \param qry Query object.
120 void ldapqry_set_name( LdapQuery
* qry
, const gchar
*value
) {
121 cm_return_if_fail( qry
!= NULL
);
122 ADDRQUERY_NAME(qry
) = mgu_replace_string( ADDRQUERY_NAME(qry
), value
);
123 if (ADDRQUERY_NAME(qry
) == NULL
)
125 g_strstrip( ADDRQUERY_NAME(qry
) );
126 debug_print("set name: %s\n", ADDRQUERY_NAME(qry
));
130 * Specify search value to be used.
131 * \param qry Query object.
134 void ldapqry_set_search_value( LdapQuery
*qry
, const gchar
*value
) {
135 cm_return_if_fail( qry
!= NULL
);
136 ADDRQUERY_SEARCHVALUE(qry
) = mgu_replace_string( ADDRQUERY_SEARCHVALUE(qry
), value
);
137 if (ADDRQUERY_SEARCHVALUE(qry
) == NULL
)
139 g_strstrip( ADDRQUERY_SEARCHVALUE(qry
) );
140 debug_print("search value: %s\n", ADDRQUERY_SEARCHVALUE(qry
));
144 * Specify query type.
145 * \param qry Query object.
146 * \param value Query type, either:
148 * <li><code>LDAPQUERY_NONE</code></li>
149 * <li><code>LDAPQUERY_STATIC</code></li>
150 * <li><code>LDAPQUERY_DYNAMIC</code></li>
154 void ldapqry_set_query_type( LdapQuery* qry, const gint value ) {
155 ADDRQUERY_TYPE(qry) = value;
160 * Specify search type.
161 * \param qry Query object.
164 void ldapqry_set_search_type( LdapQuery
*qry
, const AddrSearchType value
) {
165 cm_return_if_fail( qry
!= NULL
);
166 ADDRQUERY_SEARCHTYPE(qry
) = value
;
171 * \param qry Query object.
172 * \param value ID for the query.
174 void ldapqry_set_query_id( LdapQuery
* qry
, const gint value
) {
175 cm_return_if_fail( qry
!= NULL
);
176 ADDRQUERY_ID(qry
) = value
;
180 * Register a callback function that will be executed when each entry
181 * has been read and processed. When called, the function will be passed
182 * this query object and a GList of ItemEMail objects as arguments. An
183 * example of typical usage is shown below.
186 * ------------------------------------------------------------
187 * void myCallbackEntry( LdapQuery *qry, GList *listEMail ) {
192 * ItemEMail *email = node->data;
193 * ... process email object ...
194 * node = g_list_next( node );
196 * g_list_free( listEMail );
200 * ldapqry_set_callback_entry( qry, myCallbackEntry );
201 * ------------------------------------------------------------
204 * \param qry Query object.
205 * \param func Function.
207 void ldapqry_set_callback_entry( LdapQuery
*qry
, void *func
) {
208 pthread_mutex_lock( qry
->mutexEntry
);
209 qry
->callBackEntry
= func
;
210 pthread_mutex_unlock( qry
->mutexEntry
);
214 * Register a callback function that will be executed when the search
215 * is complete. When called, the function will be passed this query
216 * object as an argument.
217 * \param qry Query object.
218 * \param func Function.
220 void ldapqry_set_callback_end( LdapQuery
*qry
, void *func
) {
221 qry
->callBackEnd
= func
;
225 * Notify query to start/stop executing. This method should be called with a
226 * value if <i>TRUE</i> to terminate an existing running query.
228 * \param qry Query object.
229 * \param value Value of stop flag.
231 void ldapqry_set_stop_flag( LdapQuery
*qry
, const gboolean value
) {
232 cm_return_if_fail( qry
!= NULL
);
234 pthread_mutex_lock( qry
->mutexStop
);
235 qry
->stopFlag
= value
;
236 pthread_mutex_unlock( qry
->mutexStop
);
240 * Test value of stop flag. This method should be used to determine whether a
241 * query has stopped running.
242 * \param qry Query object.
243 * \return Value of stop flag.
245 static gboolean
ldapqry_get_stop_flag( LdapQuery
*qry
) {
247 cm_return_val_if_fail( qry
!= NULL
, TRUE
);
249 pthread_mutex_lock( qry
->mutexStop
);
250 value
= qry
->stopFlag
;
251 pthread_mutex_unlock( qry
->mutexStop
);
257 * \param qry Query object.
258 * \param value Value of busy flag.
260 static void ldapqry_set_busy_flag( LdapQuery
*qry
, const gboolean value
) {
261 cm_return_if_fail( qry
!= NULL
);
262 if (qry
->mutexBusy
== NULL
)
263 return; /* exiting, mutex already freed */
265 pthread_mutex_lock( qry
->mutexBusy
);
266 qry
->busyFlag
= value
;
267 pthread_mutex_unlock( qry
->mutexBusy
);
271 * Test value of busy flag. This method will return a value of <i>FALSE</i>
272 * when a query has completed running.
273 * \param qry Query object.
274 * \return Value of busy flag.
276 static gboolean
ldapqry_get_busy_flag( LdapQuery
*qry
) {
278 cm_return_val_if_fail( qry
!= NULL
, FALSE
);
280 pthread_mutex_lock( qry
->mutexBusy
);
281 value
= qry
->busyFlag
;
282 pthread_mutex_unlock( qry
->mutexBusy
);
287 * Set query aged flag.
288 * \param qry Query object.
289 * \param value Value of aged flag.
291 static void ldapqry_set_aged_flag( LdapQuery
*qry
, const gboolean value
) {
292 cm_return_if_fail( qry
!= NULL
);
293 qry
->agedFlag
= value
;
297 * Clear LDAP query member variables.
298 * \param qry Query object.
300 static void ldapqry_clear( LdapQuery
*qry
) {
301 cm_return_if_fail( qry
!= NULL
);
303 /* Free internal stuff */
304 g_free( ADDRQUERY_NAME(qry
) );
305 g_free( ADDRQUERY_SEARCHVALUE(qry
) );
307 /* Clear pointers and value */
308 ADDRQUERY_NAME(qry
) = NULL
;
309 ADDRQUERY_SEARCHVALUE(qry
) = NULL
;
310 ADDRQUERY_ID(qry
) = 0;
311 ADDRQUERY_SEARCHTYPE(qry
) = ADDRSEARCH_NONE
;
312 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
313 qry
->entriesRead
= 0;
314 qry
->elapsedTime
= 0;
315 qry
->stopFlag
= FALSE
;
316 qry
->busyFlag
= FALSE
;
317 qry
->agedFlag
= FALSE
;
318 qry
->completed
= FALSE
;
319 qry
->callBackEntry
= NULL
;
320 qry
->callBackEnd
= NULL
;
326 * Free up LDAP query object by releasing internal memory. Note that
327 * the thread object will be freed by the OS.
328 * \param qry Query object to process.
330 void ldapqry_free( LdapQuery
*qry
) {
331 cm_return_if_fail( qry
!= NULL
);
333 /* Clear out internal members */
334 ADDRQUERY_TYPE(qry
) = ADDRQUERY_NONE
;
335 ldapqry_clear( qry
);
338 pthread_mutex_destroy( qry
->mutexStop
);
339 pthread_mutex_destroy( qry
->mutexBusy
);
340 pthread_mutex_destroy( qry
->mutexEntry
);
341 g_free( qry
->mutexStop
);
342 g_free( qry
->mutexBusy
);
343 g_free( qry
->mutexEntry
);
344 qry
->mutexEntry
= NULL
;
345 qry
->mutexBusy
= NULL
;
346 qry
->mutexStop
= NULL
;
348 /* Do not free folder - parent server object should free */
349 ADDRQUERY_FOLDER(qry
) = NULL
;
351 /* Do not free thread - thread should be terminated before freeing */
354 /* Do not free LDAP control - should be destroyed before freeing */
357 /* Now release object */
362 * Free linked lists of character strings.
363 * \param listName List of common names.
364 * \param listAddr List of addresses.
365 * \param listFirst List of first names.
366 * \param listLast List of last names.
368 static void ldapqry_free_lists(
369 GSList
*listName
, GSList
*listAddr
, GSList
*listFirst
,
370 GSList
*listLast
, GSList
*listDisplay
, GSList
*other_attrs
)
372 GSList
*cur
= other_attrs
;
373 g_slist_free_full( listName
, g_free
);
374 g_slist_free_full( listAddr
, g_free
);
375 g_slist_free_full( listFirst
, g_free
);
376 g_slist_free_full( listLast
, g_free
);
377 g_slist_free_full( listDisplay
, g_free
);
378 for(;cur
; cur
= cur
->next
)
379 addritem_free_attribute((UserAttribute
*)cur
->data
);
380 g_slist_free(other_attrs
);
384 * Add all LDAP attribute values to a list.
385 * \param ld LDAP handle.
386 * \param entry LDAP entry to process.
387 * \param attr LDAP attribute.
388 * \return List of values.
390 static GSList
*ldapqry_add_list_values(
391 LDAP
*ld
, LDAPMessage
*entry
, char *attr
)
395 struct berval
**vals
;
397 if( ( vals
= ldap_get_values_len( ld
, entry
, attr
) ) != NULL
) {
398 for( i
= 0; vals
[i
] != NULL
; i
++ ) {
399 /*debug_print("lv\t%s: %s\n", attr?attr:"null",
400 vals[i]->bv_val?vals[i]->bv_val:"null");*/
401 list
= g_slist_append( list
, g_strndup( vals
[i
]->bv_val
, vals
[i
]->bv_len
) );
404 ldap_value_free_len( vals
);
409 * Add a single attribute value to a list.
410 * \param ld LDAP handle.
411 * \param entry LDAP entry to process.
412 * \param attr LDAP attribute name to process.
413 * \return List of values; only one value will be present.
415 static GSList
*ldapqry_add_single_value( LDAP
*ld
, LDAPMessage
*entry
, char *attr
) {
417 struct berval
**vals
;
419 if( ( vals
= ldap_get_values_len( ld
, entry
, attr
) ) != NULL
) {
420 if( vals
[0] != NULL
) {
421 if (strcmp(attr
, "jpegPhoto")) {
422 debug_print("sv\t%s: %s\n", attr
?attr
:"null",
423 vals
[0]->bv_val
?vals
[0]->bv_val
:"null");
424 list
= g_slist_append( list
, g_strndup( vals
[0]->bv_val
, vals
[0]->bv_len
));
426 char *file
= get_tmp_file();
427 FILE *fp
= claws_fopen(file
, "wb");
429 claws_fwrite(vals
[0]->bv_val
, 1, vals
[0]->bv_len
, fp
);
430 claws_safe_fclose(fp
);
432 list
= g_slist_append( list
, file
);
436 ldap_value_free_len( vals
);
441 * Build an address list entry and append to list of address items. Name is formatted
442 * as "<first-name> <last-name>".
444 * \param cache Address cache to load.
445 * \param qry Query object to process.
446 * \param dn DN for entry found on server.
447 * \param listName List of common names for entry; see notes below.
448 * \param listAddr List of EMail addresses for entry.
449 * \param listFirst List of first names for entry.
450 * \param listLast List of last names for entry.
452 * \return List of ItemEMail objects.
455 * 1) Each LDAP server entry may have multiple LDAP attributes with the same
456 * name. For example, a single entry for a person may have more than one
457 * common name, email address, etc.
459 * 2) The DN for the entry is unique for the server.
461 static GList
*ldapqry_build_items_fl(
462 AddressCache
*cache
, LdapQuery
*qry
, gchar
*dn
,
463 GSList
*listName
, GSList
*listAddr
, GSList
*listFirst
,
464 GSList
*listLast
, GSList
*listDisplay
, GSList
*attributes
)
466 GSList
*nodeAddress
, *cur
;
467 gchar
*firstName
= NULL
, *lastName
= NULL
, *fullName
= NULL
;
468 gboolean allocated
= FALSE
;
472 gchar
*picfile
= NULL
;
473 GList
*listReturn
= NULL
;
475 folder
= ADDRQUERY_FOLDER(qry
);
476 if( folder
== NULL
) return listReturn
;
477 if( listAddr
== NULL
) return listReturn
;
481 fullName
= listDisplay
->data
;
484 /* Find longest first name in list */
485 firstName
= mgu_slist_longest_entry( listFirst
);
487 /* Format last name */
489 lastName
= listLast
->data
;
492 if ( fullName
== NULL
) {
493 /* Find longest common name */
495 fullName
= mgu_slist_longest_entry( listName
);
496 if( fullName
== NULL
) {
497 /* Format a full name from first and last names */
500 fullName
= g_strdup_printf( "%s %s", firstName
, lastName
);
503 fullName
= g_strdup_printf( "%s", firstName
);
508 fullName
= g_strdup_printf( "%s", lastName
);
512 g_strstrip( fullName
);
518 /* Add person into folder */
519 person
= addritem_create_item_person();
520 addritem_person_set_common_name( person
, fullName
);
521 addritem_person_set_first_name( person
, firstName
);
522 addritem_person_set_last_name( person
, lastName
);
523 addritem_person_set_nick_name( person
, fullName
);
524 addrcache_id_person( cache
, person
);
525 addritem_person_set_external_id( person
, dn
);
527 for (cur
= attributes
; cur
; cur
= cur
->next
) {
528 UserAttribute
*attrib
= addritem_copy_attribute((UserAttribute
*)cur
->data
);
529 if (attrib
->name
&& strcmp(attrib
->name
, "jpegPhoto")) {
530 addritem_person_add_attribute( person
, attrib
);
532 if (qry
->server
&& qry
->server
->control
) {
533 gchar
*dir
= g_strconcat( get_rc_dir(), G_DIR_SEPARATOR_S
,
534 ADDRBOOK_DIR
, G_DIR_SEPARATOR_S
, NULL
);
535 gchar
*filename
= g_strdup_printf("%s-%s-%s",
536 qry
->server
->control
->hostName
?qry
->server
->control
->hostName
:"nohost",
537 qry
->server
->control
->baseDN
?qry
->server
->control
->baseDN
:"nobase",
539 picfile
= g_strdup_printf("%s%s.png", dir
, filename
);
540 addritem_person_set_picture( person
, filename
);
541 rename_force(attrib
->value
, picfile
);
549 addrcache_folder_add_person( cache
, ADDRQUERY_FOLDER(qry
), person
);
553 /* Add each address item */
554 nodeAddress
= listAddr
;
555 while( nodeAddress
) {
556 email
= addritem_create_item_email();
557 addritem_email_set_address( email
, nodeAddress
->data
);
558 addrcache_id_email( cache
, email
);
559 addrcache_person_add_email( cache
, person
, email
);
560 addritem_person_add_email( person
, email
);
561 /*if (debug_get_mode()) {
562 addritem_print_item_email(email, stdout);
564 listReturn
= g_list_append( listReturn
, email
);
565 nodeAddress
= g_slist_next( nodeAddress
);
568 /* Free any allocated memory */
572 fullName
= firstName
= lastName
= NULL
;
578 * Process a single search entry.
579 * \param cache Address cache to load.
580 * \param qry Query object to process.
581 * \param ld LDAP handle.
582 * \param e LDAP message.
583 * \return List of EMail objects found.
585 static GList
*ldapqry_process_single_entry(
586 AddressCache
*cache
, LdapQuery
*qry
, LDAP
*ld
, LDAPMessage
*e
)
592 GSList
*listName
= NULL
, *listAddress
= NULL
;
593 GSList
*listFirst
= NULL
, *listLast
= NULL
;
594 GSList
*listDisplay
= NULL
;
595 GSList
*other_attrs
= NULL
;
600 dnEntry
= ldap_get_dn( ld
, e
);
601 debug_print( "DN: %s\n", dnEntry
?dnEntry
:"null" );
603 /* Process all attributes */
604 for( attribute
= ldap_first_attribute( ld
, e
, &ber
); attribute
!= NULL
;
605 attribute
= ldap_next_attribute( ld
, e
, ber
) ) {
606 if( strcasecmp( attribute
, ctl
->attribEMail
) == 0 ) {
607 listAddress
= ldapqry_add_list_values( ld
, e
, attribute
);
609 else if( strcasecmp( attribute
, ctl
->attribCName
) == 0 ) {
610 listName
= ldapqry_add_list_values( ld
, e
, attribute
);
612 else if( strcasecmp( attribute
, ctl
->attribFName
) == 0 ) {
613 listFirst
= ldapqry_add_list_values( ld
, e
, attribute
);
615 else if( strcasecmp( attribute
, ctl
->attribLName
) == 0 ) {
616 listLast
= ldapqry_add_single_value( ld
, e
, attribute
);
617 } else if( strcasecmp( attribute
, ctl
->attribDName
) == 0 ) {
618 listDisplay
= ldapqry_add_single_value( ld
, e
, attribute
);
620 GSList
*attlist
= ldapqry_add_single_value( ld
, e
, attribute
);
621 UserAttribute
*attrib
= addritem_create_attribute();
622 const gchar
*attvalue
= attlist
?((gchar
*)attlist
->data
):NULL
;
624 addritem_attrib_set_name( attrib
, attribute
);
625 addritem_attrib_set_value( attrib
, attvalue
);
626 other_attrs
= g_slist_prepend(other_attrs
, attrib
);
628 g_slist_free_full(attlist
, g_free
);
630 /* Free memory used to store attribute */
631 ldap_memfree( attribute
);
634 /* Format and add items to cache */
635 listReturn
= ldapqry_build_items_fl(
636 cache
, qry
, dnEntry
, listName
, listAddress
, listFirst
, listLast
, listDisplay
, other_attrs
);
639 ldapqry_free_lists( listName
, listAddress
, listFirst
, listLast
, listDisplay
, other_attrs
);
640 listName
= listAddress
= listFirst
= listLast
= listDisplay
= other_attrs
= NULL
;
645 ldap_memfree( dnEntry
);
651 * Check parameters that are required for a search. This should
652 * be called before performing a search.
653 * \param qry Query object to process.
654 * \return <i>TRUE</i> if search criteria appear OK.
656 gboolean
ldapqry_check_search( LdapQuery
*qry
) {
658 ADDRQUERY_RETVAL(qry
) = LDAPRC_CRITERIA
;
660 /* Test for control data */
666 /* Test for search value */
667 if( ADDRQUERY_SEARCHVALUE(qry
) == NULL
) {
670 if( strlen( ADDRQUERY_SEARCHVALUE(qry
) ) < 1 ) {
673 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
678 * Touch the query. This nudges the touch time with the current time.
679 * \param qry Query object to process.
681 void ldapqry_touch( LdapQuery
*qry
) {
682 qry
->touchTime
= time( NULL
);
683 qry
->agedFlag
= FALSE
;
687 * Connect to LDAP server.
688 * \param qry Query object to process.
689 * \return Error/status code.
691 static gint
ldapqry_connect( LdapQuery
*qry
) {
695 /* Initialize connection */
696 if (debug_get_mode()) {
697 debug_print("===ldapqry_connect===\n");
698 /*ldapqry_print(qry, stdout);*/
701 /*if (debug_get_mode()) {
702 ldapctl_print(ctl, stdout);
703 debug_print("======\n");
705 ldapqry_touch( qry
);
706 qry
->startTime
= qry
->touchTime
;
707 qry
->elapsedTime
= -1;
708 ADDRQUERY_RETVAL(qry
) = LDAPRC_INIT
;
710 ld
= ldapsvr_connect(ctl
);
713 return ADDRQUERY_RETVAL(qry
);
716 ADDRQUERY_RETVAL(qry
) = LDAPRC_STOP_FLAG
;
717 if( ldapqry_get_stop_flag( qry
) ) {
718 return ADDRQUERY_RETVAL(qry
);
720 ldapqry_touch( qry
);
722 debug_print("connected to LDAP host %s on port %d\n",
723 ctl
->hostName
?ctl
->hostName
:"null", ctl
->port
);
725 ADDRQUERY_RETVAL(qry
) = LDAPRC_STOP_FLAG
;
726 if( ldapqry_get_stop_flag( qry
) ) {
727 return ADDRQUERY_RETVAL(qry
);
729 ldapqry_touch( qry
);
731 ADDRQUERY_RETVAL(qry
) = LDAP_SUCCESS
;
733 return ADDRQUERY_RETVAL(qry
);
737 * Connect to LDAP server.
738 * \param qry Query object to process.
739 * \return Error/status code.
741 static gint
ldapqry_disconnect( LdapQuery
*qry
) {
745 rc
= ldap_unbind_ext( qry
->ldap
, NULL
, NULL
);
746 if (rc
!= LDAP_SUCCESS
) {
747 log_error(LOG_PROTOCOL
, _("LDAP error (unbind): %d (%s)\n"),
748 rc
, ldaputil_get_error(qry
->ldap
));
750 log_print(LOG_PROTOCOL
, _("LDAP (unbind): successful\n"));
755 ldapqry_touch( qry
);
756 qry
->elapsedTime
= qry
->touchTime
- qry
->startTime
;
758 return ADDRQUERY_RETVAL(qry
);
762 * Perform the LDAP search, reading LDAP entries into cache.
763 * Note that one LDAP entry can have multiple values for many of its
764 * attributes. If these attributes are E-Mail addresses; these are
765 * broken out into separate address items. For any other attribute,
766 * only the first occurrence is read.
768 * \param qry Query object to process.
769 * \return Error/status code.
771 static gint
ldapqry_search_retrieve( LdapQuery
*qry
) {
774 LDAPMessage
*result
= NULL
, *e
= NULL
;
778 gboolean entriesFound
;
780 struct timeval timeout
;
785 /* Initialize some variables */
788 cache
= qry
->server
->addressCache
;
789 timeout
.tv_sec
= ctl
->timeOut
;
790 timeout
.tv_usec
= 0L;
791 entriesFound
= FALSE
;
792 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
794 /* Define all attributes we are interested in. */
795 attribs
= ldapctl_full_attribute_array( ctl
);
797 /* Create LDAP search string */
798 criteria
= ldapctl_format_criteria( ctl
, ADDRQUERY_SEARCHVALUE(qry
) );
799 debug_print("Search criteria ::%s::\n", criteria
?criteria
:"null");
802 * Execute the search - this step may take some time to complete
803 * depending on network traffic and server response time.
805 ADDRQUERY_RETVAL(qry
) = LDAPRC_TIMEOUT
;
806 rc
= ldap_search_ext_s( ld
, ctl
->baseDN
, LDAP_SCOPE_SUBTREE
, criteria
,
807 attribs
, 0, NULL
, NULL
, &timeout
, 0, &result
);
808 debug_print("LDAP ldap_search_ext_s: %d (%s)\n", rc
, ldaputil_get_error(ld
));
809 ldapctl_free_attribute_array( attribs
);
812 if( rc
== LDAP_TIMEOUT
) {
813 log_warning(LOG_PROTOCOL
, _("LDAP (search): timeout\n"));
814 return ADDRQUERY_RETVAL(qry
);
816 ADDRQUERY_RETVAL(qry
) = LDAPRC_SEARCH
;
818 /* Test valid returns */
820 if( rc
== LDAP_ADMINLIMIT_EXCEEDED
) {
821 log_warning(LOG_PROTOCOL
, _("LDAP (search): server limits exceeded\n"));
824 else if( rc
== LDAP_SUCCESS
) {
825 log_print(LOG_PROTOCOL
, _("LDAP (search): successful\n"));
828 else if( rc
== LDAP_PARTIAL_RESULTS
|| (result
&& ldap_count_entries(ld
, result
) > 0) ) {
829 log_print(LOG_PROTOCOL
, _("LDAP (search): successful (partial results)\n"));
833 log_error(LOG_PROTOCOL
, _("LDAP error (search): %d (%s)\n"), rc
, ldaputil_get_error(ld
));
834 return ADDRQUERY_RETVAL(qry
);
836 ADDRQUERY_RETVAL(qry
) = LDAPRC_STOP_FLAG
;
839 debug_print("Total results are: %lu\n", ldap_count_entries(ld
, result
));
841 debug_print("Total results are: %d\n", ldap_count_entries(ld
, result
));
844 /* Process results */
846 while( searchFlag
) {
847 ldapqry_touch( qry
);
848 if( qry
->entriesRead
>= ctl
->maxEntries
) break;
851 if( ldapqry_get_stop_flag( qry
) ) {
858 e
= ldap_first_entry( ld
, result
);
861 e
= ldap_next_entry( ld
, e
);
863 if( e
== NULL
) break;
866 /* Setup a critical section here */
867 pthread_mutex_lock( qry
->mutexEntry
);
870 listEMail
= ldapqry_process_single_entry( cache
, qry
, ld
, e
);
872 /* Process callback */
873 if( qry
->callBackEntry
)
874 qry
->callBackEntry( qry
, ADDRQUERY_ID(qry
), listEMail
, qry
->data
);
876 g_list_free( listEMail
);
877 pthread_mutex_unlock( qry
->mutexEntry
);
880 /* Free up and disconnect */
881 ldap_msgfree( result
);
885 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
888 ADDRQUERY_RETVAL(qry
) = LDAPRC_NOENTRIES
;
892 return ADDRQUERY_RETVAL(qry
);
896 * Connection, perform search and disconnect.
897 * \param qry Query object to process.
898 * \return Error/status code.
900 static gint
ldapqry_perform_search( LdapQuery
*qry
) {
901 /* Check search criteria */
902 if( ! ldapqry_check_search( qry
) ) {
903 return ADDRQUERY_RETVAL(qry
);
908 ldapqry_connect( qry
);
909 if( ADDRQUERY_RETVAL(qry
) == LDAPRC_SUCCESS
) {
911 ldapqry_search_retrieve( qry
);
914 ldapqry_disconnect( qry
);
917 return ADDRQUERY_RETVAL(qry
);
920 static gint
ldapqry_perform_locate( LdapQuery
*qry
);
923 * Wrapper around search.
924 * \param qry Query object to process.
925 * \return Error/status code.
927 static gint
ldapqry_search( LdapQuery
*qry
) {
930 cm_return_val_if_fail( qry
!= NULL
, -1 );
931 cm_return_val_if_fail( qry
->control
!= NULL
, -1 );
933 ldapqry_touch( qry
);
934 qry
->completed
= FALSE
;
936 /* Setup pointer to thread specific area */
937 pthread_setspecific( _queryThreadKey_
, qry
);
939 pthread_detach( pthread_self() );
941 /* Now perform the search */
942 qry
->entriesRead
= 0;
943 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
944 ldapqry_set_busy_flag( qry
, TRUE
);
945 ldapqry_set_stop_flag( qry
, FALSE
);
946 if( ADDRQUERY_SEARCHTYPE(qry
) == ADDRSEARCH_LOCATE
) {
947 retVal
= ldapqry_perform_locate( qry
);
950 retVal
= ldapqry_perform_search( qry
);
952 if( retVal
== LDAPRC_SUCCESS
) {
953 qry
->server
->addressCache
->dataRead
= TRUE
;
954 qry
->server
->addressCache
->accessFlag
= FALSE
;
955 if( ldapqry_get_stop_flag( qry
) ) {
956 debug_print("Search was terminated prematurely\n");
959 ldapqry_touch( qry
);
960 qry
->completed
= TRUE
;
961 debug_print("Search ran to completion\n");
964 ldapqry_set_stop_flag( qry
, TRUE
);
965 ldapqry_set_busy_flag( qry
, FALSE
);
967 /* Process callback */
968 if( qry
->callBackEnd
) {
969 g_timeout_add(0, callbackend
, qry
);
972 return ADDRQUERY_RETVAL(qry
);
976 * Read data into list using a background thread. Callback function will be
977 * notified when search is complete.
978 * \param qry Query object to process.
979 * \return Error/status code.
981 gint
ldapqry_read_data_th( LdapQuery
*qry
) {
982 cm_return_val_if_fail( qry
!= NULL
, -1 );
983 cm_return_val_if_fail( qry
->control
!= NULL
, -1 );
985 ldapqry_set_stop_flag( qry
, FALSE
);
986 ldapqry_touch( qry
);
987 if( ldapqry_check_search( qry
) ) {
988 if( ADDRQUERY_RETVAL(qry
) == LDAPRC_SUCCESS
) {
989 debug_print("Starting LDAP search thread\n");
990 ldapqry_set_busy_flag( qry
, TRUE
);
991 qry
->thread
= g_malloc0( sizeof( pthread_t
) );
994 if (pthread_create( qry
->thread
, NULL
,
995 (void *) ldapqry_search
, (void *) qry
) != 0) {
998 ADDRQUERY_RETVAL(qry
) = LDAPRC_SEARCH
;
1002 return ADDRQUERY_RETVAL(qry
);
1006 * Cleanup LDAP thread data. This function will be called when each thread
1007 * exits. Note that the thread object will be freed by the kernel.
1008 * \param ptr Pointer to object being destroyed (a query object in this case).
1010 static void ldapqry_destroyer( void * ptr
) {
1013 qry
= ( LdapQuery
* ) ptr
;
1014 cm_return_if_fail( qry
!= NULL
);
1016 /* Perform any destruction here */
1017 if( qry
->control
!= NULL
) {
1018 ldapctl_free( qry
->control
);
1020 qry
->control
= NULL
;
1022 ldapqry_set_busy_flag( qry
, FALSE
);
1026 * Cancel thread associated with query.
1027 * \param qry Query object to process.
1029 void ldapqry_cancel( LdapQuery
*qry
) {
1030 cm_return_if_fail( qry
!= NULL
);
1032 if( ldapqry_get_busy_flag( qry
) ) {
1034 debug_print("calling pthread_cancel\n");
1035 pthread_cancel( * qry
->thread
);
1041 * Initialize LDAP query. This function should be called once before executing
1042 * any LDAP queries to initialize thread specific data.
1044 void ldapqry_initialize( void ) {
1045 debug_print("ldapqry_initialize...\n");
1046 if( ! _queryThreadInit_
) {
1047 debug_print("ldapqry_initialize::creating thread specific area\n");
1048 pthread_key_create( &_queryThreadKey_
, ldapqry_destroyer
);
1049 _queryThreadInit_
= TRUE
;
1051 debug_print("ldapqry_initialize... done!\n");
1055 * Age the query based on LDAP control parameters.
1056 * \param qry Query object to process.
1057 * \param maxAge Maximum age of query (in seconds).
1059 void ldapqry_age( LdapQuery
*qry
, gint maxAge
) {
1062 cm_return_if_fail( qry
!= NULL
);
1064 /* Limit the time that queries can hang around */
1065 if( maxAge
< 1 ) maxAge
= LDAPCTL_MAX_QUERY_AGE
;
1067 /* Check age of query */
1068 age
= time( NULL
) - qry
->touchTime
;
1069 if( age
> maxAge
) {
1070 qry
->agedFlag
= TRUE
;
1075 * Delete folder associated with query results.
1076 * \param qry Query object to process.
1078 void ldapqry_delete_folder( LdapQuery
*qry
) {
1079 AddressCache
*cache
;
1082 cm_return_if_fail( qry
!= NULL
);
1084 folder
= ADDRQUERY_FOLDER(qry
);
1086 cache
= qry
->server
->addressCache
;
1087 folder
= addrcache_remove_folder_delete( cache
, folder
);
1089 addritem_free_item_folder( folder
);
1091 ADDRQUERY_FOLDER(qry
) = NULL
;
1096 * Create a name/value pair object.
1099 * \return Initialized object.
1101 static NameValuePair
*ldapqry_create_name_value( const gchar
*n
, const gchar
*v
) {
1102 NameValuePair
*nvp
= g_new0( NameValuePair
, 1 );
1104 nvp
->name
= g_strdup( n
);
1105 nvp
->value
= g_strdup( v
);
1110 * Free up name/value pair object.
1111 * \param nvp Name/value object.
1113 void ldapqry_free_name_value( NameValuePair
*nvp
) {
1115 g_free( nvp
->name
);
1116 g_free( nvp
->value
);
1117 nvp
->name
= nvp
->value
= NULL
;
1123 * Free up a list name/value pair objects.
1124 * \param list List of name/value objects.
1126 void ldapqry_free_list_name_value( GList
*list
) {
1131 NameValuePair
*nvp
= ( NameValuePair
* ) node
->data
;
1132 ldapqry_free_name_value( nvp
);
1134 node
= g_list_next( node
);
1136 g_list_free( list
);
1140 * Load a list of name/value pairs from LDAP attributes.
1141 * \param ld LDAP handle.
1142 * \param e LDAP message.
1143 * \param attr Attribute name.
1144 * \param listValues List to populate.
1145 * \return List of attribute name/value pairs.
1147 static GList
*ldapqry_load_attrib_values(
1148 LDAP
*ld
, LDAPMessage
*entry
, char *attr
,
1153 struct berval
**vals
;
1157 if( ( vals
= ldap_get_values_len( ld
, entry
, attr
) ) != NULL
) {
1158 for( i
= 0; vals
[i
] != NULL
; i
++ ) {
1159 gchar
*tmp
= g_strndup( vals
[i
]->bv_val
, vals
[i
]->bv_len
);
1160 nvp
= ldapqry_create_name_value( attr
, tmp
);
1162 list
= g_list_append( list
, nvp
);
1165 ldap_value_free_len( vals
);
1170 * Fetch a list of all attributes.
1171 * \param ld LDAP handle.
1172 * \param e LDAP message.
1173 * \return List of attribute name/value pairs.
1175 static GList
*ldapqry_fetch_attribs( LDAP
*ld
, LDAPMessage
*e
)
1179 GList
*listValues
= NULL
;
1181 /* Process all attributes */
1182 for( attribute
= ldap_first_attribute( ld
, e
, &ber
); attribute
!= NULL
;
1183 attribute
= ldap_next_attribute( ld
, e
, ber
) ) {
1184 listValues
= ldapqry_load_attrib_values( ld
, e
, attribute
, listValues
);
1185 ldap_memfree( attribute
);
1195 #define CRITERIA_SINGLE "(objectclass=*)"
1198 * Perform the data retrieval for a specific LDAP record.
1200 * \param qry Query object to process.
1201 * \return Error/status code.
1203 static gint
ldapqry_locate_retrieve( LdapQuery
*qry
) {
1206 LDAPMessage
*result
, *e
= NULL
;
1207 gboolean entriesFound
;
1209 struct timeval timeout
;
1214 /* Initialize some variables */
1217 dn
= ADDRQUERY_SEARCHVALUE(qry
);
1218 timeout
.tv_sec
= ctl
->timeOut
;
1219 timeout
.tv_usec
= 0L;
1220 entriesFound
= FALSE
;
1223 * Execute the search - this step may take some time to complete
1224 * depending on network traffic and server response time.
1226 ADDRQUERY_RETVAL(qry
) = LDAPRC_TIMEOUT
;
1227 rc
= ldap_search_ext_s( ld
, dn
, LDAP_SCOPE_BASE
, CRITERIA_SINGLE
,
1228 NULL
, 0, NULL
, NULL
, &timeout
, 0, &result
);
1229 if( rc
== LDAP_TIMEOUT
) {
1230 return ADDRQUERY_RETVAL(qry
);
1232 ADDRQUERY_RETVAL(qry
) = LDAPRC_SEARCH
;
1233 if( rc
!= LDAP_SUCCESS
) {
1234 log_error(LOG_PROTOCOL
, _("LDAP error (search): %d (%s)\n"),
1235 rc
, ldaputil_get_error(ld
));
1236 debug_print("LDAP Error: ldap_search_ext_s: %d (%s)\n",
1237 rc
, ldaputil_get_error(ld
));
1238 return ADDRQUERY_RETVAL(qry
);
1240 log_print(LOG_PROTOCOL
, _("LDAP (search): successful\n"));
1244 debug_print("Total results are: %lu\n", ldap_count_entries(ld
, result
));
1246 debug_print("Total results are: %d\n", ldap_count_entries(ld
, result
));
1249 /* Process results */
1250 ADDRQUERY_RETVAL(qry
) = LDAPRC_STOP_FLAG
;
1253 ldapqry_touch( qry
);
1254 if( qry
->entriesRead
>= ctl
->maxEntries
) break;
1257 if( ldapqry_get_stop_flag( qry
) ) {
1261 /* Retrieve entry */
1264 e
= ldap_first_entry( ld
, result
);
1267 e
= ldap_next_entry( ld
, e
);
1269 if( e
== NULL
) break;
1271 entriesFound
= TRUE
;
1273 /* Setup a critical section here */
1274 pthread_mutex_lock( qry
->mutexEntry
);
1277 listValues
= ldapqry_fetch_attribs( ld
, e
);
1279 /* Process callback */
1280 if( qry
->callBackEntry
) {
1281 qry
->callBackEntry( qry
, ADDRQUERY_ID(qry
), listValues
, qry
->data
);
1283 ldapqry_free_list_name_value( listValues
);
1286 pthread_mutex_unlock( qry
->mutexEntry
);
1289 /* Free up and disconnect */
1290 ldap_msgfree( result
);
1292 if( entriesFound
) {
1293 ADDRQUERY_RETVAL(qry
) = LDAPRC_SUCCESS
;
1296 ADDRQUERY_RETVAL(qry
) = LDAPRC_NOENTRIES
;
1299 return ADDRQUERY_RETVAL(qry
);
1303 * Perform the search to locate a specific LDAP record identified by
1304 * distinguished name (dn).
1306 * \param qry Query object to process.
1307 * \return Error/status code.
1309 static gint
ldapqry_perform_locate( LdapQuery
*qry
) {
1312 ldapqry_connect( qry
);
1313 if( ADDRQUERY_RETVAL(qry
) == LDAPRC_SUCCESS
) {
1314 /* Perform search */
1315 ldapqry_locate_retrieve( qry
);
1318 ldapqry_disconnect( qry
);
1321 /* Process callback */
1322 if( qry
->callBackEnd
) {
1323 g_timeout_add(0, callbackend
, qry
);
1326 return ADDRQUERY_RETVAL(qry
);
1330 * Remove results (folder and data) for specified LDAP query.
1331 * \param qry Query object to process.
1332 * \return TRUE if folder deleted successfully.
1334 gboolean
ldapquery_remove_results( LdapQuery
*qry
) {
1335 gboolean retVal
= FALSE
;
1337 ldapqry_set_aged_flag( qry
, TRUE
);
1339 if( ldapqry_get_busy_flag( qry
) ) {
1340 ldapqry_set_stop_flag( qry
, TRUE
);
1343 LdapServer
*server
= qry
->server
;
1344 server
->listQuery
= g_list_remove(server
->listQuery
, qry
);
1351 void ldapqry_print(LdapQuery
*qry
, FILE *stream
) {
1352 cm_return_if_fail( qry
!= NULL
);
1354 ldapsvr_print_data(qry
->server
, stream
);
1355 ldapctl_print(qry
->control
, stream
);
1356 fprintf(stream
, "entriesRead: %d\n", qry
->entriesRead
);
1357 fprintf(stream
, "elapsedTime: %d\n", qry
->elapsedTime
);
1358 fprintf(stream
, "stopFlag: %d\n", qry
->stopFlag
);
1359 fprintf(stream
, "busyFlag: %d\n", qry
->busyFlag
);
1360 fprintf(stream
, "agedFlag: %d\n", qry
->agedFlag
);
1361 fprintf(stream
, "completed: %d\n", qry
->completed
);
1362 fprintf(stream
, "startTime: %d\n", (int) qry
->startTime
);
1363 fprintf(stream
, "touchTime: %d\n", (int) qry
->touchTime
);
1364 fprintf(stream
, "data: %s\n", qry
->data
?(gchar
*)qry
->data
:"null");
1367 #endif /* USE_LDAP */