2 * util.c Various utility functions.
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.
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.
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
20 * Copyright 2000,2006 The FreeRADIUS server project
23 #include <freeradius-devel/ident.h>
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/rad_assert.h>
36 * The signal() function in Solaris 2.5.1 sets SA_NODEFER in
37 * sa_flags, which causes grief if signal() is called in the
38 * handler before the cause of the signal has been cleared.
39 * (Infinite recursion).
41 * The same problem appears on HPUX, so we avoid it, if we can.
43 * Using sigaction() to reset the signal handler fixes the problem,
44 * so where available, we prefer that solution.
47 void (*reset_signal(int signo, void (*func)(int)))(int)
50 struct sigaction act, oact;
52 memset(&act, 0, sizeof(act));
53 act.sa_handler = func;
54 sigemptyset(&act.sa_mask);
56 #ifdef SA_INTERRUPT /* SunOS */
57 act.sa_flags |= SA_INTERRUPT;
59 if (sigaction(signo, &act, &oact) < 0)
61 return oact.sa_handler;
65 * re-set by calling the 'signal' function, which
66 * may cause infinite recursion and core dumps due to
69 * However, the system is too dumb to implement sigaction(),
70 * so we don't have a choice.
79 * Per-request data, added by modules...
81 struct request_data_t {
87 void (*free_opaque)(void *);
91 * Add opaque data (with a "free" function) to a REQUEST.
93 * The unique ptr is meant to be a malloc'd module configuration,
94 * and the unique integer allows the caller to have multiple
95 * opaque data associated with a REQUEST.
97 int request_data_add(REQUEST *request,
98 void *unique_ptr, int unique_int,
99 void *opaque, void (*free_opaque)(void *))
101 request_data_t *this, **last, *next;
104 * Some simple sanity checks.
106 if (!request || !opaque) return -1;
109 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
110 if (((*last)->unique_ptr == unique_ptr) &&
111 ((*last)->unique_int == unique_int)) {
116 if (this->opaque && /* free it, if necessary */
118 this->free_opaque(this->opaque);
119 break; /* replace the existing entry */
123 if (!this) this = rad_malloc(sizeof(*this));
124 memset(this, 0, sizeof(*this));
127 this->unique_ptr = unique_ptr;
128 this->unique_int = unique_int;
129 this->opaque = opaque;
130 this->free_opaque = free_opaque;
139 * Get opaque data from a request.
141 void *request_data_get(REQUEST *request,
142 void *unique_ptr, int unique_int)
144 request_data_t **last;
146 if (!request) return NULL;
148 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
149 if (((*last)->unique_ptr == unique_ptr) &&
150 ((*last)->unique_int == unique_int)) {
151 request_data_t *this = *last;
152 void *ptr = this->opaque;
155 * Remove the entry from the list, and free it.
159 return ptr; /* don't free it, the caller does that */
163 return NULL; /* wasn't found, too bad... */
168 * Get opaque data from a request without removing it.
170 void *request_data_reference(REQUEST *request,
171 void *unique_ptr, int unique_int)
173 request_data_t **last;
175 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
176 if (((*last)->unique_ptr == unique_ptr) &&
177 ((*last)->unique_int == unique_int)) {
178 request_data_t *this = *last;
179 void *ptr = this->opaque;
185 return NULL; /* wasn't found, too bad... */
190 * Free a REQUEST struct.
192 void request_free(REQUEST **request_ptr)
196 if ((request_ptr == NULL) || !*request_ptr)
199 request = *request_ptr;
201 rad_assert(!request->in_request_hash);
203 rad_assert(!request->in_proxy_hash);
205 rad_assert(!request->ev);
208 rad_free(&request->packet);
212 rad_free(&request->proxy);
216 rad_free(&request->reply);
219 if (request->proxy_reply)
220 rad_free(&request->proxy_reply);
223 if (request->config_items)
224 pairfree(&request->config_items);
226 request->username = NULL;
227 request->password = NULL;
230 request_data_t *this, *next;
232 for (this = request->data; this != NULL; this = next) {
234 if (this->opaque && /* free it, if necessary */
236 this->free_opaque(this->opaque);
239 request->data = NULL;
243 (request->root->refcount > 0)) {
244 request->root->refcount--;
245 request->root = NULL;
250 request->coa->parent = NULL;
251 rad_assert(request->coa->ev == NULL);
252 request_free(&request->coa);
255 if (request->parent && (request->parent->coa == request)) {
256 request->parent->coa = NULL;
261 request->magic = 0x01020304; /* set the request to be nonsense */
263 request->client = NULL;
265 request->home_server = NULL;
273 * Check a filename for sanity.
275 * Allow only uppercase/lowercase letters, numbers, and '-_/.'
277 int rad_checkfilename(const char *filename)
279 if (strspn(filename, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_/.") == strlen(filename)) {
287 * Create possibly many directories.
289 * Note that the input directory name is NOT a constant!
290 * This is so that IF an error is returned, the 'directory' ptr
291 * points to the name of the file which caused the error.
293 int rad_mkdir(char *directory, mode_t mode)
300 * If the directory exists, don't do anything.
302 if (stat(directory, &st) == 0) {
307 * Look for the LAST directory name. Try to create that,
308 * failing on any error.
310 p = strrchr(directory, FR_DIR_SEP);
313 rcode = rad_mkdir(directory, mode);
316 * On error, we leave the directory name as the
317 * one which caused the error.
320 if (errno == EEXIST) return 0;
325 * Reset the directory delimiter, and go ask
326 * the system to make the directory.
334 * Having done everything successfully, we do the
335 * system call to actually go create the directory.
337 rcode = mkdir(directory, mode & 0777);
343 * Set things like sticky bits that aren't supported by
347 rcode = chmod(directory, mode);
355 * Module malloc() call, which does stuff if the malloc fails.
357 * This call ALWAYS succeeds!
359 void *rad_malloc(size_t size)
361 void *ptr = malloc(size);
364 radlog(L_ERR, "no memory");
372 void *rad_calloc(size_t size)
374 void *ptr = rad_malloc(size);
375 memset(ptr, 0, size);
380 * Signature for free is dumb, and raises errors when we try
381 * to free const ptrs.
383 void rad_cfree(const void *ptr)
388 memcpy(&tmp, &ptr, sizeof(tmp));
393 * Logs an error message and aborts the program
397 void NEVER_RETURNS rad_assert_fail (const char *file, unsigned int line,
400 radlog(L_ERR, "ASSERT FAILED %s[%u]: %s", file, line, expr);
406 * Create a new REQUEST data structure.
408 REQUEST *request_alloc(void)
412 request = rad_malloc(sizeof(REQUEST));
413 memset(request, 0, sizeof(REQUEST));
415 request->magic = REQUEST_MAGIC;
418 request->proxy = NULL;
420 request->reply = NULL;
422 request->proxy_reply = NULL;
424 request->config_items = NULL;
425 request->username = NULL;
426 request->password = NULL;
427 request->timestamp = time(NULL);
428 request->options = debug_flag; /* Default to global debug level */
430 request->module = "";
431 request->component = "<core>";
432 if (debug_flag) request->radlog = radlog_request;
439 * Create a new REQUEST, based on an old one.
441 * This function allows modules to inject fake requests
442 * into the server, for tunneled protocols like TTLS & PEAP.
444 REQUEST *request_alloc_fake(REQUEST *request)
448 fake = request_alloc();
450 fake->number = request->number;
451 #ifdef HAVE_PTHREAD_H
452 fake->child_pid = request->child_pid;
454 fake->parent = request;
455 fake->root = request->root;
456 fake->client = request->client;
459 * For new server support.
461 * FIXME: Key instead off of a "virtual server" data structure.
463 * FIXME: Permit different servers for inner && outer sessions?
465 fake->server = request->server;
467 fake->packet = rad_alloc(1);
473 fake->reply = rad_alloc(0);
479 fake->master_state = REQUEST_ACTIVE;
480 fake->child_state = REQUEST_RUNNING;
483 * Fill in the fake request.
485 fake->packet->sockfd = -1;
486 fake->packet->src_ipaddr = request->packet->src_ipaddr;
487 fake->packet->src_port = request->packet->src_port;
488 fake->packet->dst_ipaddr = request->packet->dst_ipaddr;
489 fake->packet->dst_port = 0;
492 * This isn't STRICTLY required, as the fake request MUST NEVER
493 * be put into the request list. However, it's still reasonable
496 fake->packet->id = fake->number & 0xff;
497 fake->packet->code = request->packet->code;
498 fake->timestamp = request->timestamp;
501 * Required for new identity support
503 fake->listener = request->listener;
506 * Fill in the fake reply, based on the fake request.
508 fake->reply->sockfd = fake->packet->sockfd;
509 fake->reply->src_ipaddr = fake->packet->dst_ipaddr;
510 fake->reply->src_port = fake->packet->dst_port;
511 fake->reply->dst_ipaddr = fake->packet->src_ipaddr;
512 fake->reply->dst_port = fake->packet->src_port;
513 fake->reply->id = fake->packet->id;
514 fake->reply->code = 0; /* UNKNOWN code */
517 * Copy debug information.
519 fake->options = request->options;
520 fake->radlog = request->radlog;
526 REQUEST *request_alloc_coa(REQUEST *request)
528 if (!request || request->coa) return NULL;
531 * Originate CoA requests only when necessary.
533 if ((request->packet->code != PW_AUTHENTICATION_REQUEST) &&
534 (request->packet->code != PW_ACCOUNTING_REQUEST)) return NULL;
536 request->coa = request_alloc_fake(request);
537 if (!request->coa) return NULL;
539 request->coa->packet->code = 0; /* unknown, as of yet */
540 request->coa->child_state = REQUEST_RUNNING;
541 request->coa->proxy = rad_alloc(0);
542 if (!request->coa->proxy) {
543 request_free(&request->coa);
552 * Copy a quoted string.
554 int rad_copy_string(char *to, const char *from)
566 } while (*from && (*from != quote));
568 if (*from != quote) return -1; /* not properly quoted */
581 int rad_copy_variable(char *to, const char *from)
593 sublen = rad_copy_string(to, from);
594 if (sublen < 0) return sublen;
600 case '}': /* end of variable expansion */
604 return length; /* proper end of variable */
612 case '%': /* start of variable expansion */
613 if (from[1] == '{') {
617 sublen = rad_copy_variable(to, from);
618 if (sublen < 0) return sublen;
623 } /* else FIXME: catch %%{ ?*/
631 } /* loop over the input string */
634 * We ended the string before a trailing '}'
644 int rad_pps(int *past, int *present, time_t *then, struct timeval *now)
648 if (*then != now->tv_sec) {
655 * Bootstrap PPS by looking at a percentage of
656 * the previous PPS. This lets us take a moving
657 * count, without doing a moving average. If
658 * we're a fraction "f" (0..1) into the current
659 * second, we can get a good guess for PPS by
662 * PPS = pps_now + pps_old * (1 - f)
664 * It's an instantaneous measurement, rather than
665 * a moving average. This will hopefully let it
666 * respond better to sudden spikes.
668 * Doing the calculations by thousands allows us
669 * to not overflow 2^32, AND to not underflow
670 * when we divide by USEC.
672 pps = USEC - now->tv_usec; /* useconds left in previous second */
673 pps /= 1000; /* scale to milliseconds */
674 pps *= *past; /* multiply by past count to get fraction */
675 pps /= 1000; /* scale to usec again */
676 pps += *present; /* add in current count */