Updated API for 2.2.
[freeradius.git] / src / modules / rlm_ippool / rlm_ippool.c
1 /*
2  * rlm_ippool.c
3  *
4  * Version:  $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2001,2006  The FreeRADIUS server project
21  * Copyright 2002  Kostas Kalevras <kkalev@noc.ntua.gr>
22  *
23  * March 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
24  * - Initial release
25  * April 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
26  * - Add support for the Pool-Name attribute
27  * May 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
28  * - Check the return value of a gdbm_fetch() we didn't check
29  * - Change the nas entry in the ippool_key structure from uint32 to string[64]
30  *   That should allow us to also use the NAS-Identifier attribute
31  * Sep 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
32  * - Move from authorize to post-auth
33  * - Use mutex locks when accessing the gdbm files
34  * - Fail if we don't find nas port information
35  * Oct 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
36  * - Do a memset(0) on the key.nas before doing searches. Nusty bug
37  * Jul 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
38  * - Make Multilink work this time
39  * - Instead of locking file operations, lock transactions. That means we only keep
40  *   one big transaction lock instead of per file locks (mutexes).
41  * Sep 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
42  * - Fix postauth to not leak ip's
43  *   Add an extra attribute in each entry <char extra> signifying if we need to delete this
44  *   entry in the accounting phase. This is only true in case we are doing MPPP
45  *   Various other code changes. Code comments should explain things
46  *   Highly experimental at this phase.
47  * Mar 2004, Kostas Kalevras <kkalev@noc.ntua.gr>
48  * - Add a timestamp and a timeout attribute in ippool_info. When we assign an ip we set timestamp
49  *   to request->timestamp and timeout to %{Session-Timeout:-0}. When we search for a free entry
50  *   we check if timeout has expired. If it has then we free the entry. We also add a maximum
51  *   timeout configuration directive. If it is non zero then we also use that one to free entries.
52  * Jul 2004, Kostas Kalevras <kkalev@noc.ntua.gr>
53  * - If Pool-Name is set to DEFAULT then always run.
54  * Mar 2005, Kostas Kalevras <kkalev@noc.ntua.gr>
55  * - Make the key an MD5 of a configurable xlated string. This closes Bug #42
56  */
57
58 #include <freeradius-devel/ident.h>
59 RCSID("$Id$")
60
61 #include <freeradius-devel/radiusd.h>
62 #include <freeradius-devel/modules.h>
63
64 #include "config.h"
65 #include <ctype.h>
66
67 #include "../../include/md5.h"
68
69 #include <gdbm.h>
70
71 #ifdef NEEDS_GDBM_SYNC
72 #       define GDBM_SYNCOPT GDBM_SYNC
73 #else
74 #       define GDBM_SYNCOPT 0
75 #endif
76
77 #ifdef GDBM_NOLOCK
78 #define GDBM_IPPOOL_OPTS (GDBM_SYNCOPT | GDBM_NOLOCK)
79 #else
80 #define GDBM_IPPOOL_OPTS (GDBM_SYNCOPT)
81 #endif
82
83 #define MAX_NAS_NAME_SIZE 64
84
85 /*
86  *      Define a structure for our module configuration.
87  *
88  *      These variables do not need to be in a structure, but it's
89  *      a lot cleaner to do so, and a pointer to the structure can
90  *      be used as the instance handle.
91  */
92 typedef struct rlm_ippool_t {
93         char *session_db;
94         char *ip_index;
95         char *name;
96         char *key;
97         uint32_t range_start;
98         uint32_t range_stop;
99         uint32_t netmask;
100         time_t max_timeout;
101         int cache_size;
102         int override;
103         GDBM_FILE gdbm;
104         GDBM_FILE ip;
105 #ifdef HAVE_PTHREAD_H
106         pthread_mutex_t op_mutex;
107 #endif
108 } rlm_ippool_t;
109
110 #ifndef HAVE_PTHREAD_H
111 /*
112  *      This is easier than ifdef's throughout the code.
113  */
114 #define pthread_mutex_init(_x, _y)
115 #define pthread_mutex_destroy(_x)
116 #define pthread_mutex_lock(_x)
117 #define pthread_mutex_unlock(_x)
118 #endif
119
120 typedef struct ippool_info {
121         uint32_t        ipaddr;
122         char            active;
123         char            cli[32];
124         char            extra;
125         time_t          timestamp;
126         time_t          timeout;
127 } ippool_info;
128
129 typedef struct ippool_key {
130         char key[16];
131 } ippool_key;
132
133 /*
134  *      A mapping of configuration file names to internal variables.
135  *
136  *      Note that the string is dynamically allocated, so it MUST
137  *      be freed.  When the configuration file parse re-reads the string,
138  *      it free's the old one, and strdup's the new one, placing the pointer
139  *      to the strdup'd string into 'config.string'.  This gets around
140  *      buffer over-flows.
141  */
142 static const CONF_PARSER module_config[] = {
143   { "session-db", PW_TYPE_STRING_PTR, offsetof(rlm_ippool_t,session_db), NULL, NULL },
144   { "ip-index", PW_TYPE_STRING_PTR, offsetof(rlm_ippool_t,ip_index), NULL, NULL },
145   { "key", PW_TYPE_STRING_PTR, offsetof(rlm_ippool_t,key), NULL, "%{NAS-IP-Address} %{NAS-Port}" },
146   { "range-start", PW_TYPE_IPADDR, offsetof(rlm_ippool_t,range_start), NULL, "0" },
147   { "range-stop", PW_TYPE_IPADDR, offsetof(rlm_ippool_t,range_stop), NULL, "0" },
148   { "netmask", PW_TYPE_IPADDR, offsetof(rlm_ippool_t,netmask), NULL, "0" },
149   { "cache-size", PW_TYPE_INTEGER, offsetof(rlm_ippool_t,cache_size), NULL, "1000" },
150   { "override", PW_TYPE_BOOLEAN, offsetof(rlm_ippool_t,override), NULL, "no" },
151   { "maximum-timeout", PW_TYPE_INTEGER, offsetof(rlm_ippool_t,max_timeout), NULL, "0" },
152   { NULL, -1, 0, NULL, NULL }
153 };
154
155 /*
156  *      Do any per-module initialization that is separate to each
157  *      configured instance of the module.  e.g. set up connections
158  *      to external databases, read configuration files, set up
159  *      dictionary entries, etc.
160  *
161  *      If configuration information is given in the config section
162  *      that must be referenced in later calls, store a handle to it
163  *      in *instance otherwise put a null pointer there.
164  */
165 static int ippool_instantiate(CONF_SECTION *conf, void **instance)
166 {
167         rlm_ippool_t *data;
168         int cache_size;
169         ippool_info entry;
170         ippool_key key;
171         datum key_datum;
172         datum data_datum;
173         const char *cli = "0";
174         const char *pool_name = NULL;
175
176         /*
177          *      Set up a storage area for instance data
178          */
179         data = rad_malloc(sizeof(*data));
180         if (!data) {
181                 return -1;
182         }
183         memset(data, 0, sizeof(*data));
184
185         /*
186          *      If the configuration parameters can't be parsed, then
187          *      fail.
188          */
189         if (cf_section_parse(conf, data, module_config) < 0) {
190                 free(data);
191                 return -1;
192         }
193         cache_size = data->cache_size;
194
195         if (data->session_db == NULL) {
196                 radlog(L_ERR, "rlm_ippool: 'session-db' must be set.");
197                 free(data);
198                 return -1;
199         }
200         if (data->ip_index == NULL) {
201                 radlog(L_ERR, "rlm_ippool: 'ip-index' must be set.");
202                 free(data);
203                 return -1;
204         }
205         data->range_start = htonl(data->range_start);
206         data->range_stop = htonl(data->range_stop);
207         data->netmask = htonl(data->netmask);
208         if (data->range_start == 0 || data->range_stop == 0 || \
209                          data->range_start >= data->range_stop ) {
210                 radlog(L_ERR, "rlm_ippool: Invalid configuration data given.");
211                 free(data);
212                 return -1;
213         }
214
215         data->gdbm = gdbm_open(data->session_db, sizeof(int),
216                         GDBM_WRCREAT | GDBM_IPPOOL_OPTS, 0600, NULL);
217         if (data->gdbm == NULL) {
218                 radlog(L_ERR, "rlm_ippool: Failed to open file %s: %s",
219                                 data->session_db, strerror(errno));
220                 return -1;
221         }
222         data->ip = gdbm_open(data->ip_index, sizeof(int),
223                         GDBM_WRCREAT | GDBM_IPPOOL_OPTS, 0600, NULL);
224         if (data->ip == NULL) {
225                 radlog(L_ERR, "rlm_ippool: Failed to open file %s: %s",
226                                 data->ip_index, strerror(errno));
227                 return -1;
228         }
229         if (gdbm_setopt(data->gdbm, GDBM_CACHESIZE, &cache_size, sizeof(int)) == -1)
230                 radlog(L_ERR, "rlm_ippool: Failed to set cache size");
231         if (gdbm_setopt(data->ip, GDBM_CACHESIZE, &cache_size, sizeof(int)) == -1)
232                 radlog(L_ERR, "rlm_ippool: Failed to set cache size");
233
234         key_datum = gdbm_firstkey(data->gdbm);
235         if (key_datum.dptr == NULL){
236                         /*
237                          * If the database does not exist initialize it.
238                          * We set the nas/port pairs to not existent values and
239                          * active = 0
240                          */
241                 int rcode;
242                 uint32_t i, j;
243                 uint32_t or_result;
244                 char str[32];
245                 char init_str[17];
246
247                 DEBUG("rlm_ippool: Initializing database");
248                 for(i=data->range_start,j=~0;i<=data->range_stop;i++,j--){
249
250                         /*
251                          * Net and Broadcast addresses are excluded
252                          */
253                         or_result = i | data->netmask;
254                         if (~data->netmask != 0 &&
255                                 (or_result == data->netmask ||
256                             (~or_result == 0))) {
257                                 DEBUG("rlm_ippool: IP %s excluded",
258                                       ip_ntoa(str, ntohl(i)));
259                                 continue;
260                         }
261
262                         sprintf(init_str,"%016d",j);
263                         DEBUG("rlm_ippool: Initialized bucket: %s",init_str);
264                         memcpy(key.key, init_str,16);
265                         key_datum.dptr = (char *) &key;
266                         key_datum.dsize = sizeof(ippool_key);
267
268                         entry.ipaddr = ntohl(i);
269                         entry.active = 0;
270                         entry.extra = 0;
271                         entry.timestamp = 0;
272                         entry.timeout = 0;
273                         strcpy(entry.cli,cli);
274
275                         data_datum.dptr = (char *) &entry;
276                         data_datum.dsize = sizeof(ippool_info);
277
278                         rcode = gdbm_store(data->gdbm, key_datum, data_datum, GDBM_REPLACE);
279                         if (rcode < 0) {
280                                 radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
281                                                 data->session_db, gdbm_strerror(gdbm_errno));
282                                 gdbm_close(data->gdbm);
283                                 gdbm_close(data->ip);
284                                 free(data);
285                                 return -1;
286                         }
287                 }
288         }
289         else
290                 free(key_datum.dptr);
291
292         /* Add the ip pool name */
293         data->name = NULL;
294         pool_name = cf_section_name2(conf);
295         if (pool_name != NULL)
296                 data->name = strdup(pool_name);
297
298         pthread_mutex_init(&data->op_mutex, NULL);
299         *instance = data;
300
301         return 0;
302 }
303
304
305 /*
306  *      Check for an Accounting-Stop
307  *      If we find one and we have allocated an IP to this nas/port combination, deallocate it.
308  */
309 static int ippool_accounting(void *instance, REQUEST *request)
310 {
311         rlm_ippool_t *data = (rlm_ippool_t *)instance;
312         datum key_datum;
313         datum data_datum;
314         datum save_datum;
315         int acctstatustype = 0;
316         int rcode;
317         ippool_info entry;
318         ippool_key key;
319         int num = 0;
320         VALUE_PAIR *vp;
321         char str[32];
322         uint8_t key_str[17];
323         char hex_str[35];
324         char xlat_str[MAX_STRING_LEN];
325         FR_MD5_CTX md5_context;
326
327
328         if ((vp = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0)) != NULL)
329                 acctstatustype = vp->vp_integer;
330         else {
331                 RDEBUG("Could not find account status type in packet. Return NOOP.");
332                 return RLM_MODULE_NOOP;
333         }
334         switch(acctstatustype){
335                 case PW_STATUS_STOP:
336                         if (!radius_xlat(xlat_str,MAX_STRING_LEN,data->key, request, NULL)){
337                                 RDEBUG("xlat on the 'key' directive failed");
338                                 return RLM_MODULE_NOOP;
339                         }
340                         fr_MD5Init(&md5_context);
341                         fr_MD5Update(&md5_context, xlat_str, strlen(xlat_str));
342                         fr_MD5Final(key_str, &md5_context);
343                         key_str[16] = '\0';
344                         fr_bin2hex(key_str,hex_str,16);
345                         hex_str[32] = '\0';
346                         RDEBUG("MD5 on 'key' directive maps to: %s",hex_str);
347                         memcpy(key.key,key_str,16);
348                         break;
349                 default:
350                         /* We don't care about any other accounting packet */
351                         RDEBUG("This is not an Accounting-Stop. Return NOOP.");
352
353                         return RLM_MODULE_NOOP;
354         }
355
356         RDEBUG("Searching for an entry for key: '%s'",xlat_str);
357         key_datum.dptr = (char *) &key;
358         key_datum.dsize = sizeof(ippool_key);
359
360         pthread_mutex_lock(&data->op_mutex);
361         data_datum = gdbm_fetch(data->gdbm, key_datum);
362         if (data_datum.dptr != NULL){
363
364                 /*
365                  * If the entry was found set active to zero
366                  */
367                 memcpy(&entry, data_datum.dptr, sizeof(ippool_info));
368                 free(data_datum.dptr);
369                 RDEBUG("Deallocated entry for ip: %s",ip_ntoa(str,entry.ipaddr));
370                 entry.active = 0;
371                 entry.timestamp = 0;
372                 entry.timeout = 0;
373
374                 /*
375                  * Save the reference to the entry
376                  */
377                 save_datum.dptr = key_datum.dptr;
378                 save_datum.dsize = key_datum.dsize;
379
380                 data_datum.dptr = (char *) &entry;
381                 data_datum.dsize = sizeof(ippool_info);
382
383                 rcode = gdbm_store(data->gdbm, key_datum, data_datum, GDBM_REPLACE);
384                 if (rcode < 0) {
385                         radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
386                                         data->session_db, gdbm_strerror(gdbm_errno));
387                         pthread_mutex_unlock(&data->op_mutex);
388                         return RLM_MODULE_FAIL;
389                 }
390
391                 /*
392                  * Decrease allocated count from the ip index
393                  */
394                 key_datum.dptr = (char *) &entry.ipaddr;
395                 key_datum.dsize = sizeof(uint32_t);
396                 data_datum = gdbm_fetch(data->ip, key_datum);
397                 if (data_datum.dptr != NULL){
398                         memcpy(&num, data_datum.dptr, sizeof(int));
399                         free(data_datum.dptr);
400                         if (num >0){
401                                 num--;
402                                 RDEBUG("num: %d",num);
403                                 data_datum.dptr = (char *) &num;
404                                 data_datum.dsize = sizeof(int);
405                                 rcode = gdbm_store(data->ip, key_datum, data_datum, GDBM_REPLACE);
406                                 if (rcode < 0) {
407                                         radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
408                                                         data->ip_index, gdbm_strerror(gdbm_errno));
409                                         pthread_mutex_unlock(&data->op_mutex);
410                                         return RLM_MODULE_FAIL;
411                                 }
412                                 if (num >0 && entry.extra == 1){
413                                         /*
414                                          * We are doing MPPP and we still have nas/port entries referencing
415                                          * this ip. Delete this entry so that eventually we only keep one
416                                          * reference to this ip.
417                                          */
418                                         gdbm_delete(data->gdbm,save_datum);
419                                 }
420                         }
421                 }
422                 pthread_mutex_unlock(&data->op_mutex);
423         }
424         else{
425                 pthread_mutex_unlock(&data->op_mutex);
426                 RDEBUG("Entry not found");
427         }
428
429         return RLM_MODULE_OK;
430 }
431
432 static int ippool_postauth(void *instance, REQUEST *request)
433 {
434         rlm_ippool_t *data = (rlm_ippool_t *) instance;
435         int delete = 0;
436         int found = 0;
437         int mppp = 0;
438         int extra = 0;
439         int rcode;
440         int num = 0;
441         datum key_datum;
442         datum nextkey;
443         datum data_datum;
444         datum save_datum;
445         ippool_key key;
446         ippool_info entry;
447         VALUE_PAIR *vp;
448         char *cli = NULL;
449         char str[32];
450         uint8_t key_str[17];
451         char hex_str[35];
452         char xlat_str[MAX_STRING_LEN];
453         FR_MD5_CTX md5_context;
454
455
456         /* quiet the compiler */
457         instance = instance;
458         request = request;
459
460         /* Check if Pool-Name attribute exists. If it exists check our name and
461          * run only if they match
462          */
463         if ((vp = pairfind(request->config_items, PW_POOL_NAME, 0)) != NULL){
464                 if (data->name == NULL || (strcmp(data->name,vp->vp_strvalue) && strcmp(vp->vp_strvalue,"DEFAULT")))
465                         return RLM_MODULE_NOOP;
466         } else {
467                 RDEBUG("Could not find Pool-Name attribute.");
468                 return RLM_MODULE_NOOP;
469         }
470
471
472         /*
473          * Find the caller id
474          */
475         if ((vp = pairfind(request->packet->vps, PW_CALLING_STATION_ID, 0)) != NULL)
476                 cli = vp->vp_strvalue;
477
478
479         if (!radius_xlat(xlat_str,MAX_STRING_LEN,data->key, request, NULL)){
480                 RDEBUG("xlat on the 'key' directive failed");
481                 return RLM_MODULE_NOOP;
482         }
483         fr_MD5Init(&md5_context);
484         fr_MD5Update(&md5_context, xlat_str, strlen(xlat_str));
485         fr_MD5Final(key_str, &md5_context);
486         key_str[16] = '\0';
487         fr_bin2hex(key_str,hex_str,16);
488         hex_str[32] = '\0';
489         RDEBUG("MD5 on 'key' directive maps to: %s",hex_str);
490         memcpy(key.key,key_str,16);
491
492         RDEBUG("Searching for an entry for key: '%s'",hex_str);
493         key_datum.dptr = (char *) &key;
494         key_datum.dsize = sizeof(ippool_key);
495
496         pthread_mutex_lock(&data->op_mutex);
497         data_datum = gdbm_fetch(data->gdbm, key_datum);
498         if (data_datum.dptr != NULL){
499                 /*
500                  * If there is a corresponding entry in the database with active=1 it is stale.
501                  * Set active to zero
502                  */
503                 found = 1;
504                 memcpy(&entry, data_datum.dptr, sizeof(ippool_info));
505                 free(data_datum.dptr);
506                 if (entry.active){
507                         RDEBUG("Found a stale entry for ip: %s",ip_ntoa(str,entry.ipaddr));
508                         entry.active = 0;
509                         entry.timestamp = 0;
510                         entry.timeout = 0;
511
512                         /*
513                          * Save the reference to the entry
514                          */
515                         save_datum.dptr = key_datum.dptr;
516                         save_datum.dsize = key_datum.dsize;
517
518                         data_datum.dptr = (char *) &entry;
519                         data_datum.dsize = sizeof(ippool_info);
520
521                         rcode = gdbm_store(data->gdbm, key_datum, data_datum, GDBM_REPLACE);
522                         if (rcode < 0) {
523                                 radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
524                                         data->session_db, gdbm_strerror(gdbm_errno));
525                                 pthread_mutex_unlock(&data->op_mutex);
526                                 return RLM_MODULE_FAIL;
527                         }
528                         /* Decrease allocated count from the ip index */
529
530                         key_datum.dptr = (char *) &entry.ipaddr;
531                         key_datum.dsize = sizeof(uint32_t);
532                         data_datum = gdbm_fetch(data->ip, key_datum);
533                         if (data_datum.dptr != NULL){
534                                 memcpy(&num, data_datum.dptr, sizeof(int));
535                                 free(data_datum.dptr);
536                                 if (num >0){
537                                         num--;
538                                         RDEBUG("num: %d",num);
539                                         data_datum.dptr = (char *) &num;
540                                         data_datum.dsize = sizeof(int);
541                                         rcode = gdbm_store(data->ip, key_datum, data_datum, GDBM_REPLACE);
542                                         if (rcode < 0) {
543                                                 radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
544                                                                 data->ip_index, gdbm_strerror(gdbm_errno));
545                                                 pthread_mutex_unlock(&data->op_mutex);
546                                                 return RLM_MODULE_FAIL;
547                                         }
548                                         if (num >0 && entry.extra == 1){
549                                                 /*
550                                                  * We are doing MPPP and we still have nas/port entries referencing
551                                                  * this ip. Delete this entry so that eventually we only keep one
552                                                  * reference to this ip.
553                                                  */
554                                                 gdbm_delete(data->gdbm,save_datum);
555                                         }
556                                 }
557                         }
558                 }
559         }
560
561         pthread_mutex_unlock(&data->op_mutex);
562
563         /*
564          * If there is a Framed-IP-Address attribute in the reply, check for override
565          */
566         if (pairfind(request->reply->vps, PW_FRAMED_IP_ADDRESS, 0) != NULL) {
567                 RDEBUG("Found Framed-IP-Address attribute in reply attribute list.");
568                 if (data->override)
569                 {
570                         /* Override supplied Framed-IP-Address */
571                         RDEBUG("override is set to yes. Override the existing Framed-IP-Address attribute.");
572                         pairdelete(&request->reply->vps, PW_FRAMED_IP_ADDRESS, 0);
573                 } else {
574                         /* Abort */
575                         RDEBUG("override is set to no. Return NOOP.");
576                         return RLM_MODULE_NOOP;
577                 }
578         }
579
580         /*
581          * Walk through the database searching for an active=0 entry.
582          * We search twice. Once to see if we have an active entry with the same callerid
583          * so that MPPP can work ok and then once again to find a free entry.
584          */
585
586         pthread_mutex_lock(&data->op_mutex);
587
588         key_datum.dptr = NULL;
589         if (cli != NULL){
590                 key_datum = gdbm_firstkey(data->gdbm);
591                 while(key_datum.dptr){
592                         data_datum = gdbm_fetch(data->gdbm, key_datum);
593                         if (data_datum.dptr){
594                                 memcpy(&entry,data_datum.dptr, sizeof(ippool_info));
595                                 free(data_datum.dptr);
596                                 /*
597                                 * If we find an entry for the same caller-id with active=1
598                                 * then we use that for multilink (MPPP) to work properly.
599                                 */
600                                 if (strcmp(entry.cli,cli) == 0 && entry.active){
601                                         mppp = 1;
602                                         break;
603                                 }
604                         }
605                         nextkey = gdbm_nextkey(data->gdbm, key_datum);
606                         free(key_datum.dptr);
607                         key_datum = nextkey;
608                 }
609         }
610
611         if (key_datum.dptr == NULL){
612                 key_datum = gdbm_firstkey(data->gdbm);
613                 while(key_datum.dptr){
614                         data_datum = gdbm_fetch(data->gdbm, key_datum);
615                         if (data_datum.dptr){
616                                 memcpy(&entry,data_datum.dptr, sizeof(ippool_info));
617                                 free(data_datum.dptr);
618
619                                 /*
620                                  * Find an entry with active == 0
621                                  * or an entry that has expired
622                                  */
623                                 if (entry.active == 0 || (entry.timestamp && ((entry.timeout &&
624                                 request->timestamp >= (entry.timestamp + entry.timeout)) ||
625                                 (data->max_timeout && request->timestamp >= (entry.timestamp + data->max_timeout))))){
626                                         datum tmp;
627
628                                         tmp.dptr = (char *) &entry.ipaddr;
629                                         tmp.dsize = sizeof(uint32_t);
630                                         data_datum = gdbm_fetch(data->ip, tmp);
631
632                                         /*
633                                          * If we find an entry in the ip index and the number is zero (meaning
634                                          * that we haven't allocated the same ip address to another nas/port pair)
635                                          * or if we don't find an entry then delete the session entry so
636                                          * that we can change the key
637                                          * Else we don't delete the session entry since we haven't yet deallocated the
638                                          * corresponding ip address and we continue our search.
639                                          */
640
641                                         if (data_datum.dptr){
642                                                 memcpy(&num,data_datum.dptr, sizeof(int));
643                                                 free(data_datum.dptr);
644                                                 if (num == 0){
645                                                         delete = 1;
646                                                         break;
647                                                 }
648                                         }
649                                         else{
650                                                 delete = 1;
651                                                 break;
652                                         }
653                                 }
654                         }
655                         nextkey = gdbm_nextkey(data->gdbm, key_datum);
656                         free(key_datum.dptr);
657                         key_datum = nextkey;
658                 }
659         }
660         /*
661          * If we have found a free entry set active to 1 then add a Framed-IP-Address attribute to
662          * the reply
663          * We keep the operation mutex locked until after we have set the corresponding entry active
664          */
665         if (key_datum.dptr){
666                 if (found && !mppp){
667                         /*
668                          * Found == 1 means we have the nas/port combination entry in our database
669                          * We exchange the ip address between the nas/port entry and the free entry
670                          * Afterwards we will save the free ip address to the nas/port entry.
671                          * That is:
672                          *  ---------------------------------------------
673                          *  - NAS/PORT Entry  |||| Free Entry  ||| Time
674                          *  -    IP1                 IP2(Free)    BEFORE
675                          *  -    IP2(Free)           IP1          AFTER
676                          *  ---------------------------------------------
677                          *
678                          * We only do this if we are NOT doing MPPP
679                          *
680                          */
681                         datum key_datum_tmp;
682                         datum data_datum_tmp;
683                         ippool_key key_tmp;
684
685                         memcpy(key_tmp.key,key_str,16);
686                         key_datum_tmp.dptr = (char *) &key_tmp;
687                         key_datum_tmp.dsize = sizeof(ippool_key);
688
689                         data_datum_tmp = gdbm_fetch(data->gdbm, key_datum_tmp);
690                         if (data_datum_tmp.dptr != NULL){
691
692                                 rcode = gdbm_store(data->gdbm, key_datum, data_datum_tmp, GDBM_REPLACE);
693                                 free(data_datum_tmp.dptr);
694                                 if (rcode < 0) {
695                                         radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
696                                                 data->session_db, gdbm_strerror(gdbm_errno));
697                                                 pthread_mutex_unlock(&data->op_mutex);
698                                         return RLM_MODULE_FAIL;
699                                 }
700                         }
701                 }
702                 else{
703                         /*
704                          * We have not found the nas/port combination
705                          */
706                         if (delete){
707                                 /*
708                                  * Delete the entry so that we can change the key
709                                  * All is well. We delete one entry and we add one entry
710                                  */
711                                 gdbm_delete(data->gdbm, key_datum);
712                         }
713                         else{
714                                 /*
715                                  * We are doing MPPP. (mppp should be 1)
716                                  * We don't do anything.
717                                  * We will create an extra not needed entry in the database in this case
718                                  * but we don't really care since we always also use the ip_index database
719                                  * when we search for a free entry.
720                                  * We will also delete that entry on the accounting section so that we only
721                                  * have one nas/port entry referencing each ip
722                                  */
723                                 if (mppp)
724                                         extra = 1;
725                                 if (!mppp)
726                                         radlog(L_ERR, "rlm_ippool: mppp is not one. Please report this behaviour.");
727                         }
728                 }
729                 free(key_datum.dptr);
730                 entry.active = 1;
731                 entry.timestamp = request->timestamp;
732                 if ((vp = pairfind(request->reply->vps, PW_SESSION_TIMEOUT, 0)) != NULL)
733                         entry.timeout = (time_t) vp->vp_integer;
734                 else
735                         entry.timeout = 0;
736                 if (extra)
737                         entry.extra = 1;
738                 data_datum.dptr = (char *) &entry;
739                 data_datum.dsize = sizeof(ippool_info);
740                 memcpy(key.key, key_str, 16);
741                 key_datum.dptr = (char *) &key;
742                 key_datum.dsize = sizeof(ippool_key);
743
744                 DEBUG2("rlm_ippool: Allocating ip to key: '%s'",hex_str);
745                 rcode = gdbm_store(data->gdbm, key_datum, data_datum, GDBM_REPLACE);
746                 if (rcode < 0) {
747                         radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
748                                 data->session_db, gdbm_strerror(gdbm_errno));
749                                 pthread_mutex_unlock(&data->op_mutex);
750                         return RLM_MODULE_FAIL;
751                 }
752
753                 /* Increase the ip index count */
754                 key_datum.dptr = (char *) &entry.ipaddr;
755                 key_datum.dsize = sizeof(uint32_t);
756                 data_datum = gdbm_fetch(data->ip, key_datum);
757                 if (data_datum.dptr){
758                         memcpy(&num,data_datum.dptr,sizeof(int));
759                         free(data_datum.dptr);
760                 } else
761                         num = 0;
762                 num++;
763                 RDEBUG("num: %d",num);
764                 data_datum.dptr = (char *) &num;
765                 data_datum.dsize = sizeof(int);
766                 rcode = gdbm_store(data->ip, key_datum, data_datum, GDBM_REPLACE);
767                 if (rcode < 0) {
768                         radlog(L_ERR, "rlm_ippool: Failed storing data to %s: %s",
769                                 data->ip_index, gdbm_strerror(gdbm_errno));
770                         pthread_mutex_unlock(&data->op_mutex);
771                         return RLM_MODULE_FAIL;
772                 }
773                 pthread_mutex_unlock(&data->op_mutex);
774
775
776                 RDEBUG("Allocated ip %s to client key: %s",ip_ntoa(str,entry.ipaddr),hex_str);
777                 vp = radius_paircreate(request, &request->reply->vps,
778                                        PW_FRAMED_IP_ADDRESS, 0, PW_TYPE_IPADDR);
779                 vp->vp_ipaddr = entry.ipaddr;
780
781                 /*
782                  *      If there is no Framed-Netmask attribute in the
783                  *      reply, add one
784                  */
785                 if (pairfind(request->reply->vps, PW_FRAMED_IP_NETMASK, 0) == NULL) {
786                         vp = radius_paircreate(request, &request->reply->vps,
787                                                PW_FRAMED_IP_NETMASK, 0,
788                                                PW_TYPE_IPADDR);
789                         vp->vp_ipaddr = ntohl(data->netmask);
790                 }
791
792         }
793         else{
794                 pthread_mutex_unlock(&data->op_mutex);
795                 RDEBUG("No available ip addresses in pool.");
796                 return RLM_MODULE_NOTFOUND;
797         }
798
799         return RLM_MODULE_OK;
800 }
801
802 static int ippool_detach(void *instance)
803 {
804         rlm_ippool_t *data = (rlm_ippool_t *) instance;
805
806         gdbm_close(data->gdbm);
807         gdbm_close(data->ip);
808         pthread_mutex_destroy(&data->op_mutex);
809
810         free(instance);
811         return 0;
812 }
813
814 /*
815  *      The module name should be the only globally exported symbol.
816  *      That is, everything else should be 'static'.
817  *
818  *      If the module needs to temporarily modify it's instantiation
819  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
820  *      The server will then take care of ensuring that the module
821  *      is single-threaded.
822  */
823 module_t rlm_ippool = {
824         RLM_MODULE_INIT,
825         "ippool",
826         RLM_TYPE_THREAD_SAFE,           /* type */
827         ippool_instantiate,             /* instantiation */
828         ippool_detach,                  /* detach */
829         {
830                 NULL,                   /* authentication */
831                 NULL,                   /* authorization */
832                 NULL,                   /* preaccounting */
833                 ippool_accounting,      /* accounting */
834                 NULL,                   /* checksimul */
835                 NULL,                   /* pre-proxy */
836                 NULL,                   /* post-proxy */
837                 ippool_postauth         /* post-auth */
838         },
839 };