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>
34 * The signal() function in Solaris 2.5.1 sets SA_NODEFER in
35 * sa_flags, which causes grief if signal() is called in the
36 * handler before the cause of the signal has been cleared.
37 * (Infinite recursion).
39 * The same problem appears on HPUX, so we avoid it, if we can.
41 * Using sigaction() to reset the signal handler fixes the problem,
42 * so where available, we prefer that solution.
45 void (*reset_signal(int signo, void (*func)(int)))(int)
48 struct sigaction act, oact;
50 memset(&act, 0, sizeof(act));
51 act.sa_handler = func;
52 sigemptyset(&act.sa_mask);
54 #ifdef SA_INTERRUPT /* SunOS */
55 act.sa_flags |= SA_INTERRUPT;
57 if (sigaction(signo, &act, &oact) < 0)
59 return oact.sa_handler;
63 * re-set by calling the 'signal' function, which
64 * may cause infinite recursion and core dumps due to
67 * However, the system is too dumb to implement sigaction(),
68 * so we don't have a choice.
77 * Per-request data, added by modules...
79 struct request_data_t {
89 * Add opaque data (with a "free" function) to a REQUEST.
91 * The unique ptr is meant to be a module configuration,
92 * and the unique integer allows the caller to have multiple
93 * opaque data associated with a REQUEST.
95 int request_data_add(REQUEST *request,
96 void *unique_ptr, int unique_int,
97 void *opaque, bool free_opaque)
99 request_data_t *this, **last, *next;
102 * Some simple sanity checks.
104 if (!request || !opaque) return -1;
107 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
108 if (((*last)->unique_ptr == unique_ptr) &&
109 ((*last)->unique_int == unique_int)) {
115 * If caller requires custom behaviour on free
116 * they must set a destructor.
118 if (this->opaque && this->free_opaque) {
119 talloc_free(this->opaque);
121 break; /* replace the existing entry */
125 if (!this) this = talloc_zero(request, request_data_t);
128 this->unique_ptr = unique_ptr;
129 this->unique_int = unique_int;
130 this->opaque = opaque;
132 this->free_opaque = free_opaque;
142 * Get opaque data from a request.
144 void *request_data_get(REQUEST *request,
145 void *unique_ptr, int unique_int)
147 request_data_t **last;
149 if (!request) return NULL;
151 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
152 if (((*last)->unique_ptr == unique_ptr) &&
153 ((*last)->unique_int == unique_int)) {
154 request_data_t *this = *last;
155 void *ptr = this->opaque;
158 * Remove the entry from the list, and free it.
162 return ptr; /* don't free it, the caller does that */
166 return NULL; /* wasn't found, too bad... */
171 * Get opaque data from a request without removing it.
173 void *request_data_reference(REQUEST *request,
174 void *unique_ptr, int unique_int)
176 request_data_t **last;
178 for (last = &(request->data); *last != NULL; last = &((*last)->next)) {
179 if (((*last)->unique_ptr == unique_ptr) &&
180 ((*last)->unique_int == unique_int)) {
181 request_data_t *this = *last;
182 void *ptr = this->opaque;
188 return NULL; /* wasn't found, too bad... */
192 * Free a REQUEST struct.
194 void request_free(REQUEST **request_ptr)
198 if (!request_ptr || !*request_ptr) {
202 request = *request_ptr;
204 rad_assert(!request->in_request_hash);
206 rad_assert(!request->in_proxy_hash);
208 rad_assert(!request->ev);
212 request->coa->parent = NULL;
213 request_free(&request->coa);
216 if (request->parent && (request->parent->coa == request)) {
217 request->parent->coa = NULL;
222 request->magic = 0x01020304; /* set the request to be nonsense */
224 request->client = NULL;
226 request->home_server = NULL;
228 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, char const *expr)
393 ERROR("ASSERT FAILED %s[%u]: %s", file, line, expr);
399 * Create a new REQUEST data structure.
401 REQUEST *request_alloc(TALLOC_CTX *ctx)
405 request = talloc_zero(ctx, REQUEST);
407 request->magic = REQUEST_MAGIC;
410 request->proxy = NULL;
412 request->reply = NULL;
414 request->proxy_reply = NULL;
416 request->config_items = NULL;
417 request->username = NULL;
418 request->password = NULL;
419 request->timestamp = time(NULL);
420 request->options = debug_flag; /* Default to global debug level */
422 request->module = "";
423 request->component = "<core>";
424 request->radlog = vradlog_request;
431 * Create a new REQUEST, based on an old one.
433 * This function allows modules to inject fake requests
434 * into the server, for tunneled protocols like TTLS & PEAP.
436 REQUEST *request_alloc_fake(REQUEST *request)
440 fake = request_alloc(request);
442 fake->number = request->number;
443 #ifdef HAVE_PTHREAD_H
444 fake->child_pid = request->child_pid;
446 fake->parent = request;
447 fake->root = request->root;
448 fake->client = request->client;
451 * For new server support.
453 * FIXME: Key instead off of a "virtual server" data structure.
455 * FIXME: Permit different servers for inner && outer sessions?
457 fake->server = request->server;
459 fake->packet = rad_alloc(fake, 1);
465 fake->reply = rad_alloc(fake, 0);
471 fake->master_state = REQUEST_ACTIVE;
472 fake->child_state = REQUEST_RUNNING;
475 * Fill in the fake request.
477 fake->packet->sockfd = -1;
478 fake->packet->src_ipaddr = request->packet->src_ipaddr;
479 fake->packet->src_port = request->packet->src_port;
480 fake->packet->dst_ipaddr = request->packet->dst_ipaddr;
481 fake->packet->dst_port = 0;
484 * This isn't STRICTLY required, as the fake request MUST NEVER
485 * be put into the request list. However, it's still reasonable
488 fake->packet->id = fake->number & 0xff;
489 fake->packet->code = request->packet->code;
490 fake->timestamp = request->timestamp;
491 fake->packet->timestamp = request->packet->timestamp;
494 * Required for new identity support
496 fake->listener = request->listener;
499 * Fill in the fake reply, based on the fake request.
501 fake->reply->sockfd = fake->packet->sockfd;
502 fake->reply->src_ipaddr = fake->packet->dst_ipaddr;
503 fake->reply->src_port = fake->packet->dst_port;
504 fake->reply->dst_ipaddr = fake->packet->src_ipaddr;
505 fake->reply->dst_port = fake->packet->src_port;
506 fake->reply->id = fake->packet->id;
507 fake->reply->code = 0; /* UNKNOWN code */
510 * Copy debug information.
512 fake->options = request->options;
513 fake->radlog = request->radlog;
519 REQUEST *request_alloc_coa(REQUEST *request)
521 if (!request || request->coa) return NULL;
524 * Originate CoA requests only when necessary.
526 if ((request->packet->code != PW_CODE_AUTHENTICATION_REQUEST) &&
527 (request->packet->code != PW_CODE_ACCOUNTING_REQUEST)) return NULL;
529 request->coa = request_alloc_fake(request);
530 if (!request->coa) return NULL;
532 request->coa->packet->code = 0; /* unknown, as of yet */
533 request->coa->child_state = REQUEST_RUNNING;
534 request->coa->proxy = rad_alloc(request->coa, 0);
535 if (!request->coa->proxy) {
536 request_free(&request->coa);
545 * Copy a quoted string.
547 int rad_copy_string(char *to, char const *from)
559 } while (*from && (*from != quote));
561 if (*from != quote) return -1; /* not properly quoted */
571 * Copy a quoted string but without the quotes. The length
572 * returned is the number of chars written; the number of
573 * characters consumed is 2 more than this.
575 int rad_copy_string_bare(char *to, char const *from)
581 while (*from && (*from != quote)) {
590 if (*from != quote) return -1; /* not properly quoted */
601 int rad_copy_variable(char *to, char const *from)
613 sublen = rad_copy_string(to, from);
614 if (sublen < 0) return sublen;
620 case '}': /* end of variable expansion */
624 return length; /* proper end of variable */
632 case '%': /* start of variable expansion */
633 if (from[1] == '{') {
637 sublen = rad_copy_variable(to, from);
638 if (sublen < 0) return sublen;
643 } /* else FIXME: catch %%{ ?*/
651 } /* loop over the input string */
654 * We ended the string before a trailing '}'
664 int rad_pps(int *past, int *present, time_t *then, struct timeval *now)
668 if (*then != now->tv_sec) {
675 * Bootstrap PPS by looking at a percentage of
676 * the previous PPS. This lets us take a moving
677 * count, without doing a moving average. If
678 * we're a fraction "f" (0..1) into the current
679 * second, we can get a good guess for PPS by
682 * PPS = pps_now + pps_old * (1 - f)
684 * It's an instantaneous measurement, rather than
685 * a moving average. This will hopefully let it
686 * respond better to sudden spikes.
688 * Doing the calculations by thousands allows us
689 * to not overflow 2^32, AND to not underflow
690 * when we divide by USEC.
692 pps = USEC - now->tv_usec; /* useconds left in previous second */
693 pps /= 1000; /* scale to milliseconds */
694 pps *= *past; /* multiply by past count to get fraction */
695 pps /= 1000; /* scale to usec again */
696 pps += *present; /* add in current count */
701 /** Split string into words and expand each one
703 * @param request Current request.
704 * @param cmd string to split.
705 * @param max_argc the maximum number of arguments to split into.
706 * @param argv Where to write the pointers into argv_buf.
707 * @param can_fail If false, stop processing if any of the xlat expansions fail.
708 * @param argv_buflen size of argv_buf.
709 * @param argv_buf temporary buffer we used to mangle/expand cmd.
710 * Pointers to offsets of this buffer will be written to argv.
711 * @return argc or -1 on failure.
714 int rad_expand_xlat(REQUEST *request, char const *cmd,
715 int max_argc, char *argv[], bool can_fail,
716 size_t argv_buflen, char *argv_buf)
724 if (strlen(cmd) > (argv_buflen - 1)) {
725 ERROR("rad_expand_xlat: Command line is too long");
730 * Check for bad escapes.
732 if (cmd[strlen(cmd) - 1] == '\\') {
733 ERROR("rad_expand_xlat: Command line has final backslash, without a following character");
737 strlcpy(argv_buf, cmd, argv_buflen);
740 * Split the string into argv's BEFORE doing radius_xlat...
751 if ((*from == ' ') || (*from == '\t')) {
759 if (argc >= (max_argc - 1)) break;
762 * Copy the argv over to our buffer.
764 while (*from && (*from != ' ') && (*from != '\t')) {
765 if (to >= argv_buf + argv_buflen - 1) {
766 ERROR("rad_expand_xlat: Ran out of space in command line");
773 length = rad_copy_string_bare(to, from);
775 ERROR("rad_expand_xlat: Invalid string passed as argument");
783 if (from[1] == '{') {
786 length = rad_copy_variable(to, from);
788 ERROR("rad_expand_xlat: Invalid variable expansion passed as argument");
793 } else { /* FIXME: catch %%{ ? */
799 if (from[1] == ' ') from++;
805 } /* end of string, or found a space */
807 *(to++) = '\0'; /* terminate the string */
811 * We have to have SOMETHING, at least.
814 ERROR("rad_expand_xlat: Empty command line.");
819 * Expand each string, as appropriate.
821 left = argv_buf + argv_buflen - to;
822 for (i = 0; i < argc; i++) {
826 * Don't touch argv's which won't be translated.
828 if (strchr(argv[i], '%') == NULL) continue;
830 if (!request) continue;
832 sublen = radius_xlat(to, left - 1, request, argv[i], NULL, NULL);
836 * Fail to be backwards compatible.
838 * It's yucky, but it won't break anything,
839 * and it won't cause security problems.
843 ERROR("rad_expand_xlat: xlat failed");
855 ERROR("rad_expand_xlat: Ran out of space while expanding arguments.");
864 const FR_NAME_NUMBER pair_lists[] = {
865 { "request", PAIR_LIST_REQUEST },
866 { "reply", PAIR_LIST_REPLY },
867 { "config", PAIR_LIST_CONTROL },
868 { "control", PAIR_LIST_CONTROL },
870 { "proxy-request", PAIR_LIST_PROXY_REQUEST },
871 { "proxy-reply", PAIR_LIST_PROXY_REPLY },
874 { "coa", PAIR_LIST_COA },
875 { "coa-reply", PAIR_LIST_COA_REPLY },
876 { "disconnect", PAIR_LIST_DM },
877 { "disconnect-reply", PAIR_LIST_DM_REPLY },
882 const FR_NAME_NUMBER request_refs[] = {
883 { "outer", REQUEST_OUTER },
884 { "current", REQUEST_CURRENT },
885 { "parent", REQUEST_PARENT },
890 /** Resolve attribute name to a list.
892 * Check the name string for qualifiers that specify a list and return
893 * an pair_lists_t value for that list. This value may be passed to
894 * radius_list, along with the current request, to get a pointer to the
895 * actual list in the request.
897 * If qualifiers were consumed, write a new pointer into name to the
898 * char after the last qualifier to be consumed.
900 * radius_list_name should be called before passing a name string that
901 * may contain qualifiers to dict_attrbyname.
903 * @see dict_attrbyname
905 * @param[in,out] name of attribute.
906 * @param[in] default_list the list to return if no qualifiers were found.
907 * @return PAIR_LIST_UNKOWN if qualifiers couldn't be resolved to a list.
909 pair_lists_t radius_list_name(char const **name, pair_lists_t default_list)
911 char const *p = *name;
915 /* This should never be a NULL pointer or zero length string */
916 rad_assert(name && *name);
919 * Unfortunately, ':' isn't a definitive separator for
920 * the list name. We may have numeric tags, too.
925 * Check for tagged attributes. They have
926 * "name:tag", where tag is a decimal number.
927 * Valid tags are invalid attributes, so that's
930 * Also allow "name:tag[#]" as a tag.
932 * However, "request:" is allowed, too, and
933 * shouldn't be interpreted as a tag.
935 * We do this check first rather than just
936 * looking up the request name, because this
937 * check is cheap, and looking up the request
940 if (isdigit((int) q[1])) {
941 char const *d = q + 1;
943 while (isdigit((int) *d)) {
948 * Return the DEFAULT list as supplied by
949 * the caller. This is usually
952 if (!*d || (*d == '[')) {
958 * If the first part is a list name, then treat
959 * it as a list. This means that we CANNOT have
960 * an attribute which is named "request",
961 * "reply", etc. Allowing a tagged attribute
962 * "request:3" would just be insane.
964 output = fr_substr2int(pair_lists, p, PAIR_LIST_UNKNOWN, (q - p));
965 if (output != PAIR_LIST_UNKNOWN) {
966 *name = (q + 1); /* Consume the list and delimiter */
971 * It's not a known list, say so.
973 return PAIR_LIST_UNKNOWN;
977 * The input string may be just a list name,
978 * e.g. "request". Check for that.
981 output = fr_substr2int(pair_lists, p, PAIR_LIST_UNKNOWN, (q - p));
982 if (output != PAIR_LIST_UNKNOWN) {
988 * It's just an attribute name. Return the default list
989 * as supplied by the caller.
995 /** Resolve attribute name to a request.
997 * Check the name string for qualifiers that reference a parent request and
998 * write the pointer to this request to 'request'.
1000 * If qualifiers were consumed, write a new pointer into name to the
1001 * char after the last qualifier to be consumed.
1003 * radius_ref_request should be called before radius_list_name.
1005 * @see radius_list_name
1006 * @param[in,out] name of attribute.
1007 * @param[in] def default request ref to return if no request qualifier is present.
1008 * @return one of the REQUEST_* definitions or REQUEST_UNKOWN
1010 request_refs_t radius_request_name(char const **name, request_refs_t def)
1015 p = strchr(*name, '.');
1021 * We may get passed "127.0.0.1".
1023 request = fr_substr2int(request_refs, *name, REQUEST_UNKNOWN,
1027 * If we get a valid name, skip it.
1029 if (request != REQUEST_UNKNOWN) {
1035 * Otherwise leave it alone, and return the caller's
1041 /** Resolve request to a request.
1043 * Resolve name to a current request.
1046 * @param[in,out] context Base context to use, and to write the result back to.
1047 * @param[in] name (request) to resolve to.
1048 * @return 0 if request is valid in this context, else -1.
1050 int radius_request(REQUEST **context, request_refs_t name)
1052 REQUEST *request = *context;
1055 case REQUEST_CURRENT:
1058 case REQUEST_PARENT: /* for future use in request chaining */
1060 if (!request->parent) {
1063 *context = request->parent;
1066 case REQUEST_UNKNOWN:
1075 /** Adds subcapture values to request data
1077 * Allows use of %{n} expansions.
1079 * @param request Current request.
1080 * @param compare Result returned by regexec.
1081 * @param value The original value.
1082 * @param rxmatch Pointers into value.
1084 void rad_regcapture(REQUEST *request, int compare, char const *value, regmatch_t rxmatch[])
1090 if (compare == REG_NOMATCH) {
1095 * Add new %{0}, %{1}, etc.
1097 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
1099 * Didn't match: delete old match, if it existed.
1101 if (rxmatch[i].rm_so == -1) {
1102 p = request_data_get(request, request, REQUEST_DATA_REGEX | i);
1104 RDEBUG4("%%{%i}: Clearing old value \"%s\"", i, p);
1107 RDEBUG4("%%{%i}: Was empty", i);
1113 len = rxmatch[i].rm_eo - rxmatch[i].rm_so;
1114 p = talloc_array(request, char, len + 1);
1116 ERROR("Out of memory");
1120 memcpy(p, value + rxmatch[i].rm_so, len);
1123 RDEBUG4("%%{%i}: Inserting new value \"%s\"", i, p);
1125 * Copy substring, and add it to
1128 * Note that we don't check
1129 * for out of memory, which is
1130 * the only error we can get...
1132 request_data_add(request, request, REQUEST_DATA_REGEX | i, p, true);