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
25 #include <freeradius-devel/radiusd.h>
26 #include <freeradius-devel/rad_assert.h>
35 * The signal() function in Solaris 2.5.1 sets SA_NODEFER in
36 * sa_flags, which causes grief if signal() is called in the
37 * handler before the cause of the signal has been cleared.
38 * (Infinite recursion).
40 * The same problem appears on HPUX, so we avoid it, if we can.
42 * Using sigaction() to reset the signal handler fixes the problem,
43 * so where available, we prefer that solution.
46 void (*reset_signal(int signo, void (*func)(int)))(int)
49 struct sigaction act, oact;
51 memset(&act, 0, sizeof(act));
52 act.sa_handler = func;
53 sigemptyset(&act.sa_mask);
55 #ifdef SA_INTERRUPT /* SunOS */
56 act.sa_flags |= SA_INTERRUPT;
58 if (sigaction(signo, &act, &oact) < 0)
60 return oact.sa_handler;
64 * re-set by calling the 'signal' function, which
65 * may cause infinite recursion and core dumps due to
68 * However, the system is too dumb to implement sigaction(),
69 * so we don't have a choice.
78 * Per-request data, added by modules...
80 struct request_data_t {
90 * Add opaque data (with a "free" function) to a REQUEST.
92 * The unique ptr is meant to be a module configuration,
93 * and the unique integer allows the caller to have multiple
94 * opaque data associated with a REQUEST.
96 int request_data_add(REQUEST *request,
97 void *unique_ptr, int unique_int,
98 void *opaque, bool free_opaque)
100 request_data_t *this, **last, *next;
103 * Some simple sanity checks.
105 if (!request || !opaque) return -1;
108 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
109 if (((*last)->unique_ptr == unique_ptr) &&
110 ((*last)->unique_int == unique_int)) {
116 * If caller requires custom behaviour on free
117 * they must set a destructor.
119 if (this->opaque && this->free_opaque) {
120 talloc_free(this->opaque);
122 break; /* replace the existing entry */
126 if (!this) this = talloc_zero(request, request_data_t);
129 this->unique_ptr = unique_ptr;
130 this->unique_int = unique_int;
131 this->opaque = opaque;
133 this->free_opaque = free_opaque;
143 * Get opaque data from a request.
145 void *request_data_get(REQUEST *request,
146 void *unique_ptr, int unique_int)
148 request_data_t **last;
150 if (!request) return NULL;
152 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
153 if (((*last)->unique_ptr == unique_ptr) &&
154 ((*last)->unique_int == unique_int)) {
155 request_data_t *this = *last;
156 void *ptr = this->opaque;
159 * Remove the entry from the list, and free it.
163 return ptr; /* don't free it, the caller does that */
167 return NULL; /* wasn't found, too bad... */
172 * Get opaque data from a request without removing it.
174 void *request_data_reference(REQUEST *request,
175 void *unique_ptr, int unique_int)
177 request_data_t **last;
179 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
180 if (((*last)->unique_ptr == unique_ptr) &&
181 ((*last)->unique_int == unique_int)) {
182 request_data_t *this = *last;
183 void *ptr = this->opaque;
189 return NULL; /* wasn't found, too bad... */
194 * Free a REQUEST struct.
196 void request_free(REQUEST **request_ptr)
200 if (!request_ptr || !*request_ptr) {
204 request = *request_ptr;
206 rad_assert(!request->in_request_hash);
208 rad_assert(!request->in_proxy_hash);
210 rad_assert(!request->ev);
214 request->coa->parent = NULL;
215 request_free(&request->coa);
218 if (request->parent && (request->parent->coa == request)) {
219 request->parent->coa = NULL;
224 request->magic = 0x01020304; /* set the request to be nonsense */
226 request->client = NULL;
228 request->home_server = NULL;
230 talloc_free(request);
237 int request_opaque_free(REQUEST *request)
239 request_free(&request);
245 * Check a filename for sanity.
247 * Allow only uppercase/lowercase letters, numbers, and '-_/.'
249 int rad_checkfilename(char const *filename)
251 if (strspn(filename, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_/.") == strlen(filename)) {
258 /** Check if file exists
260 * @param filename to check.
261 * @return 0 if the file does not exist, 1 if the file exists, -1 if the file
262 * exists but there was an error opening it. errno value should be usable
263 * for error messages.
265 int rad_file_exists(char const *filename)
270 if ((des = open(filename, O_RDONLY)) == -1) {
271 if (errno == ENOENT) {
284 * Create possibly many directories.
286 * Note that the input directory name is NOT a constant!
287 * This is so that IF an error is returned, the 'directory' ptr
288 * points to the name of the file which caused the error.
290 int rad_mkdir(char *directory, mode_t mode)
297 * If the directory exists, don't do anything.
299 if (stat(directory, &st) == 0) {
304 * Look for the LAST directory name. Try to create that,
305 * failing on any error.
307 p = strrchr(directory, FR_DIR_SEP);
310 rcode = rad_mkdir(directory, mode);
313 * On error, we leave the directory name as the
314 * one which caused the error.
317 if (errno == EEXIST) return 0;
322 * Reset the directory delimiter, and go ask
323 * the system to make the directory.
331 * Having done everything successfully, we do the
332 * system call to actually go create the directory.
334 rcode = mkdir(directory, mode & 0777);
340 * Set things like sticky bits that aren't supported by
344 rcode = chmod(directory, mode);
352 * Allocate memory, or exit.
354 * This call ALWAYS succeeds!
356 void *rad_malloc(size_t size)
358 void *ptr = malloc(size);
369 void *rad_calloc(size_t size)
371 void *ptr = rad_malloc(size);
372 memset(ptr, 0, size);
376 void rad_const_free(void const *ptr)
381 memcpy(&tmp, &ptr, sizeof(tmp));
387 * Logs an error message and aborts the program
391 void NEVER_RETURNS rad_assert_fail (char const *file, unsigned int line,
394 ERROR("ASSERT FAILED %s[%u]: %s", file, line, expr);
400 * Create a new REQUEST data structure.
402 REQUEST *request_alloc(TALLOC_CTX *ctx)
406 request = talloc_zero(ctx, REQUEST);
408 request->magic = REQUEST_MAGIC;
411 request->proxy = NULL;
413 request->reply = NULL;
415 request->proxy_reply = NULL;
417 request->config_items = NULL;
418 request->username = NULL;
419 request->password = NULL;
420 request->timestamp = time(NULL);
421 request->options = debug_flag; /* Default to global debug level */
423 request->module = "";
424 request->component = "<core>";
425 request->radlog = radlog_request;
432 * Create a new REQUEST, based on an old one.
434 * This function allows modules to inject fake requests
435 * into the server, for tunneled protocols like TTLS & PEAP.
437 REQUEST *request_alloc_fake(REQUEST *request)
441 fake = request_alloc(request);
443 fake->number = request->number;
444 #ifdef HAVE_PTHREAD_H
445 fake->child_pid = request->child_pid;
447 fake->parent = request;
448 fake->root = request->root;
449 fake->client = request->client;
452 * For new server support.
454 * FIXME: Key instead off of a "virtual server" data structure.
456 * FIXME: Permit different servers for inner && outer sessions?
458 fake->server = request->server;
460 fake->packet = rad_alloc(request, 1);
466 fake->reply = rad_alloc(request, 0);
472 fake->master_state = REQUEST_ACTIVE;
473 fake->child_state = REQUEST_RUNNING;
476 * Fill in the fake request.
478 fake->packet->sockfd = -1;
479 fake->packet->src_ipaddr = request->packet->src_ipaddr;
480 fake->packet->src_port = request->packet->src_port;
481 fake->packet->dst_ipaddr = request->packet->dst_ipaddr;
482 fake->packet->dst_port = 0;
485 * This isn't STRICTLY required, as the fake request MUST NEVER
486 * be put into the request list. However, it's still reasonable
489 fake->packet->id = fake->number & 0xff;
490 fake->packet->code = request->packet->code;
491 fake->timestamp = request->timestamp;
492 fake->packet->timestamp = request->packet->timestamp;
495 * Required for new identity support
497 fake->listener = request->listener;
500 * Fill in the fake reply, based on the fake request.
502 fake->reply->sockfd = fake->packet->sockfd;
503 fake->reply->src_ipaddr = fake->packet->dst_ipaddr;
504 fake->reply->src_port = fake->packet->dst_port;
505 fake->reply->dst_ipaddr = fake->packet->src_ipaddr;
506 fake->reply->dst_port = fake->packet->src_port;
507 fake->reply->id = fake->packet->id;
508 fake->reply->code = 0; /* UNKNOWN code */
511 * Copy debug information.
513 fake->options = request->options;
514 fake->radlog = request->radlog;
520 REQUEST *request_alloc_coa(REQUEST *request)
522 if (!request || request->coa) return NULL;
525 * Originate CoA requests only when necessary.
527 if ((request->packet->code != PW_AUTHENTICATION_REQUEST) &&
528 (request->packet->code != PW_ACCOUNTING_REQUEST)) return NULL;
530 request->coa = request_alloc_fake(request);
531 if (!request->coa) return NULL;
533 request->coa->packet->code = 0; /* unknown, as of yet */
534 request->coa->child_state = REQUEST_RUNNING;
535 request->coa->proxy = rad_alloc(request->coa, 0);
536 if (!request->coa->proxy) {
537 request_free(&request->coa);
546 * Copy a quoted string.
548 int rad_copy_string(char *to, char const *from)
560 } while (*from && (*from != quote));
562 if (*from != quote) return -1; /* not properly quoted */
572 * Copy a quoted string but without the quotes. The length
573 * returned is the number of chars written; the number of
574 * characters consumed is 2 more than this.
576 int rad_copy_string_bare(char *to, char const *from)
582 while (*from && (*from != quote)) {
591 if (*from != quote) return -1; /* not properly quoted */
602 int rad_copy_variable(char *to, char const *from)
614 sublen = rad_copy_string(to, from);
615 if (sublen < 0) return sublen;
621 case '}': /* end of variable expansion */
625 return length; /* proper end of variable */
633 case '%': /* start of variable expansion */
634 if (from[1] == '{') {
638 sublen = rad_copy_variable(to, from);
639 if (sublen < 0) return sublen;
644 } /* else FIXME: catch %%{ ?*/
652 } /* loop over the input string */
655 * We ended the string before a trailing '}'
665 int rad_pps(int *past, int *present, time_t *then, struct timeval *now)
669 if (*then != now->tv_sec) {
676 * Bootstrap PPS by looking at a percentage of
677 * the previous PPS. This lets us take a moving
678 * count, without doing a moving average. If
679 * we're a fraction "f" (0..1) into the current
680 * second, we can get a good guess for PPS by
683 * PPS = pps_now + pps_old * (1 - f)
685 * It's an instantaneous measurement, rather than
686 * a moving average. This will hopefully let it
687 * respond better to sudden spikes.
689 * Doing the calculations by thousands allows us
690 * to not overflow 2^32, AND to not underflow
691 * when we divide by USEC.
693 pps = USEC - now->tv_usec; /* useconds left in previous second */
694 pps /= 1000; /* scale to milliseconds */
695 pps *= *past; /* multiply by past count to get fraction */
696 pps /= 1000; /* scale to usec again */
697 pps += *present; /* add in current count */
702 /** Split string into words and expand each one
704 * @param request Current request.
705 * @param cmd string to split.
706 * @param max_argc the maximum number of arguments to split into.
707 * @param argv Where to write the pointers into argv_buf.
708 * @param can_fail If false, stop processing if any of the xlat expansions fail.
709 * @param argv_buflen size of argv_buf.
710 * @param argv_buf temporary buffer we used to mangle/expand cmd.
711 * Pointers to offsets of this buffer will be written to argv.
712 * @return argc or -1 on failure.
715 int rad_expand_xlat(REQUEST *request, char const *cmd,
716 int max_argc, char *argv[], bool can_fail,
717 size_t argv_buflen, char *argv_buf)
725 if (strlen(cmd) > (argv_buflen - 1)) {
726 ERROR("rad_expand_xlat: Command line is too long");
731 * Check for bad escapes.
733 if (cmd[strlen(cmd) - 1] == '\\') {
734 ERROR("rad_expand_xlat: Command line has final backslash, without a following character");
738 strlcpy(argv_buf, cmd, argv_buflen);
741 * Split the string into argv's BEFORE doing radius_xlat...
752 if ((*from == ' ') || (*from == '\t')) {
760 if (argc >= (max_argc - 1)) break;
763 * Copy the argv over to our buffer.
765 while (*from && (*from != ' ') && (*from != '\t')) {
766 if (to >= argv_buf + argv_buflen - 1) {
767 ERROR("rad_expand_xlat: Ran out of space in command line");
774 length = rad_copy_string_bare(to, from);
776 ERROR("rad_expand_xlat: Invalid string passed as argument");
784 if (from[1] == '{') {
787 length = rad_copy_variable(to, from);
789 ERROR("rad_expand_xlat: Invalid variable expansion passed as argument");
794 } else { /* FIXME: catch %%{ ? */
800 if (from[1] == ' ') from++;
806 } /* end of string, or found a space */
808 *(to++) = '\0'; /* terminate the string */
812 * We have to have SOMETHING, at least.
815 ERROR("rad_expand_xlat: Empty command line.");
820 * Expand each string, as appropriate.
822 left = argv_buf + argv_buflen - to;
823 for (i = 0; i < argc; i++) {
827 * Don't touch argv's which won't be translated.
829 if (strchr(argv[i], '%') == NULL) continue;
831 if (!request) continue;
833 sublen = radius_xlat(to, left - 1, request, argv[i], NULL, NULL);
837 * Fail to be backwards compatible.
839 * It's yucky, but it won't break anything,
840 * and it won't cause security problems.
844 ERROR("rad_expand_xlat: xlat failed");
856 ERROR("rad_expand_xlat: Ran out of space while expanding arguments.");
865 const FR_NAME_NUMBER pair_lists[] = {
866 { "request", PAIR_LIST_REQUEST },
867 { "reply", PAIR_LIST_REPLY },
868 { "config", PAIR_LIST_CONTROL },
869 { "control", PAIR_LIST_CONTROL },
871 { "proxy-request", PAIR_LIST_PROXY_REQUEST },
872 { "proxy-reply", PAIR_LIST_PROXY_REPLY },
875 { "coa", PAIR_LIST_COA },
876 { "coa-reply", PAIR_LIST_COA_REPLY },
877 { "disconnect", PAIR_LIST_DM },
878 { "disconnect-reply", PAIR_LIST_DM_REPLY },
883 const FR_NAME_NUMBER request_refs[] = {
884 { "outer", REQUEST_OUTER },
885 { "current", REQUEST_CURRENT },
886 { "parent", REQUEST_PARENT },
891 /** Resolve attribute name to a list.
893 * Check the name string for qualifiers that specify a list and return
894 * an pair_lists_t value for that list. This value may be passed to
895 * radius_list, along with the current request, to get a pointer to the
896 * actual list in the request.
898 * If qualifiers were consumed, write a new pointer into name to the
899 * char after the last qualifier to be consumed.
901 * radius_list_name should be called before passing a name string that
902 * may contain qualifiers to dict_attrbyname.
904 * @see dict_attrbyname
906 * @param[in,out] name of attribute.
907 * @param[in] unknown the list to return if no qualifiers were found.
908 * @return PAIR_LIST_UNKOWN if qualifiers couldn't be resolved to a list.
910 pair_lists_t radius_list_name(char const **name, pair_lists_t unknown)
912 char const *p = *name;
916 /* This should never be a NULL pointer or zero length string */
917 rad_assert(name && *name);
920 * We couldn't determine the list if:
922 * A colon delimiter was found, but the next char was a
923 * number, indicating a tag, not a list qualifier.
925 * No colon was found and the first char was upper case
926 * indicating an attribute.
930 if (((q && (q[1] >= '0') && (q[1] <= '9'))) ||
931 (!q && isupper((int) *p))) {
936 *name = (q + 1); /* Consume the list and delimiter */
937 return fr_substr2int(pair_lists, p, PAIR_LIST_UNKNOWN, (q - p));
940 q = (p + strlen(p)); /* Consume the entire string */
941 output = fr_substr2int(pair_lists, p, PAIR_LIST_UNKNOWN, (q - p));
942 if (output != PAIR_LIST_UNKNOWN) {
951 /** Resolve attribute name to a request.
953 * Check the name string for qualifiers that reference a parent request and
954 * write the pointer to this request to 'request'.
956 * If qualifiers were consumed, write a new pointer into name to the
957 * char after the last qualifier to be consumed.
959 * radius_ref_request should be called before radius_list_name.
961 * @see radius_list_name
962 * @param[in,out] name of attribute.
963 * @param[in] def default request ref to return if no request qualifier is present.
964 * @return one of the REQUEST_* definitions or REQUEST_UNKOWN
966 request_refs_t radius_request_name(char const **name, request_refs_t def)
971 p = strchr(*name, '.');
977 * We may get passed "127.0.0.1".
979 request = fr_substr2int(request_refs, *name, REQUEST_UNKNOWN,
983 * If we get a valid name, skip it.
985 if (request != REQUEST_UNKNOWN) {
991 * Otherwise leave it alone, and return the caller's
997 /** Resolve request to a request.
999 * Resolve name to a current request.
1002 * @param[in,out] context Base context to use, and to write the result back to.
1003 * @param[in] name (request) to resolve to.
1004 * @return 0 if request is valid in this context, else -1.
1006 int radius_request(REQUEST **context, request_refs_t name)
1008 REQUEST *request = *context;
1011 case REQUEST_CURRENT:
1014 case REQUEST_PARENT: /* for future use in request chaining */
1016 if (!request->parent) {
1019 *context = request->parent;
1022 case REQUEST_UNKNOWN:
1031 /** Adds subcapture values to request data
1033 * Allows use of %{n} expansions.
1035 * @param request Current request.
1036 * @param compare Result returned by regexec.
1037 * @param value The original value.
1038 * @param rxmatch Pointers into value.
1040 void rad_regcapture(REQUEST *request, int compare, char const *value, regmatch_t rxmatch[])
1046 if (compare == REG_NOMATCH) {
1051 * Add new %{0}, %{1}, etc.
1053 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
1055 * Didn't match: delete old match, if it existed.
1057 if (rxmatch[i].rm_so == -1) {
1058 p = request_data_get(request, request, REQUEST_DATA_REGEX | i);
1060 RDEBUG4("%%{%i}: Clearing old value \"%s\"", i, p);
1063 RDEBUG4("%%{%i}: Was empty", i);
1069 len = rxmatch[i].rm_eo - rxmatch[i].rm_so;
1070 p = talloc_array(request, char, len + 1);
1072 ERROR("Out of memory");
1076 memcpy(p, value + rxmatch[i].rm_so, len);
1079 RDEBUG4("%%{%i}: Inserting new value \"%s\"", i, p);
1081 * Copy substring, and add it to
1084 * Note that we don't check
1085 * for out of memory, which is
1086 * the only error we can get...
1088 request_data_add(request, request, REQUEST_DATA_REGEX | i, p, true);