Compile even if we don't have pthread's
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
1 /*
2  * rlm_ldap.c   LDAP authorization and authentication module.
3  *
4  *   This program is free software; you can redistribute it and/or modify
5  *   it under the terms of the GNU General Public License as published by
6  *   the Free Software Foundation; either version 2 of the License, or
7  *   (at your option) any later version.
8  *
9  *   This program is distributed in the hope that it will be useful,
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *   GNU General Public License for more details.
13  *
14  *   You should have received a copy of the GNU General Public License
15  *   along with this program; if not, write to the Free Software
16  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  *
18  * This module is based on LDAP patch to Cistron radiusd by James Golovich 
19  * <james@wwnet.net>, which in turn was based mostly on a Mysql+Cistron patch 
20  * from <oyarzun@wilmington.net>
21  * 
22  * 17 Jan 2000, Adrian Pavlykevych <pam@polynet.lviv.ua>
23  *      - OpenLDAP SDK porting, basic TLS support, LDAP authorization,
24  *        fault tolerance with multiple LDAP server support 
25  * 24 May 2000, Adrian Pavlykevych <pam@polynet.lviv.ua> 
26  *      - Converting to new configuration file format, futher improvements
27  *        in fault tolerance, threaded operation
28  * 12 Dec 2000, Adrian Pavlykevych <pam@polynet.lviv.ua> 
29  *      - Added preliminary support for multiple instances
30  *      - moved all instance configuration into dynamicly allocated structure
31  *      - Removed connection maintenance thread and all attempts for multihreading
32  *        the module itself. OpenLDAP SDK is not thread safe when used with shared
33  *        LDAP connection.
34  *      - Added configuration option for defining LDAP attribute of user object,
35  *        which controls remote access.
36  * 16 Feb 2001, Hannu Laurila <hannu.laurila@japo.fi>
37  *      - LDAP<->RADIUS attribute mappings are now read from a file
38  *      - Support for generic RADIUS check and reply attribute.
39  * Jun 2001, Kostas Kalevras <kkalev@noc.ntua.gr>
40  *      - Fix: check and reply attributes from LDAP _replace_ existing ones
41  *      - Added "default_profile" directive, which points to radiusProfile 
42  *        object, which contains default values for RADIUS users
43  *      - Added "profile_attribute" directive, which specifies user object 
44  *        attribute pointing to radiusProfile object.
45  * Nov 2001, Kostas Kalevras <kkalev@noc.ntua.gr>
46  *      - Added support for adding the user password to the check. Based on
47  *        the password_header directive rlm_ldap will strip the
48  *        password header if needed. This will make support for CHAP much easier.
49  *      - Added module messages when we reject a user.
50  *      - Added ldap_groupcmp to allow searching for user group membership.
51  *      - Added ldap_xlat to allow ldap urls in xlat strings. Something like:
52  *        %{ldap:ldap:///dc=company,dc=com?cn?sub?uid=user}
53  * Nov 2001, Gordon Tetlow <gordont@gnf.org>
54  *      - Do an xlat on the access_group attribute.
55  * Dec 2001, Kostas Kalevras <kkalev@noc.ntua.gr>
56  *      - Added ldap caching for the default/regular profiles and group entries.
57  *      - Fixed a memory leak in ldap_xlat.
58  *      - Removed dict_attrbyname from ldap_pairget. They are not needed.
59  *      - Moved the radius_xlat's for filter and basedn in ldap_authenticate() to
60  *        the right place.
61  *      - Made the module thread safe. We create a connection pool and each thread
62  *        will call ldap_get_conn to lock one of the ldap connections and release with
63  *        a call to ldap_release_conn when it has finished.
64  *      - Request only the user attributes that interest us (radius attributes,regular
65  *        profile,user password and access attribute).
66  * Mar 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
67  *      - Fixed a bug where the ldap server will kill the idle connections from the ldap
68  *        connection pool. We now check if ldap_search returns LDAP_SERVER_DOWN and try to
69  *        reconnect if it does. Bug noted by Dan Perik <dan_perik-work@ntm.org.pg>
70  * May 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
71  *      - Instead of the Group attribute we now have the Ldap-Group attribute, to avoid
72  *        collisions with other modules
73  *      - If perform_search fails check the ld != NULL before using it. Based on a bug report
74  *        by John <jhogenmiller@pennswoods.net>
75  * Jun 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
76  *      - Add the ability to do a paircmp on the check items. Add a compare_check_items boolean
77  *        configuration directive which defaults to no. If it is set then we will do a compare
78  *      - Add another configuration directive. access_attr_used_for_allow. If it is set to yes
79  *        then the access_attr will be used to allow user access. If it is set to no then it will
80  *        be used to deny user access.
81  *      - Remember to free inst->atts in ldap_detach()
82  *      - Add a forgotten ldap_free_urldesc in ldap_xlat()
83  *      - Add a variable locked in the LDAP_CONN structure. We use this to avoid deadlocks. The mutex
84  *        we are using is of type fast and can deadlock if the same thread tries to relock it. That
85  *        could happen in case of calls to xlat.
86  *      - When ldap_search returns NO_SUCH_OBJECT don't return fail but notfound
87  * Jul 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
88  *      - Fix the logic when we get an LDAP_SERVER_DOWN or we have conn->ld == NULL in perform_search
89  *      - Try to minimize the penalty of having the ldap server go down. The comments before
90  *        MAX_FAILED_CONNS_* definitions should explain things.
91  *      - Check for a number of error codes from ldap_search and log corresponding error messages
92  *        We should only reconnect when that can help things.
93  *      - In ldap_groupcmp instead of first searching for the group object and then checking user
94  *        group membership combine them in one ldap search operation. That should make group
95  *        membership checks a lot faster.
96  *      - Remember to do ldap_release_conn and ldap_msgfree when we do paircmp and the result is reject
97  * Aug 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
98  *      - Add support for group membership attribute inside the user entry in ldap_groupcmp. The attribute
99  *        can either contain the name or the DN of the group. Added the groupmembership_attribute
100  *        configuration directive
101  *      - Move the ldap_{get,release}_conn in ldap_groupcmp so that we hold a connection for the minimum time.
102  *      - Now that ldap_groupcmp is complete we really don't need access_group. Removed it.
103  *      - Remember to free groupmembership_attribute in ldap_detach
104  *      - Don't delete existing generic attributes in ldap_pairget when adding new ones. Since generic attributes
105  *        have operators we don't need to try to be cleaver.
106  * Sep 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
107  *      - Fix a crash in ldap_pairget when the attribute value is larger than the buffer size
108  *        Bug report by Stefan Radovanovici <sra@rtsffm.com>
109  *      - If we add a check item then use the == operator. Based on an idea by Allister Maguire <amaguire@gnc.net.nz>
110  *      - Only add a failure message for bind as user failed in ldap_authenticate if the result of ldap_connect was
111  *        RLM_MODULE_REJECT
112  *      - Make tls_mode a configurable option. Patch from John <jhogenmiller@pennswoods.net>
113  *      - Allow multiple regular profiles for an entry
114  * Oct 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
115  *      - Disable cache after searching for the default profile
116  *      - Use the MAX_FAILED_CONNS_* in ldap_authenticate() when calling ldap_connect()
117  * Nov 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
118  *      - Set LDAP version to V3 before binding. Now freeradius should work with openldap21
119  * Dec 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
120  *      - Set default values for the server and basedn parameters
121  * Feb 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
122  *      - Add support for ldap_initialize. That way we can specify the server as an ldap url.
123  *        Based on ideas from Derrik Pates <dpates@dsdk12.net>
124  * Mar 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
125  *      - Add an ldap_escape_func. Escape the * character from the filter so that we can avoid
126  *        the trivial DoS of username=*
127  *      - Remove the caching code. It does not exist in openldap21.
128  *        Based on a report from Mike Denka <mdenk@whidbey.net>
129  * May 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
130  *      - Don't do a double free on the attribute maps. Bug noted by Derrik Pates <dpates@dsdk12.net>
131  *      - Apply a patch from Alexander M. Pravking <fduch@antar.bryansk.ru> to do an xlat on the
132  *        retrieved attributes.
133  * Aug 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
134  *      - In case of a bad search filter, print out the corresponding filter
135  * Sep 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
136  *      - Compile even if we don't have pthread's
137  */
138 static const char rcsid[] = "$Id$";
139
140 #include "autoconf.h"
141
142 #include        <sys/types.h>
143 #include        <sys/socket.h>
144 #include        <sys/time.h>
145 #include        <netinet/in.h>
146
147 #include        <stdio.h>
148 #include        <stdlib.h>
149 #include        <netdb.h>
150 #include        <pwd.h>
151 #include        <time.h>
152 #include        <ctype.h>
153 #include        <string.h>
154
155 #include        <lber.h>
156 #include        <ldap.h>
157
158 #include        <errno.h>
159 #include        <unistd.h>
160 #include        <pthread.h>
161
162 #include        "libradius.h"
163 #include        "radiusd.h"
164 #include        "conffile.h"
165 #include        "modules.h"
166 #include        "rad_assert.h"
167
168 #ifndef HAVE_PTHREAD_H
169 /*
170  *      This is a lot simpler than putting ifdef's around
171  *      every use of the pthread functions.
172  */
173 #define pthread_mutex_lock(a)
174 #define pthread_mutex_unlock(a)
175 #define pthread_mutex_init(a,b)
176 #define pthread_mutex_destroy(a)
177 #endif
178
179
180 #define MAX_FILTER_STR_LEN      1024
181 #define TIMELIMIT 5
182
183 /*
184  * These are used in case ldap_search returns LDAP_SERVER_DOWN
185  * In that case we do conn->failed_conns++ and then check it:
186  * If conn->failed_conns <= MAX_FAILED_CONNS_START then we try
187  * to reconnect
188  * conn->failed_conns is also checked on entrance in perform_search:
189  * If conn->failed_conns > MAX_FAILED_CONNS_START then we don't
190  * try to do anything and we just do conn->failed_conns++ and
191  * return RLM_MODULE_FAIL
192  * if conn->failed_conns >= MAX_FAILED_CONNS_END then we give it
193  * another chance and we set it to MAX_FAILED_CONNS_RESTART and
194  * try to reconnect.
195  *
196  *
197  * We are assuming that the majority of the LDAP_SERVER_DOWN cases
198  * will either be an ldap connection timeout or a temporary ldap
199  * server problem.
200  * As a result we make a few attempts to reconnect hoping that the problem
201  * will soon go away. If it does not go away then we just return
202  * RLM_MODULE_FAIL on entrance in perform_search until conn->failed_conns
203  * gets to MAX_FAILED_CONNS_END. After that we give it one more chance by
204  * going back to MAX_FAILED_CONNS_RESTART
205  *
206  */
207
208 #define MAX_FAILED_CONNS_END            20
209 #define MAX_FAILED_CONNS_RESTART        4
210 #define MAX_FAILED_CONNS_START          5
211
212 /* linked list of mappings between RADIUS attributes and LDAP attributes */
213 struct TLDAP_RADIUS {
214         char*                 attr;
215         char*                 radius_attr;
216         struct TLDAP_RADIUS*  next;
217 };
218 typedef struct TLDAP_RADIUS TLDAP_RADIUS;
219
220 typedef struct ldap_conn {
221         LDAP            *ld;
222         char            bound;
223         char            locked;
224         int             failed_conns;
225         pthread_mutex_t mutex;
226 } LDAP_CONN;
227
228 typedef struct {
229         char           *server;
230         int             port;
231         int             timelimit;
232         struct timeval  net_timeout;
233         struct timeval  timeout;
234         int             debug;
235         int             tls_mode;
236         int             start_tls;
237         int             num_conns;
238         int             do_comp;
239         int             default_allow;
240         int             failed_conns;
241         int             is_url;
242         char           *login;
243         char           *password;
244         char           *filter;
245         char           *basedn;
246         char           *default_profile;
247         char           *profile_attr;
248         char           *access_attr;
249         char           *passwd_hdr;
250         char           *passwd_attr;
251         char           *dictionary_mapping;
252         char           *groupname_attr;
253         char           *groupmemb_filt;
254         char           *groupmemb_attr;
255         char            **atts;
256         TLDAP_RADIUS   *check_item_map;
257         TLDAP_RADIUS   *reply_item_map;
258         LDAP_CONN       *conns;
259         int             ldap_debug; /* Debug flag for LDAP SDK */
260         char            *xlat_name; /* name used to xlat */
261 }               ldap_instance;
262
263 static CONF_PARSER module_config[] = {
264         {"server", PW_TYPE_STRING_PTR, offsetof(ldap_instance,server), NULL, "localhost"},
265         {"port", PW_TYPE_INTEGER, offsetof(ldap_instance,port), NULL, "389"},
266         /* wait forever on network activity */
267         {"net_timeout", PW_TYPE_INTEGER, offsetof(ldap_instance,net_timeout.tv_sec), NULL, "10"},
268         /* wait forever for search results */
269         {"timeout", PW_TYPE_INTEGER, offsetof(ldap_instance,timeout.tv_sec), NULL, "20"},
270         /* allow server unlimited time for search (server-side limit) */
271         {"timelimit", PW_TYPE_INTEGER, offsetof(ldap_instance,timelimit), NULL, "20"},
272         {"identity", PW_TYPE_STRING_PTR, offsetof(ldap_instance,login), NULL, ""},
273         {"start_tls", PW_TYPE_BOOLEAN, offsetof(ldap_instance,start_tls), NULL, "no"},
274         {"password", PW_TYPE_STRING_PTR, offsetof(ldap_instance,password), NULL, ""},
275         {"basedn", PW_TYPE_STRING_PTR, offsetof(ldap_instance,basedn), NULL, "o=notexist"},
276         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,filter), NULL, "(uid=%u)"},
277         {"default_profile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,default_profile), NULL, NULL},
278         {"profile_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,profile_attr), NULL, NULL},
279         {"password_header", PW_TYPE_STRING_PTR, offsetof(ldap_instance,passwd_hdr), NULL, NULL},
280         {"password_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,passwd_attr), NULL, NULL},
281         /* LDAP attribute name that controls remote access */
282         {"access_attr", PW_TYPE_STRING_PTR, offsetof(ldap_instance,access_attr), NULL, NULL},
283         /* file with mapping between LDAP and RADIUS attributes */
284         {"groupname_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupname_attr), NULL, "cn"},
285         {"groupmembership_filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupmemb_filt), NULL, "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
286         {"groupmembership_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
287         {"dictionary_mapping", PW_TYPE_STRING_PTR, offsetof(ldap_instance,dictionary_mapping), NULL, "${confdir}/ldap.attrmap"},
288         {"ldap_debug", PW_TYPE_INTEGER, offsetof(ldap_instance,ldap_debug), NULL, "0x0000"},
289         {"ldap_connections_number", PW_TYPE_INTEGER, offsetof(ldap_instance,num_conns), NULL, "5"},
290         {"compare_check_items", PW_TYPE_BOOLEAN, offsetof(ldap_instance,do_comp), NULL, "no"},
291         {"access_attr_used_for_allow", PW_TYPE_BOOLEAN, offsetof(ldap_instance,default_allow), NULL, "yes"},
292
293         {NULL, -1, 0, NULL, NULL}
294 };
295
296 #define ld_valid                ld_options.ldo_valid
297 #define LDAP_VALID_SESSION      0x2
298 #define LDAP_VALID(ld)  ( (ld)->ld_valid == LDAP_VALID_SESSION )
299
300 #ifdef FIELDCPY
301 static void     fieldcpy(char *, char **);
302 #endif
303 static VALUE_PAIR *ldap_pairget(LDAP *, LDAPMessage *, TLDAP_RADIUS *,VALUE_PAIR **,char);
304 static int ldap_groupcmp(void *, REQUEST *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **);
305 static int ldap_xlat(void *,REQUEST *, char *, char *,int, RADIUS_ESCAPE_STRING);
306 static LDAP    *ldap_connect(void *instance, const char *, const char *, int, int *);
307 static int     read_mappings(ldap_instance* inst);
308
309 static inline int ldap_get_conn(LDAP_CONN *conns,LDAP_CONN **ret,void *instance)
310 {
311         ldap_instance *inst = instance;
312         register int i = 0;
313
314         for(;i<inst->num_conns;i++){
315                 if (conns[i].locked == 0 && pthread_mutex_trylock(&(conns[i].mutex)) == 0){
316                         *ret = &conns[i];
317                         conns[i].locked = 1;
318                         DEBUG("ldap_get_conn: Got Id: %d",i);
319                         return i;
320                 }
321         }
322
323         return -1;
324 }
325         
326 static inline void ldap_release_conn(int i, LDAP_CONN *conns)
327 {
328         DEBUG("ldap_release_conn: Release Id: %d",i);
329         conns[i].locked = 0;
330         pthread_mutex_unlock(&(conns[i].mutex));
331 }
332
333 /*************************************************************************
334  *
335  *      Function: rlm_ldap_instantiate
336  *
337  *      Purpose: Uses section of radiusd config file passed as parameter
338  *               to create an instance of the module.
339  *
340  *************************************************************************/
341 static int 
342 ldap_instantiate(CONF_SECTION * conf, void **instance)
343 {
344         ldap_instance  *inst;
345         int i = 0;
346         int atts_num = 0;
347         int reply_map_num = 0;
348         int check_map_num = 0;
349         int att_map[3] = {0,0,0};
350         TLDAP_RADIUS *pair;
351         char *xlat_name;
352
353         inst = rad_malloc(sizeof *inst);
354         if (!inst) {
355                 return -1;
356         }
357         memset(inst, 0, sizeof(*inst));
358
359         if (cf_section_parse(conf, inst, module_config) < 0) {
360                 free(inst);
361                 return -1;
362         }
363
364         if (inst->server == NULL) {
365                 radlog(L_ERR, "rlm_ldap: missing 'server' directive.");
366                 free(inst);
367                 return -1;
368         }
369         inst->is_url = 0;
370 #ifdef HAVE_LDAP_INITIALIZE
371         if (ldap_is_ldap_url(inst->server)){
372                 inst->is_url = 1;
373                 inst->port = 0;
374         }
375 #endif
376  
377         inst->timeout.tv_usec = 0;
378         inst->net_timeout.tv_usec = 0;
379         /* workaround for servers which support LDAPS but not START TLS */
380         if(inst->port == LDAPS_PORT)
381                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
382         else
383                 inst->tls_mode = 0;
384         inst->reply_item_map = NULL;
385         inst->check_item_map = NULL;
386         inst->conns = NULL;
387         inst->failed_conns = 0;
388
389         paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst);
390         DEBUG("conns: %p",inst->conns);
391
392         xlat_name = cf_section_name2(conf);
393         if (xlat_name == NULL) {
394                 xlat_name = cf_section_name1(conf);
395                 rad_assert(xlat_name != NULL); /* or all hell breaks loose */
396         }
397         inst->xlat_name = strdup(xlat_name);
398         xlat_register(xlat_name,ldap_xlat,inst);
399
400         if (inst->num_conns <= 0){
401                 radlog(L_ERR, "rlm_ldap: Invalid ldap connections number passed.");
402                 free(inst);
403                 return -1;
404         }
405         inst->conns = (LDAP_CONN *)malloc(sizeof(LDAP_CONN)*inst->num_conns);
406         if (inst->conns == NULL){
407                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
408                 free(inst);
409                 return -1;
410         }
411         for(;i<inst->num_conns;i++){
412                 inst->conns[i].bound = 0;
413                 inst->conns[i].locked = 0;
414                 inst->conns[i].failed_conns = 0;
415                 inst->conns[i].ld = NULL;
416                 pthread_mutex_init(&inst->conns[i].mutex, NULL);
417         }       
418
419         if (read_mappings(inst) != 0) {
420                 radlog(L_ERR, "rlm_ldap: Reading dictionary mappings from file %s failed",
421                        inst->dictionary_mapping);
422                 radlog(L_ERR, "rlm_ldap: Proceeding with no mappings");
423         }
424         
425         pair = inst->check_item_map;
426         while(pair != NULL){
427                 atts_num++;
428                 pair = pair->next;
429         }
430         check_map_num = (atts_num - 1);
431         pair = inst->reply_item_map;
432         while(pair != NULL){
433                 atts_num++;
434                 pair = pair->next;
435         }
436         reply_map_num = (atts_num - 1);
437         if (inst->profile_attr)
438                 atts_num++;
439         if (inst->passwd_attr)
440                 atts_num++;
441         if (inst->access_attr)
442                 atts_num++;
443         inst->atts = (char **)malloc(sizeof(char *)*(atts_num + 1));
444         if (inst->atts == NULL){
445                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
446                 free(inst);
447                 return -1;
448         }
449         pair = inst->check_item_map;
450         for(i=0;i<atts_num;i++){
451                 if (i <= check_map_num ){
452                         inst->atts[i] = pair->attr;
453                         if (i == check_map_num)
454                                 pair = inst->reply_item_map;
455                         else
456                                 pair = pair->next;
457                 }
458                 else if (i <= reply_map_num){
459                         inst->atts[i] = pair->attr;
460                         pair = pair->next;
461                 }
462                 else{
463                         if (inst->profile_attr && !att_map[0]){
464                                 inst->atts[i] = inst->profile_attr;
465                                 att_map[0] = 1;
466                         }
467                         else if (inst->passwd_attr && !att_map[1]){
468                                 inst->atts[i] = inst->passwd_attr;
469                                 att_map[1] = 1;
470                         }
471                         else if (inst->access_attr && !att_map[2]){
472                                 inst->atts[i] = inst->access_attr;
473                                 att_map[2] = 1;
474                         }
475                 }
476         }
477         inst->atts[atts_num] = NULL;            
478
479         DEBUG("conns: %p",inst->conns);
480
481         *instance = inst;
482
483
484         return 0;
485 }
486
487
488 /*
489  * read_mappings(...) reads a ldap<->radius mappings file to inst->reply_item_map and inst->check_item_map
490  */
491
492 #define MAX_LINE_LEN 160
493 #define GENERIC_ATTRIBUTE_ID "$GENERIC$"
494
495 static int
496 read_mappings(ldap_instance* inst)
497 {
498         FILE* mapfile;
499         char *filename;
500         /* all buffers are of MAX_LINE_LEN so we can use sscanf without being afraid of buffer overflows */
501         char buf[MAX_LINE_LEN], itemType[MAX_LINE_LEN], radiusAttribute[MAX_LINE_LEN], ldapAttribute[MAX_LINE_LEN];
502         int linenumber;
503
504         /* open the mappings file for reading */
505
506         filename = inst->dictionary_mapping;
507         DEBUG("rlm_ldap: reading ldap<->radius mappings from file %s", filename);
508         mapfile = fopen(filename, "r");
509
510         if (mapfile == NULL) {
511                 radlog(L_ERR, "rlm_ldap: Opening file %s failed", filename);
512                 return -1; /* error */
513         }
514
515         /* read file line by line. Note that if line length exceed MAX_LINE_LEN, line numbers will be mixed up */
516
517         linenumber = 0;
518
519         while (fgets(buf, sizeof buf, mapfile)!=NULL) {
520                 char* ptr;
521                 int token_count;
522                 TLDAP_RADIUS* pair;
523
524                 linenumber++;
525
526                 /* strip comments */
527                 ptr = strchr(buf, '#');
528                 if (ptr) *ptr = 0;
529                 
530                 /* empty line */
531                 if (buf[0] == 0) continue;
532                 
533                 /* extract tokens from the string */            
534                 token_count = sscanf(buf, "%s %s %s", itemType, radiusAttribute, ldapAttribute);
535
536                 if (token_count <= 0) /* no tokens */                   
537                         continue;
538
539                 if (token_count != 3) {
540                         radlog(L_ERR, "rlm_ldap: Skipping %s line %i: %s", filename, linenumber, buf);
541                         radlog(L_ERR, "rlm_ldap: Expected 3 tokens "
542                                "(Item type, RADIUS Attribute and LDAP Attribute) but found only %i", token_count);
543                         continue;
544                 }
545
546                 /* create new TLDAP_RADIUS list node */
547                 pair = rad_malloc(sizeof(TLDAP_RADIUS));
548
549                 pair->attr = strdup(ldapAttribute);
550                 pair->radius_attr = strdup(radiusAttribute);
551
552                 if ( (pair->attr == NULL) || (pair->radius_attr == NULL) ) {
553                         radlog(L_ERR, "rlm_ldap: Out of memory");
554                         if (pair->attr) free(pair->attr);
555                         if (pair->radius_attr) free(pair->radius_attr);
556                         free(pair);
557                         fclose(mapfile);
558                         return -1;
559                 }
560                         
561                 /* push node to correct list */
562                 if (strcasecmp(itemType, "checkItem") == 0) {
563                         pair->next = inst->check_item_map;
564                         inst->check_item_map = pair;
565                 } else if (strcasecmp(itemType, "replyItem") == 0) {
566                         pair->next = inst->reply_item_map;
567                         inst->reply_item_map = pair;
568                 } else {
569                         radlog(L_ERR, "rlm_ldap: file %s: skipping line %i: unknown itemType %s", 
570                                filename, linenumber, itemType);
571                         free(pair->attr);
572                         free(pair->radius_attr);
573                         free(pair);
574                         continue;
575                 }
576
577                 DEBUG("rlm_ldap: LDAP %s mapped to RADIUS %s",
578                       pair->attr, pair->radius_attr);
579         }
580         
581         fclose(mapfile);
582
583         return 0; /* success */
584 }
585
586 static int 
587 perform_search(void *instance, LDAP_CONN *conn, char *search_basedn, int scope, char *filter, 
588                 char **attrs, LDAPMessage ** result)
589 {
590         int             res = RLM_MODULE_OK;
591         int             ldap_errno = 0;
592         ldap_instance  *inst = instance;
593         int             search_retry = 0;
594
595         *result = NULL;
596
597         if (!conn){
598                 radlog(L_ERR, "rlm_ldap: NULL connection handle passed");
599                 return RLM_MODULE_FAIL;
600         }
601         if (conn->failed_conns > MAX_FAILED_CONNS_START){
602                 conn->failed_conns++;
603                 if (conn->failed_conns >= MAX_FAILED_CONNS_END){
604                         conn->failed_conns = MAX_FAILED_CONNS_RESTART;
605                         conn->bound = 0;
606                 }
607         }
608 retry:
609         if (!conn->bound || conn->ld == NULL) {
610                 DEBUG2("rlm_ldap: attempting LDAP reconnection");
611                 if (conn->ld){
612                         DEBUG2("rlm_ldap: closing existing LDAP connection");
613                         ldap_unbind_s(conn->ld);
614                 }
615                 if ((conn->ld = ldap_connect(instance, inst->login, inst->password, 0, &res)) == NULL) {
616                         radlog(L_ERR, "rlm_ldap: (re)connection attempt failed");
617                         if (search_retry == 0)
618                                 conn->failed_conns++;
619                         return (RLM_MODULE_FAIL);
620                 }
621                 conn->bound = 1;
622                 conn->failed_conns = 0;
623         }
624         DEBUG2("rlm_ldap: performing search in %s, with filter %s", search_basedn ? search_basedn : "(null)" , filter);
625         switch (ldap_search_st(conn->ld, search_basedn, scope, filter, attrs, 0, &(inst->timeout), result)) {
626         case LDAP_SUCCESS:
627         case LDAP_NO_SUCH_OBJECT:
628                 break;
629         case LDAP_SERVER_DOWN:
630                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: LDAP connection lost.");
631                 conn->failed_conns++;
632                 if (search_retry == 0){
633                         if (conn->failed_conns <= MAX_FAILED_CONNS_START){
634                                 radlog(L_INFO, "rlm_ldap: Attempting reconnect");
635                                 search_retry = 1;
636                                 conn->bound = 0;
637                                 ldap_msgfree(*result);  
638                                 goto retry;
639                         }
640                 }
641                 ldap_msgfree(*result);
642                 return RLM_MODULE_FAIL;
643         case LDAP_INSUFFICIENT_ACCESS:
644                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Insufficient access. Check the identity and password configuration directives.");
645                 ldap_msgfree(*result);
646                 return RLM_MODULE_FAIL;
647         case LDAP_TIMEOUT:
648                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Timed out while waiting for server to respond. Please increase the timeout.");
649                 ldap_msgfree(*result);
650                 return RLM_MODULE_FAIL;
651         case LDAP_FILTER_ERROR:
652                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Bad search filter: %s",filter);
653                 ldap_msgfree(*result);
654                 return RLM_MODULE_FAIL;
655         case LDAP_TIMELIMIT_EXCEEDED:
656         case LDAP_BUSY:
657         case LDAP_UNAVAILABLE:
658                 /* We don't need to reconnect in these cases so we don't set conn->bound */
659                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
660                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: %s", ldap_err2string(ldap_errno));
661                 ldap_msgfree(*result);  
662                 return (RLM_MODULE_FAIL);
663         default:
664                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
665                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: %s", ldap_err2string(ldap_errno));
666                 conn->bound = 0;
667                 ldap_msgfree(*result);  
668                 return (RLM_MODULE_FAIL);
669         }
670
671         if ((ldap_count_entries(conn->ld, *result)) != 1) {
672                 DEBUG("rlm_ldap: object not found or got ambiguous search result");
673                 res = RLM_MODULE_NOTFOUND;
674                 ldap_msgfree(*result);  
675         }
676         return res;
677 }
678
679
680 /*
681  *      Translate the LDAP queries.
682  */
683 static int ldap_escape_func(char *out, int outlen, const char *in)
684 {
685         int len = 0;
686         
687         while (in[0]) {
688                 /*
689                  *  Only one byte left.
690                  */
691                 if (outlen <= 1) {
692                         break;
693                 }
694                 
695                 if (strchr("*", *in)) {
696                         in++;
697                         outlen--;
698                         continue;
699                 }
700                 
701                 /*
702                  *      Else it's a nice character.
703                  */
704                 *out = *in;
705                 out++;
706                 in++;
707                 outlen--;
708                 len++;
709         }
710         *out = '\0';
711         return len;
712 }
713
714 /*
715  * ldap_groupcmp(). Implement the Ldap-Group == "group" filter
716  */
717
718 static int ldap_groupcmp(void *instance, REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check,
719                 VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
720 {
721         char            filter[MAX_FILTER_STR_LEN];
722         char            gr_filter[MAX_FILTER_STR_LEN];
723         int             res;
724         LDAPMessage     *result = NULL;
725         LDAPMessage     *msg = NULL;
726         char            basedn[MAX_FILTER_STR_LEN];
727         char            *attrs[] = {"dn",NULL};
728         char            **vals;
729         ldap_instance   *inst = instance;
730         char            *group_attrs[] = {inst->groupmemb_attr,NULL};
731         LDAP_CONN       *conn;
732         int             conn_id = -1;
733         VALUE_PAIR      *vp_user_dn;
734         VALUE_PAIR      **request_pairs;
735
736         request_pairs = &req->packet->vps;
737
738         DEBUG("rlm_ldap: Entering ldap_groupcmp()");
739
740         if (check->strvalue == NULL || check->length == 0){
741                 DEBUG("rlm_ldap::ldap_groupcmp: Illegal group name");
742                 return 1;
743         }
744
745         if (req == NULL){
746                 DEBUG("rlm_ldap::ldap_groupcmp: NULL request");
747                 return 1;
748         }
749
750         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn, req, NULL)) {
751                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create basedn.");
752                 return 1;
753         }
754
755         while((vp_user_dn = pairfind(*request_pairs, PW_LDAP_USERDN)) == NULL){
756                 char            *user_dn = NULL;
757
758                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
759                                         req, ldap_escape_func)){
760                         DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter");
761                         return 1;
762                 }
763                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
764                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
765                         return 1;
766                 }
767                 if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
768                                         filter, attrs, &result)) != RLM_MODULE_OK){
769                         DEBUG("rlm_ldap::ldap_groupcmp: search failed");
770                         ldap_release_conn(conn_id,inst->conns);
771                         return 1;
772                 }
773                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
774                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
775                         ldap_release_conn(conn_id,inst->conns);
776                         ldap_msgfree(result);
777                         return 1;
778                 }
779                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
780                         DEBUG("rlm_ldap:ldap_groupcmp:: ldap_get_dn() failed");
781                         ldap_release_conn(conn_id,inst->conns);
782                         ldap_msgfree(result);
783                         return 1;
784                 }
785                 ldap_release_conn(conn_id,inst->conns);
786                 /*
787                 * Adding new attribute containing DN for LDAP object associated with
788                 * given username
789                 */
790                 pairadd(request_pairs, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
791                 ldap_memfree(user_dn);
792                 ldap_msgfree(result);
793         }
794
795         if(!radius_xlat(gr_filter, sizeof(gr_filter), inst->groupmemb_filt, req, NULL)){
796                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter.");
797                 return 1;
798         }
799
800         if (strchr((char *)check->strvalue,',') != NULL) {
801                 /* This looks like a DN */
802                 snprintf(filter,sizeof(filter), "%s",gr_filter);
803                 snprintf(basedn,sizeof(basedn), "%s",(char *)check->strvalue);
804         } else 
805                 snprintf(filter,sizeof(filter), "(&(%s=%s)%s)",inst->groupname_attr,(char *)check->strvalue,gr_filter);
806
807         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
808                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
809                 return 1;
810         }
811         
812         if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
813                                 filter, attrs, &result)) == RLM_MODULE_OK){
814                 DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",
815                                 (char *)check->strvalue);
816                 ldap_msgfree(result);
817                 ldap_release_conn(conn_id,inst->conns);
818                 return 0;
819         }
820         
821         ldap_release_conn(conn_id,inst->conns);
822
823         if (res != RLM_MODULE_NOTFOUND ) {
824                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
825                 return 1;
826         }
827
828         if (inst->groupmemb_attr == NULL){
829                 /* search returned NOTFOUND and searching for membership 
830                  * using user object attributes is not specified in config
831                  * file
832                  */
833                 DEBUG("rlm_ldap::ldap_groupcmp: Group %s not found or user is not a member.",(char *)check->strvalue);
834                 return 1;
835         }
836
837         snprintf(filter,sizeof(filter), "(objectclass=*)");
838         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
839                 radlog(L_ERR, "rlm_ldap: Add ldap connections are in use");
840                 return 1;
841         }
842         if ((res = perform_search(inst, conn, vp_user_dn->strvalue, LDAP_SCOPE_BASE,
843                                         filter, group_attrs,&result)) != RLM_MODULE_OK){
844                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
845                 ldap_release_conn(conn_id, inst->conns);
846                 return 1;
847         }               
848
849         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
850                 DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
851                 ldap_release_conn(conn_id,inst->conns);
852                 ldap_msgfree(result);
853                 return 1;
854         }
855         if ((vals = ldap_get_values(conn->ld, msg, inst->groupmemb_attr)) != NULL) {
856                 unsigned int i = 0;
857                 char found = 0;
858                 for (;i < ldap_count_values(vals);i++){
859                         if (strchr(vals[i],',') != NULL){ 
860                                 /* This looks like a DN */
861                                 LDAPMessage *gr_result = NULL;
862                                 snprintf(filter,sizeof(filter), "(%s=%s)",
863                                         inst->groupname_attr,
864                                         (char *)check->strvalue);
865                                 if ((res = perform_search(inst, conn, vals[i],
866                                                 LDAP_SCOPE_BASE, filter,
867                                                 attrs, &gr_result)) != RLM_MODULE_OK){
868                                         if (res != RLM_MODULE_NOTFOUND){
869                                                 DEBUG("rlm_ldap::ldap_groupcmp: \
870                                                         Search returned error");
871                                                 ldap_value_free(vals);
872                                                 ldap_msgfree(result);
873                                                 ldap_release_conn(conn_id,inst->conns);
874                                                 return 1;
875                                         }
876                                 } else {
877                                         ldap_msgfree(gr_result);
878                                         found = 1;
879                                         break;
880                                 }
881                         } else {
882                                 if (strcmp(vals[i],(char *)check->strvalue) == 0){
883                                         found = 1;
884                                         break;
885                                 }
886                         }
887                 }
888                 ldap_value_free(vals);
889                 ldap_msgfree(result);
890                 if (found == 0){
891                         DEBUG("rlm_ldap::groupcmp: Group %s not found \
892                                 or user not a member",
893                                 (char *)check->strvalue);
894                         ldap_release_conn(conn_id,inst->conns);
895                         return 1;
896                 }
897         } else {
898                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_get_values() failed");
899                         ldap_msgfree(result);
900                         ldap_release_conn(conn_id,inst->conns);
901                         return 1;
902         }
903
904         DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",(char *)check->strvalue);
905         ldap_release_conn(conn_id,inst->conns);
906
907         return 0;
908 }
909
910 /*
911  * ldap_xlat()
912  * Do an xlat on an LDAP URL
913  */
914
915 static int ldap_xlat(void *instance, REQUEST *request, char *fmt, char *out, int freespace,
916                                 RADIUS_ESCAPE_STRING func)
917 {
918         char url[MAX_FILTER_STR_LEN];
919         int res;
920         int ret = 0;
921         ldap_instance *inst = instance;
922         LDAPURLDesc *ldap_url;
923         LDAPMessage *result = NULL;
924         LDAPMessage *msg = NULL;
925         char **vals;
926         int conn_id = -1;
927         LDAP_CONN *conn;
928
929         DEBUG("rlm_ldap: - ldap_xlat");
930         if (!radius_xlat(url, sizeof(url), fmt, request, func)) {
931                 radlog (L_ERR, "rlm_ldap: Unable to create LDAP URL.\n");
932                 return 0;
933         }
934         if (!ldap_is_ldap_url(url)){
935                 radlog (L_ERR, "rlm_ldap: String passed does not look like an LDAP URL.\n");
936                 return 0;
937         }
938         if (ldap_url_parse(url,&ldap_url)){
939                 radlog (L_ERR, "rlm_ldap: LDAP URL parse failed.\n");
940                 return 0;
941         }
942         if (ldap_url->lud_attrs == NULL || ldap_url->lud_attrs[0] == NULL || \
943                 ( ldap_url->lud_attrs[1] != NULL || ( ! strlen(ldap_url->lud_attrs[0]) || \
944                 ! strcmp(ldap_url->lud_attrs[0],"*") ) ) ){
945                 radlog (L_ERR, "rlm_ldap: Invalid Attribute(s) request.\n");
946                 ldap_free_urldesc(ldap_url);
947                 return 0;
948         }
949         if (ldap_url->lud_host){
950                 if (strncmp(inst->server,ldap_url->lud_host,strlen(inst->server)) != 0 || \
951                                 ldap_url->lud_port != inst->port){
952                         DEBUG("rlm_ldap: Requested server/port is not known to this module instance.");
953                         ldap_free_urldesc(ldap_url);
954                         return 0;
955                 }
956         }
957         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
958                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
959                 ldap_free_urldesc(ldap_url);
960                 return 0;
961         }
962         if ((res = perform_search(inst, conn, ldap_url->lud_dn, ldap_url->lud_scope, ldap_url->lud_filter, ldap_url->lud_attrs, &result)) != RLM_MODULE_OK){
963                 if (res == RLM_MODULE_NOTFOUND){
964                         DEBUG("rlm_ldap: Search returned not found");
965                         ldap_free_urldesc(ldap_url);
966                         ldap_release_conn(conn_id,inst->conns);
967                         return 0;
968                 }
969                 DEBUG("rlm_ldap: Search returned error");
970                 ldap_free_urldesc(ldap_url);
971                 ldap_release_conn(conn_id,inst->conns);
972                 return 0;
973         }
974         if ((msg = ldap_first_entry(conn->ld, result)) == NULL){
975                 DEBUG("rlm_ldap: ldap_first_entry() failed");
976                 ldap_msgfree(result);
977                 ldap_free_urldesc(ldap_url);
978                 ldap_release_conn(conn_id,inst->conns);
979                 return 0;
980         }
981         if ((vals = ldap_get_values(conn->ld, msg, ldap_url->lud_attrs[0])) != NULL) {
982                 ret = strlen(vals[0]);
983                 if (ret > freespace){
984                         DEBUG("rlm_ldap: Insufficient string space");
985                         ldap_free_urldesc(ldap_url);
986                         ldap_value_free(vals);
987                         ldap_msgfree(result);
988                         ldap_release_conn(conn_id,inst->conns);
989                         return 0;
990                 }
991                 DEBUG("rlm_ldap: Adding attribute %s, value: %s",ldap_url->lud_attrs[0],vals[0]);
992                 strncpy(out,vals[0],ret);
993                 ldap_value_free(vals);
994         }
995         else
996                 ret = 0;
997
998         ldap_msgfree(result);
999         ldap_free_urldesc(ldap_url);
1000         ldap_release_conn(conn_id,inst->conns);
1001
1002         DEBUG("rlm_ldap: - ldap_xlat end");
1003
1004         return ret;
1005 }
1006
1007
1008 /******************************************************************************
1009  *
1010  *      Function: rlm_ldap_authorize
1011  *
1012  *      Purpose: Check if user is authorized for remote access
1013  *
1014  ******************************************************************************/
1015 static int 
1016 ldap_authorize(void *instance, REQUEST * request)
1017 {
1018         LDAPMessage     *result = NULL;
1019         LDAPMessage     *msg = NULL;
1020         LDAPMessage     *def_msg = NULL;
1021         LDAPMessage     *def_attr_msg = NULL;
1022         LDAPMessage     *def_result = NULL;
1023         LDAPMessage     *def_attr_result = NULL;
1024         ldap_instance   *inst = instance;
1025         char            *user_dn = NULL;
1026         char            filter[MAX_FILTER_STR_LEN];
1027         char            basedn[MAX_FILTER_STR_LEN];
1028         VALUE_PAIR      *check_tmp;
1029         VALUE_PAIR      *reply_tmp;
1030         int             res;
1031         VALUE_PAIR      **check_pairs, **reply_pairs;
1032         char            **vals;
1033         VALUE_PAIR      *module_fmsg_vp;
1034         VALUE_PAIR      *user_profile;
1035         char            module_fmsg[MAX_STRING_LEN];
1036         LDAP_CONN       *conn;
1037         int             conn_id = -1;
1038
1039         DEBUG("rlm_ldap: - authorize");
1040
1041         if (!request->username){
1042                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1043                 return RLM_MODULE_INVALID;
1044         }
1045
1046         check_pairs = &request->config_items;
1047         reply_pairs = &request->reply->vps;
1048
1049         /*
1050          * Check for valid input, zero length names not permitted
1051          */
1052         if (request->username->strvalue == 0) {
1053                 radlog(L_ERR, "rlm_ldap: zero length username not permitted\n");
1054                 return RLM_MODULE_INVALID;
1055         }
1056         DEBUG("rlm_ldap: performing user authorization for %s",
1057                request->username->strvalue);
1058
1059         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1060                          request, ldap_escape_func)) {
1061                 radlog (L_ERR, "rlm_ldap: unable to create filter.\n");
1062                 return RLM_MODULE_INVALID;
1063         }
1064
1065         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1066                          request, NULL)) {
1067                 radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1068                 return RLM_MODULE_INVALID;
1069         }
1070
1071         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1072                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1073                 return RLM_MODULE_FAIL;
1074         }
1075         if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, inst->atts, &result)) != RLM_MODULE_OK) {
1076                 DEBUG("rlm_ldap: search failed");
1077                 if (res == RLM_MODULE_NOTFOUND){
1078                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1079                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1080                         pairadd(&request->packet->vps, module_fmsg_vp);
1081                 }
1082                 ldap_release_conn(conn_id,inst->conns);
1083                 return (res);
1084         }
1085         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1086                 DEBUG("rlm_ldap: ldap_first_entry() failed");
1087                 ldap_msgfree(result);
1088                 ldap_release_conn(conn_id,inst->conns);
1089                 return RLM_MODULE_FAIL;
1090         }
1091         if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1092                 DEBUG("rlm_ldap: ldap_get_dn() failed");
1093                 ldap_msgfree(result);
1094                 ldap_release_conn(conn_id,inst->conns);
1095                 return RLM_MODULE_FAIL;
1096         }
1097         /*
1098          * Adding new attribute containing DN for LDAP object associated with
1099          * given username
1100          */
1101         pairadd(&request->packet->vps, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1102         ldap_memfree(user_dn);
1103
1104
1105         /* Remote access is controled by attribute of the user object */
1106         if (inst->access_attr) {
1107                 if ((vals = ldap_get_values(conn->ld, msg, inst->access_attr)) != NULL) {
1108                         if (inst->default_allow){
1109                                 DEBUG("rlm_ldap: checking if remote access for %s is allowed by %s", request->username->strvalue, inst->access_attr);
1110                                 if (!strncmp(vals[0], "FALSE", 5)) {
1111                                         DEBUG("rlm_ldap: dialup access disabled");
1112                                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1113                                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1114                                         pairadd(&request->packet->vps, module_fmsg_vp);
1115                                         ldap_msgfree(result);
1116                                         ldap_value_free(vals);
1117                                         ldap_release_conn(conn_id,inst->conns);
1118                                         return RLM_MODULE_USERLOCK;
1119                                 }
1120                                 ldap_value_free(vals);
1121                         }
1122                         else{
1123                                 DEBUG("rlm_ldap: %s attribute exists - access denied by default", inst->access_attr);
1124                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1125                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1126                                 pairadd(&request->packet->vps, module_fmsg_vp);
1127                                 ldap_msgfree(result);
1128                                 ldap_value_free(vals);
1129                                 ldap_release_conn(conn_id,inst->conns);
1130                                 return RLM_MODULE_USERLOCK;
1131                         }
1132                 } else {
1133                         if (inst->default_allow){
1134                                 DEBUG("rlm_ldap: no %s attribute - access denied by default", inst->access_attr);
1135                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1136                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1137                                 pairadd(&request->packet->vps, module_fmsg_vp);
1138                                 ldap_msgfree(result);
1139                                 ldap_release_conn(conn_id,inst->conns);
1140                                 return RLM_MODULE_USERLOCK;
1141                         }
1142                 }
1143         }
1144
1145         /*
1146          * Check for the default profile entry. If it exists then add the 
1147          * attributes it contains in the check and reply pairs
1148          */
1149
1150         user_profile = pairfind(request->config_items, PW_USER_PROFILE);
1151         if (inst->default_profile || user_profile){
1152                 char *profile = inst->default_profile;
1153
1154                 strNcpy(filter,"(objectclass=radiusprofile)",sizeof(filter));
1155                 if (user_profile)
1156                         profile = user_profile->strvalue;
1157                 if (profile && strlen(profile)){
1158                         if ((res = perform_search(instance, conn,
1159                                 profile, LDAP_SCOPE_BASE, 
1160                                 filter, inst->atts, &def_result)) == RLM_MODULE_OK){
1161                                 if ((def_msg = ldap_first_entry(conn->ld,def_result))){
1162                                         if ((check_tmp = ldap_pairget(conn->ld,def_msg,inst->check_item_map,check_pairs,1))) {
1163                                                 /*pairadd(check_pairs,check_tmp);*/
1164                                                 pairxlatmove(request, check_pairs, &check_tmp);
1165                                                 pairfree(&check_tmp);
1166                                         }
1167                                         if ((reply_tmp = ldap_pairget(conn->ld,def_msg,inst->reply_item_map,reply_pairs,0))) {
1168                                                 /*pairadd(reply_pairs,reply_tmp);*/
1169                                                 pairxlatmove(request, reply_pairs, &reply_tmp);
1170                                                 pairfree(&reply_tmp);
1171                                         }
1172                                 }
1173                                 ldap_msgfree(def_result);
1174                         } else 
1175                                 DEBUG("rlm_ldap: default_profile/user-profile search failed");
1176                 }
1177         }
1178
1179         /*
1180          * Check for the profile attribute. If it exists, we assume that it 
1181          * contains the DN of an entry containg a profile for the user. That
1182          * way we can have different general profiles for various user groups
1183          * (students,faculty,staff etc)
1184          */
1185
1186         if (inst->profile_attr){
1187                 if ((vals = ldap_get_values(conn->ld, msg, inst->profile_attr)) != NULL) {
1188                         unsigned int i=0;
1189                         strNcpy(filter,"(objectclass=radiusprofile)",sizeof(filter));
1190                         while(vals[i] != NULL && strlen(vals[i])){
1191                                 if ((res = perform_search(instance, conn,
1192                                         vals[i], LDAP_SCOPE_BASE, 
1193                                         filter, inst->atts, &def_attr_result)) == RLM_MODULE_OK){
1194                                         if ((def_attr_msg = ldap_first_entry(conn->ld,def_attr_result))){
1195                                                 if ((check_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->check_item_map,check_pairs,1))) {
1196                                                         /*pairadd(check_pairs,check_tmp);*/
1197                                                         pairxlatmove(request, check_pairs, &check_tmp);
1198                                                         pairfree(&check_tmp);
1199                                                 }
1200                                                 if ((reply_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->reply_item_map,reply_pairs,0))) {
1201                                                         /*pairadd(reply_pairs,reply_tmp);*/
1202                                                         pairxlatmove(request, reply_pairs, &reply_tmp);
1203                                                         pairfree(&reply_tmp);
1204                                                 }
1205                                         }
1206                                         ldap_msgfree(def_attr_result);
1207                                 } else 
1208                                         DEBUG("rlm_ldap: profile_attribute search failed");
1209                                 i++;
1210                         }
1211                         ldap_value_free(vals);
1212                 }
1213         }
1214         if (inst->passwd_attr && strlen(inst->passwd_attr)){
1215                 VALUE_PAIR *passwd_item;
1216
1217                 if ((passwd_item = pairfind(request->config_items, PW_PASSWORD)) == NULL){
1218                         char **passwd_vals;
1219                         char *passwd_val = NULL;
1220                         int passwd_len;
1221
1222                         if ((passwd_vals = ldap_get_values(conn->ld,msg,inst->passwd_attr)) != NULL){
1223                                 unsigned int i=0;
1224                                 while(passwd_vals[i] != NULL){
1225                                         if (strlen(passwd_vals[i])){
1226                                                 passwd_val = passwd_vals[i];
1227
1228                                                 if (inst->passwd_hdr && strlen(inst->passwd_hdr)){
1229                                                         passwd_val = strstr(passwd_val,inst->passwd_hdr);
1230                                                         if (passwd_val != NULL)
1231                                                                 passwd_val += strlen(inst->passwd_hdr);
1232                                                         else
1233                                                                 DEBUG("rlm_ldap: Password header not found in password %s for user %s", passwd_vals[0],request->username->strvalue);
1234                                                 }
1235                                                 if (passwd_val){
1236                                                         if ((passwd_item = paircreate(PW_PASSWORD,PW_TYPE_STRING)) == NULL){
1237                                                                 radlog(L_ERR|L_CONS, "no memory");
1238                                                                 ldap_value_free(passwd_vals);
1239                                                                 ldap_msgfree(result);
1240                                                                 ldap_release_conn(conn_id,inst->conns);
1241                                                                 return RLM_MODULE_FAIL;
1242                                                         }
1243                                                         passwd_len = strlen(passwd_val);
1244                                                         strncpy(passwd_item->strvalue,passwd_val,MAX_STRING_LEN - 1);
1245                                                         passwd_item->length = (passwd_len > (MAX_STRING_LEN - 1)) ? (MAX_STRING_LEN - 1) : passwd_len;
1246                                                         pairadd(&request->config_items,passwd_item);
1247                                                         DEBUG("rlm_ldap: Added password %s in check items",passwd_item->strvalue);
1248                                                 }
1249                                         }
1250                                         i++;
1251                                 }
1252                                 ldap_value_free(passwd_vals);
1253                         }
1254                 }
1255         }
1256
1257
1258
1259         DEBUG("rlm_ldap: looking for check items in directory...");
1260
1261         if ((check_tmp = ldap_pairget(conn->ld, msg, inst->check_item_map,check_pairs,1)) != NULL) {
1262                 /*pairadd(check_pairs,check_tmp);*/
1263                 pairxlatmove(request, check_pairs, &check_tmp);
1264                 pairfree(&check_tmp);
1265         }
1266
1267
1268         DEBUG("rlm_ldap: looking for reply items in directory...");
1269
1270
1271         if ((reply_tmp = ldap_pairget(conn->ld, msg, inst->reply_item_map,reply_pairs,0)) != NULL) {
1272                 /*pairadd(reply_pairs,reply_tmp);*/
1273                 pairxlatmove(request, reply_pairs, &reply_tmp);
1274                 pairfree(&reply_tmp);
1275         }
1276
1277        if (inst->do_comp && paircmp(request,request->packet->vps,*check_pairs,reply_pairs) != 0){
1278                 DEBUG("rlm_ldap: Pairs do not match. Rejecting user.");
1279                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Pairs do not match");
1280                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1281                 pairadd(&request->packet->vps, module_fmsg_vp);
1282                 ldap_msgfree(result);
1283                 ldap_release_conn(conn_id,inst->conns);
1284
1285                 return RLM_MODULE_REJECT;
1286         }
1287
1288         /*
1289          * Module should default to LDAP authentication if no Auth-Type
1290          * specified
1291          */
1292         if (pairfind(*check_pairs, PW_AUTHTYPE) == NULL)
1293                 pairadd(check_pairs, pairmake("Auth-Type", "LDAP", T_OP_EQ));
1294
1295
1296         DEBUG("rlm_ldap: user %s authorized to use remote access",
1297               request->username->strvalue);
1298         ldap_msgfree(result);
1299         ldap_release_conn(conn_id,inst->conns);
1300
1301         return RLM_MODULE_OK;
1302 }
1303
1304 /*****************************************************************************
1305  *
1306  *      Function: rlm_ldap_authenticate
1307  *
1308  *      Purpose: Check the user's password against ldap database
1309  *
1310  *****************************************************************************/
1311 static int 
1312 ldap_authenticate(void *instance, REQUEST * request)
1313 {
1314         LDAP           *ld_user;
1315         LDAPMessage    *result, *msg;
1316         ldap_instance  *inst = instance;
1317         char           *user_dn, *attrs[] = {"uid", NULL};
1318         char            filter[MAX_FILTER_STR_LEN];
1319         char            basedn[MAX_FILTER_STR_LEN];
1320         int             res;
1321         VALUE_PAIR     *vp_user_dn;
1322         VALUE_PAIR      *module_fmsg_vp;
1323         char            module_fmsg[MAX_STRING_LEN];
1324         LDAP_CONN       *conn;
1325         int             conn_id = -1;
1326
1327         DEBUG("rlm_ldap: - authenticate");
1328
1329         /*
1330          * Ensure that we're being passed a plain-text password, and not
1331          * anything else.
1332          */
1333
1334         if (!request->username) {
1335                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1336                 return RLM_MODULE_INVALID;
1337         }
1338
1339         if (!request->password){
1340                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication.");
1341                 return RLM_MODULE_INVALID;
1342         }
1343
1344         if(request->password->attribute != PW_PASSWORD) {
1345                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", request->password->name);
1346                 return RLM_MODULE_INVALID;
1347         }
1348
1349         if (request->password->length == 0) {
1350                 radlog(L_ERR, "rlm_ldap: empty password supplied");
1351                 return RLM_MODULE_INVALID;
1352         }
1353
1354         /*
1355          * Check that we don't have any failed connections. If we do there's no real need
1356          * of runing. Also give it another chance if we have a lot of failed connections.
1357          */
1358         if (inst->failed_conns > MAX_FAILED_CONNS_END)
1359                 inst->failed_conns = 0;
1360         if (inst->failed_conns > MAX_FAILED_CONNS_START){
1361                 inst->failed_conns++;
1362                 return RLM_MODULE_FAIL;
1363         }
1364
1365
1366         DEBUG("rlm_ldap: login attempt by \"%s\" with password \"%s\"", 
1367                request->username->strvalue, request->password->strvalue);
1368
1369         while((vp_user_dn = pairfind(request->packet->vps, PW_LDAP_USERDN)) == NULL) {
1370                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1371                                 request, NULL)) {
1372                         radlog (L_ERR, "rlm_ldap: unable to create filter.\n"); 
1373                         return RLM_MODULE_INVALID;
1374                 }
1375
1376                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1377                                 request, NULL)) {
1378                         radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1379                         return RLM_MODULE_INVALID;
1380                 }
1381
1382                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1383                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1384                         return RLM_MODULE_FAIL;
1385                 }
1386                 if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, &result)) != RLM_MODULE_OK) {
1387                         if (res == RLM_MODULE_NOTFOUND){
1388                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1389                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1390                                 pairadd(&request->packet->vps, module_fmsg_vp);
1391                         }
1392                         ldap_release_conn(conn_id,inst->conns);
1393                         return (res);
1394                 }
1395                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1396                         ldap_msgfree(result);
1397                         ldap_release_conn(conn_id,inst->conns);
1398                         return RLM_MODULE_FAIL;
1399                 }
1400                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1401                         DEBUG("rlm_ldap: ldap_get_dn() failed");
1402                         ldap_msgfree(result);
1403                         ldap_release_conn(conn_id,inst->conns);
1404                         return RLM_MODULE_FAIL;
1405                 }
1406                 ldap_release_conn(conn_id,inst->conns);
1407                 pairadd(&request->packet->vps, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1408                 ldap_memfree(user_dn);
1409                 ldap_msgfree(result);
1410         }
1411
1412         user_dn = vp_user_dn->strvalue;
1413
1414         DEBUG("rlm_ldap: user DN: %s", user_dn);
1415
1416         ld_user = ldap_connect(instance, user_dn, request->password->strvalue,
1417                                1, &res);
1418         if (ld_user == NULL){
1419                 if (res == RLM_MODULE_REJECT){
1420                         inst->failed_conns = 0;
1421                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Bind as user failed");
1422                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1423                         pairadd(&request->packet->vps, module_fmsg_vp);
1424                 }
1425                 if (res == RLM_MODULE_FAIL){
1426                         DEBUG("rlm_ldap: ldap_connect() failed");
1427                         inst->failed_conns++;
1428                 }
1429                 return (res);
1430         }
1431
1432         DEBUG("rlm_ldap: user %s authenticated succesfully",
1433               request->username->strvalue);
1434         ldap_unbind_s(ld_user);
1435         inst->failed_conns = 0;
1436
1437         return RLM_MODULE_OK;
1438 }
1439
1440 static LDAP    *
1441 ldap_connect(void *instance, const char *dn, const char *password, int auth, int *result)
1442 {
1443         ldap_instance  *inst = instance;
1444         LDAP           *ld = NULL;
1445         int             msgid, rc, ldap_version;
1446         int             ldap_errno = 0;
1447         LDAPMessage    *res;
1448
1449         if (inst->is_url){
1450 #ifdef HAVE_LDAP_INITIALIZE
1451                 DEBUG("rlm_ldap: (re)connect to %s, authentication %d", inst->server, auth);
1452                 if (ldap_initialize(&ld, inst->server) != LDAP_SUCCESS) {
1453                         radlog(L_ERR, "rlm_ldap: ldap_initialize() failed");
1454                         *result = RLM_MODULE_FAIL;
1455                         return (NULL);
1456                 }
1457 #endif
1458         }
1459         else{
1460                 DEBUG("rlm_ldap: (re)connect to %s:%d, authentication %d", inst->server, inst->port, auth);
1461                 if ((ld = ldap_init(inst->server, inst->port)) == NULL) {
1462                         radlog(L_ERR, "rlm_ldap: ldap_init() failed");
1463                         *result = RLM_MODULE_FAIL;
1464                         return (NULL);
1465                 }
1466         }
1467         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &(inst->net_timeout)) != LDAP_OPT_SUCCESS) {
1468                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_NETWORK_TIMEOUT %ld.%ld", inst->net_timeout.tv_sec, inst->net_timeout.tv_usec);
1469         }
1470         if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT, (void *) &(inst->timelimit)) != LDAP_OPT_SUCCESS) {
1471                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_TIMELIMIT %d", inst->timelimit);
1472         }
1473         if (inst->ldap_debug && ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(inst->ldap_debug)) != LDAP_OPT_SUCCESS) {
1474                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_DEBUG_LEVEL %d", inst->ldap_debug);
1475         }
1476         ldap_version = LDAP_VERSION3;
1477         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_version) != LDAP_OPT_SUCCESS) {
1478                 radlog(L_ERR, "rlm_ldap: Could not set LDAP version to V3");
1479         }
1480 #ifdef HAVE_LDAP_START_TLS
1481         if(inst->tls_mode) {
1482                 DEBUG("rlm_ldap: setting TLS mode to %d", inst->tls_mode);
1483                 if(ldap_set_option(ld, LDAP_OPT_X_TLS,
1484                            (void *) &(inst->tls_mode)) != LDAP_OPT_SUCCESS) {
1485                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1486                         radlog(L_ERR, "rlm_ldap: could not set LDAP_OPT_X_TLS option %s", ldap_err2string(ldap_errno));
1487                 }
1488         }
1489         if (inst->start_tls) {
1490                 DEBUG("rlm_ldap: starting TLS");
1491                 rc = ldap_start_tls_s(ld, NULL, NULL);
1492                 if (rc != LDAP_SUCCESS) {
1493                         DEBUG("rlm_ldap: ldap_start_tls_s()");
1494                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1495                         radlog(L_ERR, "rlm_ldap: could not start TLS %s", ldap_err2string(ldap_errno));
1496                         *result = RLM_MODULE_FAIL;
1497                         ldap_unbind_s(ld);
1498                         return (NULL);
1499                 }
1500         }
1501 #endif /* HAVE_LDAP_START_TLS */
1502
1503         if (inst->is_url){
1504                 DEBUG("rlm_ldap: bind as %s/%s to %s", dn, password, inst->server);
1505         }
1506         else{
1507                 DEBUG("rlm_ldap: bind as %s/%s to %s:%d", dn, password, inst->server, inst->port);
1508         }
1509         msgid = ldap_bind(ld, dn, password,LDAP_AUTH_SIMPLE);
1510         if (msgid == -1) {
1511                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1512                 if (inst->is_url)
1513                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
1514                                 dn, inst->server, ldap_err2string(ldap_errno));
1515                 else
1516                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
1517                                 dn, inst->server, inst->port,
1518                                 ldap_err2string(ldap_errno));
1519                 *result = RLM_MODULE_FAIL;
1520                 ldap_unbind_s(ld);
1521                 return (NULL);
1522         }
1523         DEBUG("rlm_ldap: waiting for bind result ...");
1524
1525         rc = ldap_result(ld, msgid, 1, &(inst->timeout), &res);
1526
1527         if(rc < 1) {
1528                 DEBUG("rlm_ldap: ldap_result()");
1529                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1530                 if (inst->is_url)
1531                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
1532                                 dn, inst->server, (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
1533                 else
1534                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
1535                                 dn, inst->server, inst->port,
1536                                 (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
1537                 *result = RLM_MODULE_FAIL;
1538                 ldap_unbind_s(ld);
1539                 return (NULL);
1540         }
1541         ldap_errno = ldap_result2error(ld, res, 1);
1542         switch (ldap_errno) {
1543         case LDAP_SUCCESS:
1544                 *result = RLM_MODULE_OK;
1545                 break;
1546
1547         case LDAP_INVALID_CREDENTIALS:
1548                 if (auth) 
1549                         *result = RLM_MODULE_REJECT;
1550                 else {
1551                         radlog(L_ERR, "rlm_ldap: LDAP login failed: check login, password settings in ldap section of radiusd.conf");
1552                         *result = RLM_MODULE_FAIL;
1553                 }               
1554                 break;
1555                 
1556         default:
1557                 if (inst->is_url)
1558                         radlog(L_ERR,"rlm_ldap: %s bind to %s failed %s",
1559                                 dn, inst->server, ldap_err2string(ldap_errno));
1560                 else
1561                         radlog(L_ERR,"rlm_ldap: %s bind to %s:%d failed %s",
1562                                 dn, inst->server, inst->port,
1563                                 ldap_err2string(ldap_errno));
1564                 *result = RLM_MODULE_FAIL;
1565         }
1566
1567         if (*result != RLM_MODULE_OK) {
1568                 ldap_unbind_s(ld);
1569                 ld = NULL;
1570         }
1571         return ld;
1572 }
1573
1574 /*****************************************************************************
1575  *
1576  *      Detach from the LDAP server and cleanup internal state.
1577  *
1578  *****************************************************************************/
1579 static int 
1580 ldap_detach(void *instance)
1581 {
1582         ldap_instance  *inst = instance;
1583         TLDAP_RADIUS *pair, *nextpair;
1584
1585         if (inst->server)
1586                 free((char *) inst->server);
1587         if (inst->login)
1588                 free((char *) inst->login);
1589         if (inst->password)
1590                 free((char *) inst->password);
1591         if (inst->basedn)
1592                 free((char *) inst->basedn);
1593         if (inst->dictionary_mapping)
1594                 free(inst->dictionary_mapping);
1595         if (inst->filter)
1596                 free((char *) inst->filter);
1597         if (inst->passwd_hdr)
1598                 free((char *) inst->passwd_hdr);
1599         if (inst->passwd_attr)
1600                 free((char *) inst->passwd_attr);
1601         if (inst->groupname_attr)
1602                 free((char *) inst->groupname_attr);
1603         if (inst->groupmemb_filt)
1604                 free((char *) inst->groupmemb_filt);
1605         if (inst->groupmemb_attr)
1606                 free((char *) inst->groupmemb_attr);
1607         if (inst->access_attr)
1608                 free((char *) inst->access_attr);
1609         if (inst->profile_attr)
1610                 free((char *) inst->profile_attr);
1611         if (inst->conns){
1612                 int i=0;
1613
1614                 for(;i<inst->num_conns;i++){
1615                         if (inst->conns[i].ld){
1616                                 ldap_unbind_s(inst->conns[i].ld);
1617                         }
1618                         pthread_mutex_destroy(&inst->conns[i].mutex);
1619                 }
1620                 free(inst->conns);
1621         }
1622
1623         pair = inst->check_item_map;
1624         
1625         while (pair != NULL) {
1626                 nextpair = pair->next;
1627                 free(pair->attr);
1628                 free(pair->radius_attr);
1629                 free(pair);
1630                 pair = nextpair;
1631         }
1632
1633         pair = inst->reply_item_map;
1634
1635         while (pair != NULL) {
1636                 nextpair = pair->next;
1637                 free(pair->attr);
1638                 free(pair->radius_attr);
1639                 free(pair);
1640                 pair = nextpair;
1641         }
1642
1643         if (inst->atts)
1644                 free(inst->atts);
1645
1646         paircompare_unregister(PW_LDAP_GROUP, ldap_groupcmp);
1647         xlat_unregister(inst->xlat_name,ldap_xlat);
1648         free(inst->xlat_name);
1649
1650         free(inst);
1651
1652         return 0;
1653 }
1654
1655 #ifdef FIELDCPY
1656 static void 
1657 fieldcpy(char *string, char **uptr)
1658 {
1659         char           *ptr;
1660
1661         ptr = *uptr;
1662         while (*ptr == ' ' || *ptr == '\t') {
1663                 ptr++;
1664         }
1665         if (*ptr == '"') {
1666                 ptr++;
1667                 while (*ptr != '"' && *ptr != '\0' && *ptr != '\n') {
1668                         *string++ = *ptr++;
1669                 }
1670                 *string = '\0';
1671                 if (*ptr == '"') {
1672                         ptr++;
1673                 }
1674                 *uptr = ptr;
1675                 return;
1676         }
1677         while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0' && *ptr != '\n' &&
1678                *ptr != '=' && *ptr != ',') {
1679                 *string++ = *ptr++;
1680         }
1681         *string = '\0';
1682         *uptr = ptr;
1683         return;
1684 }
1685 #endif
1686 /*****************************************************************************
1687  *      Get RADIUS attributes from LDAP object
1688  *      ( according to draft-adoba-radius-05.txt
1689  *        <http://www.ietf.org/internet-drafts/draft-adoba-radius-05.txt> )
1690  *
1691  *****************************************************************************/
1692
1693 static VALUE_PAIR *
1694 ldap_pairget(LDAP * ld, LDAPMessage * entry,
1695              TLDAP_RADIUS * item_map, VALUE_PAIR **pairs,char is_check)
1696 {
1697         char          **vals;
1698         int             vals_count;
1699         int             vals_idx;
1700         char           *ptr;
1701         TLDAP_RADIUS   *element;
1702         LRAD_TOKEN      token;
1703         int             is_generic_attribute;
1704         char            value[256];
1705         VALUE_PAIR     *pairlist = NULL;
1706         VALUE_PAIR     *newpair = NULL;
1707
1708         /* check if there is a mapping from this LDAP attribute to a RADIUS attribute */
1709         for (element = item_map; element != NULL; element = element->next) {
1710         if ((vals = ldap_get_values(ld,entry,element->attr)) != NULL){
1711                         /* check whether this is a one-to-one-mapped ldap attribute or a generic
1712                            attribute and set flag accordingly */
1713
1714                         if (strcasecmp(element->radius_attr, GENERIC_ATTRIBUTE_ID)==0)
1715                                 is_generic_attribute = 1;
1716                         else
1717                                 is_generic_attribute = 0;
1718
1719                         /* find out how many values there are for the attribute and extract all of them */
1720
1721                         vals_count = ldap_count_values(vals);
1722
1723                         for (vals_idx = 0; vals_idx < vals_count; vals_idx++) {
1724                                 ptr = vals[vals_idx];
1725
1726                                 if (is_generic_attribute) {
1727                                         /* this is a generic attribute */
1728                                         LRAD_TOKEN dummy; /* makes pairread happy */
1729                                         
1730                                         /* not sure if using pairread here is ok ... */
1731                                         if ( (newpair = pairread(&ptr, &dummy)) != NULL) {
1732                                                 DEBUG("rlm_ldap: extracted attribute %s from generic item %s", 
1733                                                       newpair->name, vals[vals_idx]);
1734                                                 pairadd(&pairlist, newpair);
1735                                         } else {
1736                                                 radlog(L_ERR, "rlm_ldap: parsing %s failed: %s", 
1737                                                        element->attr, vals[vals_idx]);
1738                                         }
1739                                 } else {
1740                                         /* this is a one-to-one-mapped attribute */
1741                                         token = gettoken(&ptr, value, sizeof(value) - 1);
1742                                         if (token < T_EQSTART || token > T_EQEND) {
1743                                                 token = (is_check) ? T_OP_CMP_EQ : T_OP_EQ;
1744                                         } else {
1745                                                 gettoken(&ptr, value, sizeof(value) - 1);
1746                                         }
1747                                         if (value[0] == 0) {
1748                                                 DEBUG("rlm_ldap: Attribute %s has no value", element->attr);
1749                                                 break;
1750                                         }
1751                                         DEBUG("rlm_ldap: Adding %s as %s, value %s & op=%d", element->attr, element->radius_attr, value, token);
1752                                                 if ((newpair = pairmake(element->radius_attr, value, token)) == NULL)
1753                                                 continue;
1754                                         if (! vals_idx){
1755                                                 pairdelete(pairs,newpair->attribute);
1756                                         }
1757                                         pairadd(&pairlist, newpair);
1758                                 }
1759                         }
1760                         ldap_value_free(vals);
1761                 }
1762         }
1763
1764         return (pairlist);
1765 }
1766
1767 /* globally exported name */
1768 module_t        rlm_ldap = {
1769         "LDAP",
1770         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
1771         NULL,                   /* initialization        */
1772         ldap_instantiate,       /* instantiation         */
1773         {
1774                 ldap_authenticate,      /* authentication        */
1775                 ldap_authorize,         /* authorization         */
1776                 NULL,                   /* preaccounting         */
1777                 NULL,                   /* accounting            */
1778                 NULL,                   /* checksimul            */
1779                 NULL,                   /* pre-proxy             */
1780                 NULL,                   /* post-proxy            */
1781                 NULL                    /* post-auth             */
1782         },
1783         ldap_detach,            /* detach                */
1784         NULL,                   /* destroy               */
1785 };