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