Few optimizations: avoid strlen when string length is known (read()>0 return);
[claws.git] / src / ldaputil.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2003-2018 Match Grun and the Claws Mail team
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 3 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, see <http://www.gnu.org/licenses/>.
17  */
18
19 /*
20  * Some utility functions to access LDAP servers.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #include "claws-features.h"
26 #endif
27
28 #ifdef USE_LDAP
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32 #include <string.h>
33 #include <sys/time.h>
34 #include <errno.h>
35 #include "common/utils.h"
36 #include "ldaputil.h"
37 #include "ldapserver.h"
38 #include "ldapctrl.h"
39 #include "log.h"
40
41 #define SYLDAP_TEST_FILTER   "(objectclass=*)"
42 #define SYLDAP_SEARCHBASE_V2 "cn=config"
43 #define SYLDAP_SEARCHBASE_V3 ""
44 #define SYLDAP_V2_TEST_ATTR  "database"
45 #define SYLDAP_V3_TEST_ATTR  "namingcontexts"
46
47 /**
48  * Attempt to discover the base DN for a server using LDAP version 3.
49  * \param  ld  LDAP handle for a connected server.
50  * \param  tov Timeout value (seconds), or 0 for none, default 30 secs.
51  * \return List of Base DN's, or NULL if could not read. List should be
52  *         g_free() when done.
53  */
54 static GList *ldaputil_test_v3( LDAP *ld, gint tov, gint *errcode ) {
55         GList *baseDN = NULL;
56         gint rc, i;
57         LDAPMessage *result = NULL, *e;
58         gchar *attribs[2];
59         BerElement *ber;
60         gchar *attribute;
61         struct berval **vals;
62         struct timeval timeout;
63
64         /* Set timeout */
65         timeout.tv_usec = 0L;
66         if( tov > 0 ) {
67                 timeout.tv_sec = tov;
68         }
69         else {
70                 timeout.tv_sec = 30L;
71         }
72
73         /* Test for LDAP version 3 */
74         attribs[0] = SYLDAP_V3_TEST_ATTR;
75         attribs[1] = NULL;
76         rc = ldap_search_ext_s(
77                 ld, SYLDAP_SEARCHBASE_V3, LDAP_SCOPE_BASE, SYLDAP_TEST_FILTER,
78                 attribs, 0, NULL, NULL, &timeout, 0, &result );
79
80         if( rc == LDAP_SUCCESS ) {
81                 log_print(LOG_PROTOCOL, _("LDAP (search): succesful\n"));
82                 /* Process entries */
83                 for( e = ldap_first_entry( ld, result );
84                      e != NULL;
85                      e = ldap_next_entry( ld, e ) ) 
86                 {
87                         /* Process attributes */
88                         for( attribute = ldap_first_attribute( ld, e, &ber );
89                              attribute != NULL;
90                              attribute = ldap_next_attribute( ld, e, ber ) )
91                         {
92                                 if( strcasecmp(
93                                         attribute, SYLDAP_V3_TEST_ATTR ) == 0 )
94                                 {
95                                         vals = ldap_get_values_len( ld, e, attribute );
96                                         if( vals != NULL ) {
97                                                 for( i = 0; vals[i] != NULL; i++ ) {
98                                                         baseDN = g_list_append(
99                                                                 baseDN, g_strndup( vals[i]->bv_val, vals[i]->bv_len ) );
100                                                 }
101                                         }
102                                         ldap_value_free_len( vals );
103                                 }
104                                 ldap_memfree( attribute );
105                         }
106                         if( ber != NULL ) {
107                                 ber_free( ber, 0 );
108                         }
109                         ber = NULL;
110                 }
111         } else {
112                 log_error(LOG_PROTOCOL, _("LDAP error (search): %d (%s)\n"),
113                                 rc, ldaputil_get_error(ld));
114                 debug_print("LDAP: Error %d (%s)\n", rc, ldaputil_get_error(ld));
115         }
116         
117         if (errcode)
118                 *errcode = rc;
119         if (result)
120                 ldap_msgfree( result );
121         return baseDN;
122 }
123
124 /**
125  * Attempt to discover the base DN for a server using LDAP version 2.
126  * \param  ld  LDAP handle for a connected server.
127  * \param  tov Timeout value (seconds), or 0 for none, default 30 secs.
128  * \return List of Base DN's, or NULL if could not read. List should be
129  *         g_free() when done.
130  */
131 static GList *ldaputil_test_v2( LDAP *ld, gint tov ) {
132         GList *baseDN = NULL;
133         gint rc, i;
134         LDAPMessage *result = NULL, *e;
135         gchar *attribs[1];
136         BerElement *ber;
137         gchar *attribute;
138         struct berval **vals;
139         struct timeval timeout;
140
141         /* Set timeout */
142         timeout.tv_usec = 0L;
143         if( tov > 0 ) {
144                 timeout.tv_sec = tov;
145         }
146         else {
147                 timeout.tv_sec = 30L;
148         }
149
150         attribs[0] = NULL;
151         rc = ldap_search_ext_s(
152                 ld, SYLDAP_SEARCHBASE_V2, LDAP_SCOPE_BASE, SYLDAP_TEST_FILTER,
153                 attribs, 0, NULL, NULL, &timeout, 0, &result );
154
155         if( rc == LDAP_SUCCESS ) {
156                 log_print(LOG_PROTOCOL, _("LDAP (search): succesful\n"));
157                 /* Process entries */
158                 for( e = ldap_first_entry( ld, result );
159                      e != NULL;
160                      e = ldap_next_entry( ld, e ) )
161                 {
162                         /* Process attributes */
163                         for( attribute = ldap_first_attribute( ld, e, &ber );
164                              attribute != NULL;
165                              attribute = ldap_next_attribute( ld, e, ber ) )
166                         {
167                                 if( strcasecmp(
168                                         attribute,
169                                         SYLDAP_V2_TEST_ATTR ) == 0 ) {
170                                         vals = ldap_get_values_len( ld, e, attribute );
171                                         if( vals != NULL ) {
172                                                 for( i = 0; vals[i] != NULL; i++ ) {
173                                                         char *ch, *tmp;
174                                                         /*
175                                                          * Strip the 'ldb:' from the
176                                                          * front of the value.
177                                                          */
178                                                         tmp = g_strndup( vals[i]->bv_val, vals[i]->bv_len);
179                                                         ch = ( char * ) strchr( tmp, ':' );
180                                                         if( ch ) {
181                                                                 gchar *bn = g_strdup( ++ch );
182                                                                 g_strstrip( bn );
183                                                                 baseDN = g_list_append(
184                                                                         baseDN, g_strdup( bn ) );
185                                                                 g_free( bn );
186                                                         }
187                                                         g_free(tmp);
188                                                 }
189                                         }
190                                         ldap_value_free_len( vals );
191                                 }
192                                 ldap_memfree( attribute );
193                         }
194                         if( ber != NULL ) {
195                                 ber_free( ber, 0 );
196                         }
197                         ber = NULL;
198                 }
199         } else {
200                 log_error(LOG_PROTOCOL, _("LDAP error (search): %d (%s)\n"),
201                                 rc, ldaputil_get_error(ld));
202                 debug_print("LDAP: Error %d (%s)\n", rc, ldaputil_get_error(ld));
203         }
204         if (result)
205                 ldap_msgfree( result );
206         return baseDN;
207 }
208
209 int claws_ldap_simple_bind_s( LDAP *ld, LDAP_CONST char *dn, LDAP_CONST char *passwd )
210 {
211         debug_print("binding: DN->%s\n", dn?dn:"null");
212 #ifdef G_OS_UNIX
213         struct berval cred;
214
215         if ( passwd != NULL ) {
216                 cred.bv_val = (char *) passwd;
217                 cred.bv_len = strlen( passwd );
218         } else {
219                 cred.bv_val = "";
220                 cred.bv_len = 0;
221         }
222
223         return ldap_sasl_bind_s( ld, dn, LDAP_SASL_SIMPLE, &cred,
224                 NULL, NULL, NULL );
225 #else
226         return ldap_simple_bind_s(ld, (PCHAR)dn, (PCHAR)passwd);
227 #endif
228 }
229
230 /**
231  * Attempt to discover the base DN for the server.
232  * \param  host   Host name.
233  * \param  port   Port number.
234  * \param  bindDN Bind DN (optional).
235  * \param  bindPW Bind PW (optional).
236  * \param  tov    Timeout value (seconds), or 0 for none, default 30 secs.
237  * \return List of Base DN's, or NULL if could not read. This list should be
238  *         g_free() when done.
239  */
240 GList *ldaputil_read_basedn(
241                 const gchar *host, const gint port, const gchar *bindDN,
242                 const gchar *bindPW, const gint tov, int ssl, int tls )
243 {
244         GList *baseDN = NULL;
245         LDAP *ld = NULL;
246         LdapControl *ctl = ldapctl_create();
247         gint rc;
248
249         if( host == NULL ) 
250                 return NULL;
251         if( port < 1 ) 
252                 return NULL;
253
254         ldapctl_set_tls(ctl, tls);
255         ldapctl_set_ssl(ctl, ssl);
256         ldapctl_set_port(ctl, port);
257         ldapctl_set_host(ctl, host);
258         ldapctl_set_timeout(ctl, tov);
259         ldapctl_set_bind_dn(ctl, bindDN);
260
261         ld = ldapsvr_connect(ctl);
262         if (ld == NULL) {
263                 ldapctl_free(ctl);
264                 return NULL;
265         }
266         baseDN = ldaputil_test_v3( ld, tov, &rc );
267         if (baseDN)
268                 debug_print("Using LDAP v3\n");
269
270 #ifdef G_OS_UNIX
271         if( baseDN == NULL && !LDAP_API_ERROR(rc) ) {
272 #else
273         if( baseDN == NULL) {
274 #endif
275                 baseDN = ldaputil_test_v2( ld, tov );
276                 if (baseDN)
277                         debug_print("Using LDAP v2\n");
278         }
279         if (ld)
280                 ldapsvr_disconnect(ld);
281
282         ldapctl_free(ctl);
283         
284         return baseDN;
285 }
286
287 /**
288  * Attempt to connect to the server.
289  * Enter:
290  * \param  host Host name.
291  * \param  port Port number.
292  * \return <i>TRUE</i> if connected successfully.
293  */
294 gboolean ldaputil_test_connect( const gchar *host, const gint port, int ssl, int tls, int secs ) {
295         gboolean retVal = FALSE;
296         LdapControl *ctl = ldapctl_create();
297         LDAP *ld;
298
299         ldapctl_set_tls(ctl, tls);
300         ldapctl_set_ssl(ctl, ssl);
301         ldapctl_set_port(ctl, port);
302         ldapctl_set_host(ctl, host);
303         ldapctl_set_timeout(ctl, secs);
304
305         ld = ldapsvr_connect(ctl);
306         if( ld != NULL ) {
307                 ldapsvr_disconnect(ld);
308                 debug_print("ld != NULL\n");
309                 retVal = TRUE;
310         }
311         ldapctl_free(ctl);
312
313         return retVal;
314 }
315
316 /**
317  * Test whether LDAP libraries installed.
318  * Return: TRUE if library available.
319  */
320 gboolean ldaputil_test_ldap_lib( void ) {
321         return TRUE;
322 }
323
324 const gchar *ldaputil_get_error(LDAP *ld)
325 {
326         gchar *ld_error = NULL;
327         static gchar error[512];
328
329         ldap_get_option( ld, LDAP_OPT_ERROR_STRING, &ld_error);
330         if (ld_error != NULL)
331                 strncpy2(error, ld_error, sizeof(error));
332         else
333                 strncpy2(error, _("Unknown error"), sizeof(error));
334 #ifndef G_OS_WIN32
335         /* From https://msdn.microsoft.com/en-us/library/aa366594%28v=vs.85%29.aspx
336          * "LDAP_OPT_ERROR_STRING returns a pointer to an internal static
337          * string table, and ldap_memfree should not be called when using
338          * this session option."
339          */
340         ldap_memfree(ld_error);
341 #endif
342
343         return error;
344 }
345 #endif  /* USE_LDAP */
346
347 /*
348  * End of Source.
349 */