The FreeRADIUS server  $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
misc.c
Go to the documentation of this file.
1 /*
2  * This library is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU Lesser General Public
4  * License as published by the Free Software Foundation; either
5  * version 2.1 of the License, or (at your option) any later version.
6  *
7  * This library is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  * Lesser General Public License for more details.
11  *
12  * You should have received a copy of the GNU Lesser General Public
13  * License along with this library; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16 
17 /** Various miscellaneous utility functions
18  *
19  * @file src/lib/util/misc.c
20  *
21  * @copyright 2000,2006 The FreeRADIUS server project
22  */
23 RCSID("$Id: 48db1bd21fdc04c51df714a904c8f26d4aa82b3b $")
24 
25 #include <freeradius-devel/util/dbuff.h>
26 #include <freeradius-devel/util/sbuff.h>
27 #include <freeradius-devel/util/syserror.h>
28 
29 #include <fcntl.h>
30 #include <grp.h>
31 #include <pwd.h>
32 #include <sys/file.h>
33 #include <sys/stat.h>
34 #include <sys/uio.h>
35 
36 #define FR_PUT_LE16(a, val)\
37  do {\
38  a[1] = ((uint16_t) (val)) >> 8;\
39  a[0] = ((uint16_t) (val)) & 0xff;\
40  } while (0)
41 
42 /** Sets a signal handler using sigaction if available, else signal
43  *
44  * @param sig to set handler for.
45  * @param func handler to set.
46  */
47 int fr_set_signal(int sig, sig_t func)
48 {
49 #ifdef HAVE_SIGACTION
50  struct sigaction act;
51 
52  memset(&act, 0, sizeof(act));
53  act.sa_flags = 0;
54  sigemptyset(&act.sa_mask);
55  act.sa_handler = func;
56 
57  if (sigaction(sig, &act, NULL) < 0) {
58  fr_strerror_printf("Failed setting signal %i handler via sigaction(): %s", sig, fr_syserror(errno));
59  return -1;
60  }
61 #else
62  if (signal(sig, func) < 0) {
63  fr_strerror_printf("Failed setting signal %i handler via signal(): %s", sig, fr_syserror(errno));
64  return -1;
65  }
66 #endif
67  return 0;
68 }
69 
70 /** Uninstall a signal for a specific handler
71  *
72  * man sigaction says these are fine to call from a signal handler.
73  *
74  * @param sig SIGNAL
75  */
76 int fr_unset_signal(int sig)
77 {
78 #ifdef HAVE_SIGACTION
79  struct sigaction act;
80 
81  memset(&act, 0, sizeof(act));
82  act.sa_flags = 0;
83  sigemptyset(&act.sa_mask);
84  act.sa_handler = SIG_DFL;
85 
86  return sigaction(sig, &act, NULL);
87 #else
88  return signal(sig, SIG_DFL);
89 #endif
90 }
91 
92 #ifndef F_WRLCK
93 #error "missing definition for F_WRLCK, all file locks will fail"
94 #endif
95 
96 /*
97  * cppcheck apparently can't pick this up from the system headers.
98  */
99 #ifdef CPPCHECK
100 #define F_WRLCK
101 #endif
102 
103 static int rad_lock(int fd, int lock_len, int cmd, int type)
104 {
105  struct flock fl;
106 
107  fl.l_start = 0;
108  fl.l_len = lock_len;
109  fl.l_pid = getpid();
110  fl.l_type = type;
111  fl.l_whence = SEEK_CUR;
112 
113  return fcntl(fd, cmd, (void *)&fl);
114 }
115 
116 /*
117  * Internal wrapper for locking, to minimize the number of ifdef's
118  */
119 int rad_lockfd(int fd, int lock_len)
120 {
121  return rad_lock(fd, lock_len, F_SETLKW, F_WRLCK);
122 }
123 
124 /*
125  * Internal wrapper for locking, to minimize the number of ifdef's
126  *
127  * Nonblocking version.
128  */
129 int rad_lockfd_nonblock(int fd, int lock_len)
130 {
131  /*
132  * Note that there's no "W" on SETLK
133  */
134  return rad_lock(fd, lock_len, F_SETLK, F_WRLCK);
135 }
136 
137 /*
138  * Internal wrapper for unlocking, to minimize the number of ifdef's
139  * in the source.
140  */
141 int rad_unlockfd(int fd, int lock_len)
142 {
143  /*
144  * Note UNLOCK.
145  */
146  return rad_lock(fd, lock_len, F_SETLK, F_UNLCK);
147 }
148 
149 /** Consume the integer (or hex) portion of a value string
150  *
151  * Allows integer or hex representations of integers (but not octal,
152  * as octal is deemed to be confusing).
153  *
154  * @param[out] out Result of parsing string as unsigned 64bit integer.
155  * @param[out] end pointer to the first non numeric char.
156  * @param[in] value string to parse.
157  *
158  * @return integer value.
159  */
160 int fr_strtoull(uint64_t *out, char **end, char const *value)
161 {
162  errno = 0; /* Explicitly clear errors, as glibc appears not to do this */
163 
164  if ((value[0] == '0') && (value[1] == 'x')) {
165  *out = strtoull(value, end, 16);
166  if (errno == ERANGE) {
167  error:
168  fr_strerror_printf("Unsigned integer value \"%s\" too large, would overflow", value);
169  return -1;
170  }
171  return 0;
172  }
173 
174  *out = strtoull(value, end, 10);
175  if (errno == ERANGE) goto error;
176  return 0;
177 }
178 
179 /** Consume the integer (or hex) portion of a value string
180  *
181  * Allows integer or hex representations of integers (but not octal,
182  * as octal is deemed to be confusing).
183  *
184  * @note Check for overflow with errno == ERANGE.
185  *
186  * @param[out] out Result of parsing string as signed 64bit integer.
187  * @param[out] end pointer to the first non numeric char.
188  * @param[in] value string to parse.
189  * @return integer value.
190  */
191 int fr_strtoll(int64_t *out, char **end, char const *value)
192 {
193  errno = 0; /* Explicitly clear errors, as glibc appears not to do this */
194 
195  if ((value[0] == '0') && (value[1] == 'x')) {
196  *out = strtoll(value, end, 16);
197  if (errno == ERANGE) {
198  error:
199  fr_strerror_printf("Signed integer value \"%s\" too large, would overflow", value);
200  return -1;
201  }
202  return 0;
203  }
204 
205  *out = strtoll(value, end, 10);
206  if (errno == ERANGE) goto error;
207  return 0;
208 }
209 
210 /** Trim whitespace from the end of a string
211  *
212  */
213 char *fr_trim(char const *str, size_t size)
214 {
215  char *q;
216 
217  if (!str || !size) return NULL;
218 
219  memcpy(&q, &str, sizeof(q));
220  for (q = q + size; q > str && isspace((uint8_t) *q); q--);
221 
222  return q;
223 }
224 
225 #ifdef O_NONBLOCK
226 /** Set O_NONBLOCK on a socket
227  *
228  * @note O_NONBLOCK is POSIX.
229  *
230  * @param fd to set nonblocking flag on.
231  * @return
232  * - Flags set on the socket.
233  * - -1 on failure.
234  */
235 int fr_nonblock(int fd)
236 {
237  int flags;
238 
239  flags = fcntl(fd, F_GETFL, NULL);
240  if (flags < 0) {
241  fr_strerror_printf("Failed getting socket flags: %s", fr_syserror(errno));
242  return -1;
243  }
244 
245  flags |= O_NONBLOCK;
246  if (fcntl(fd, F_SETFL, flags) < 0) {
247  fr_strerror_printf("Failed setting socket flags: %s", fr_syserror(errno));
248  return -1;
249  }
250 
251  return flags;
252 }
253 
254 /** Unset O_NONBLOCK on a socket
255  *
256  * @note O_NONBLOCK is POSIX.
257  *
258  * @param fd to set nonblocking flag on.
259  * @return
260  * - Flags set on the socket.
261  * - -1 on failure.
262  */
263 int fr_blocking(int fd)
264 {
265  int flags;
266 
267  flags = fcntl(fd, F_GETFL, NULL);
268  if (flags < 0) {
269  fr_strerror_printf("Failed getting socket flags: %s", fr_syserror(errno));
270  return -1;
271  }
272 
273  if (!(flags & O_NONBLOCK)) return flags;
274 
275  flags ^= O_NONBLOCK;
276  if (fcntl(fd, F_SETFL, flags) < 0) {
277  fr_strerror_printf("Failed setting socket flags: %s", fr_syserror(errno));
278  return -1;
279  }
280 
281  return flags;
282 }
283 #else
284 int fr_nonblock(UNUSED int fd)
285 {
286  fr_strerror_const("Non blocking sockets are not supported");
287  return -1;
288 }
289 int fr_blocking(UNUSED int fd)
290 {
291  fr_strerror_const("Non blocking sockets are not supported");
292  return -1;
293 }
294 #endif
295 
296 /** Convert UTF8 string to UCS2 encoding
297  *
298  * @note Borrowed from src/crypto/ms_funcs.c of wpa_supplicant project (http://hostap.epitest.fi/wpa_supplicant/)
299  *
300  * @param[out] out Where to write the ucs2 string.
301  * @param[in] outlen Size of output buffer.
302  * @param[in] in UTF8 string to convert.
303  * @param[in] inlen length of UTF8 string.
304  * @return the size of the UCS2 string written to the output buffer (in bytes).
305  */
306 ssize_t fr_utf8_to_ucs2(uint8_t *out, size_t outlen, char const *in, size_t inlen)
307 {
308  size_t i;
309  uint8_t *start = out;
310 
311  for (i = 0; i < inlen; i++) {
312  uint8_t c, c2, c3;
313 
314  c = in[i];
315  if ((size_t)(out - start) >= outlen) {
316  /* input too long */
317  return -1;
318  }
319 
320  /* One-byte encoding */
321  if (c <= 0x7f) {
322  out[0] = (uint8_t)c;
323  out[1] = 0;
324  out += 2;
325  continue;
326  } else if ((i == (inlen - 1)) || ((size_t)(out - start) >= (outlen - 1))) {
327  /* Incomplete surrogate */
328  return -1;
329  }
330 
331  c2 = in[++i];
332  /* Two-byte encoding */
333  if ((c & 0xe0) == 0xc0) {
334  FR_PUT_LE16(out, ((c & 0x1f) << 6) | (c2 & 0x3f));
335  out += 2;
336  continue;
337  }
338  if ((i == inlen) || ((size_t)(out - start) >= (outlen - 1))) {
339  /* Incomplete surrogate */
340  return -1;
341  }
342 
343  /* Three-byte encoding */
344  c3 = in[++i];
345  FR_PUT_LE16(out, ((c & 0xf) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f));
346  out += 2;
347  }
348 
349  return out - start;
350 }
351 
352 /** Write 128bit unsigned integer to buffer
353  *
354  * @author Alexey Frunze
355  *
356  * @param out where to write result to.
357  * @param outlen size of out.
358  * @param num 128 bit integer.
359  */
360 size_t fr_snprint_uint128(char *out, size_t outlen, uint128_t const num)
361 {
362  char buff[] = "00000000000000000000000000000000000000000000";
363  uint64_t n[2];
364  char *p = buff;
365  int i;
366 #ifndef WORDS_BIGENDIAN
367  size_t const l = 0;
368  size_t const h = 1;
369 #else
370  size_t const l = 1;
371  size_t const h = 0;
372 #endif
373 
374  memcpy(n, &num, sizeof(n));
375 
376  for (i = 0; i < 128; i++) {
377  ssize_t j;
378  int carry;
379 
380  carry = (n[h] >= 0x8000000000000000);
381 
382  // Shift n[] left, doubling it
383  n[h] = ((n[h] << 1) & 0xffffffffffffffff) + (n[l] >= 0x8000000000000000);
384  n[l] = ((n[l] << 1) & 0xffffffffffffffff);
385 
386  // Add s[] to itself in float, doubling it
387  for (j = sizeof(buff) - 2; j >= 0; j--) {
388  buff[j] += buff[j] - '0' + carry;
389  carry = (buff[j] > '9');
390  if (carry) buff[j] -= 10;
391  }
392  }
393 
394  while ((*p == '0') && (p < &buff[sizeof(buff) - 2])) p++;
395 
396  return strlcpy(out, p, outlen);
397 }
398 
399 /** Compares two pointers
400  *
401  * @param a first pointer to compare.
402  * @param b second pointer to compare.
403  * @return
404  * - -1 if a < b.
405  * - +1 if b > a.
406  * - 0 if both equal.
407  */
408 int8_t fr_pointer_cmp(void const *a, void const *b)
409 {
410  return CMP(a, b);
411 }
412 
413 /** Quick sort an array of pointers using a comparator
414  *
415  * @param to_sort array of pointers to sort.
416  * @param start the lowest index (usually 0).
417  * @param end the length of the array.
418  * @param cmp the comparison function to use to sort the array elements.
419  */
420 void fr_quick_sort(void const *to_sort[], int start, int end, fr_cmp_t cmp)
421 {
422  int i, pi;
423  void const *pivot;
424 
425  if (start >= end) return;
426 
427 #define SWAP(_a, _b) \
428  do { \
429  void const *_tmp = to_sort[_a]; \
430  to_sort[_a] = to_sort[_b]; \
431  to_sort[_b] = _tmp; \
432  } while (0)
433 
434  pivot = to_sort[end];
435  for (pi = start, i = start; i < end; i++) {
436  if (cmp(to_sort[i], pivot) < 0) {
437  SWAP(i , pi);
438  pi++;
439  }
440  }
441  SWAP(end, pi);
442 
443  fr_quick_sort(to_sort, start, pi - 1, cmp);
444  fr_quick_sort(to_sort, pi + 1, end, cmp);
445 }
446 
447 #ifdef TALLOC_DEBUG
448 void fr_talloc_verify_cb(UNUSED const void *ptr, UNUSED int depth,
449  UNUSED int max_depth, UNUSED int is_ref,
450  UNUSED void *private_data)
451 {
452  /* do nothing */
453 }
454 #endif
455 
456 
457 /** Do a comparison of two authentication digests by comparing the FULL data.
458  *
459  * Otherwise, the server can be subject to timing attacks.
460  *
461  * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
462  */
463 int fr_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
464 {
465  int result = 0;
466  size_t i;
467 
468  for (i = 0; i < length; i++) result |= a[i] ^ b[i];
469 
470  return result; /* 0 is OK, !0 is !OK, just like memcmp */
471 }
int n
Definition: acutest.h:577
#define RCSID(id)
Definition: build.h:444
#define CMP(_a, _b)
Same as CMP_PREFER_SMALLER use when you don't really care about ordering, you just want an ordering.
Definition: build.h:110
#define UNUSED
Definition: build.h:313
static fr_slen_t in
Definition: dict.h:645
Test enumeration values.
Definition: dict_test.h:92
long int ssize_t
Definition: merged_model.c:24
unsigned char uint8_t
Definition: merged_model.c:30
unsigned long int size_t
Definition: merged_model.c:25
static uint8_t depth(fr_minmax_heap_index_t i)
Definition: minmax_heap.c:83
void fr_quick_sort(void const *to_sort[], int start, int end, fr_cmp_t cmp)
Quick sort an array of pointers using a comparator.
Definition: misc.c:420
int fr_unset_signal(int sig)
Uninstall a signal for a specific handler.
Definition: misc.c:76
char * fr_trim(char const *str, size_t size)
Trim whitespace from the end of a string.
Definition: misc.c:213
int fr_strtoull(uint64_t *out, char **end, char const *value)
Consume the integer (or hex) portion of a value string.
Definition: misc.c:160
int fr_set_signal(int sig, sig_t func)
Sets a signal handler using sigaction if available, else signal.
Definition: misc.c:47
#define FR_PUT_LE16(a, val)
Definition: misc.c:36
int rad_unlockfd(int fd, int lock_len)
Definition: misc.c:141
int fr_nonblock(UNUSED int fd)
Definition: misc.c:284
#define SWAP(_a, _b)
ssize_t fr_utf8_to_ucs2(uint8_t *out, size_t outlen, char const *in, size_t inlen)
Convert UTF8 string to UCS2 encoding.
Definition: misc.c:306
int fr_strtoll(int64_t *out, char **end, char const *value)
Consume the integer (or hex) portion of a value string.
Definition: misc.c:191
int8_t fr_pointer_cmp(void const *a, void const *b)
Compares two pointers.
Definition: misc.c:408
static int rad_lock(int fd, int lock_len, int cmd, int type)
Definition: misc.c:103
int rad_lockfd(int fd, int lock_len)
Definition: misc.c:119
int rad_lockfd_nonblock(int fd, int lock_len)
Definition: misc.c:129
int fr_blocking(UNUSED int fd)
Definition: misc.c:289
size_t fr_snprint_uint128(char *out, size_t outlen, uint128_t const num)
Write 128bit unsigned integer to buffer.
Definition: misc.c:360
int fr_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
Do a comparison of two authentication digests by comparing the FULL data.
Definition: misc.c:463
int8_t(* fr_cmp_t)(void const *a, void const *b)
Definition: misc.h:38
static char buff[sizeof("18446744073709551615")+3]
Definition: size_tests.c:41
fr_aka_sim_id_type_t type
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition: strlcpy.c:34
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition: syserror.c:243
#define fr_strerror_printf(_fmt,...)
Log to thread local error buffer.
Definition: strerror.h:64
#define fr_strerror_const(_msg)
Definition: strerror.h:223
static size_t char fr_sbuff_t size_t inlen
Definition: value.h:984
static size_t char ** out
Definition: value.h:984