Wed Jan 27 20:02:16 2016

Asterisk developer's documentation


strcompat.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * See http://www.asterisk.org for more information about
00007  * the Asterisk project. Please do not directly contact
00008  * any of the maintainers of this project for assistance;
00009  * the project provides a web site, mailing lists and IRC
00010  * channels for your use.
00011  *
00012  * This program is free software, distributed under the terms of
00013  * the GNU General Public License Version 2. See the LICENSE file
00014  * at the top of the source tree.
00015  */
00016 
00017 /*! \file
00018  *
00019  * \brief Compatibility functions for strsep and strtoq missing on Solaris
00020  *
00021  * .. and lots of other functions too.
00022  */
00023 
00024 /*** MODULEINFO
00025    <support_level>core</support_level>
00026  ***/
00027 
00028 #include "asterisk.h"
00029 
00030 #include <ctype.h>
00031 #include <sys/time.h>       /* for getrlimit(2) */
00032 #include <sys/resource.h>   /* for getrlimit(2) */
00033 #include <sys/types.h>      /* for opendir(3) */
00034 #include <dirent.h>         /* for opendir(3) */
00035 #include <unistd.h>         /* for fcntl(2) */
00036 #include <fcntl.h>          /* for fcntl(2) */
00037 
00038 #include "asterisk/utils.h"
00039 
00040 #ifndef HAVE_STRSEP
00041 char *strsep(char **str, const char *delims)
00042 {
00043    char *token;
00044 
00045    if (!*str) {
00046       /* No more tokens */
00047       return NULL;
00048    }
00049 
00050    token = *str;
00051    while (**str != '\0') {
00052       if (strchr(delims, **str)) {
00053          **str = '\0';
00054          (*str)++;
00055          return token;
00056       }
00057       (*str)++;
00058    }
00059 
00060    /* There is no other token */
00061    *str = NULL;
00062 
00063    return token;
00064 }
00065 #endif
00066 
00067 #ifndef HAVE_SETENV
00068 int setenv(const char *name, const char *value, int overwrite)
00069 {
00070    unsigned char *buf;
00071    int buflen;
00072 
00073    if (!overwrite && getenv(name))
00074       return 0;
00075 
00076    buflen = strlen(name) + strlen(value) + 2;
00077    buf = ast_alloca(buflen);
00078 
00079    snprintf(buf, buflen, "%s=%s", name, value);
00080 
00081    return putenv(buf);
00082 }
00083 #endif
00084 
00085 #ifndef HAVE_UNSETENV
00086 int unsetenv(const char *name)
00087 {
00088    return setenv(name, "", 0);
00089 }
00090 #endif
00091 
00092 #ifndef HAVE_STRCASESTR
00093 static char *upper(const char *orig, char *buf, int bufsize)
00094 {
00095    int i = 0;
00096 
00097    while (i < (bufsize - 1) && orig[i]) {
00098       buf[i] = toupper(orig[i]);
00099       i++;
00100    }
00101 
00102    buf[i] = '\0';
00103 
00104    return buf;
00105 }
00106 
00107 char *strcasestr(const char *haystack, const char *needle)
00108 {
00109    char *u1, *u2;
00110    char *offset;
00111    int u1len = strlen(haystack) + 1, u2len = strlen(needle) + 1;
00112 
00113    if (u2len > u1len) {
00114       /* Needle bigger than haystack */
00115       return NULL;
00116    }
00117    u1 = ast_alloca(u1len);
00118    u2 = ast_alloca(u2len);
00119    offset = strstr(upper(haystack, u1, u1len), upper(needle, u2, u2len));
00120    if (offset) {
00121       /* Return the offset into the original string */
00122       return ((char *)((unsigned long)haystack + (unsigned long)(offset - u1)));
00123    } else {
00124       return NULL;
00125    }
00126 }
00127 #endif /* !HAVE_STRCASESTR */
00128 
00129 #ifndef HAVE_STRNLEN
00130 size_t strnlen(const char *s, size_t n)
00131 {
00132    size_t len;
00133 
00134    for (len = 0; len < n; len++)
00135       if (s[len] == '\0')
00136          break;
00137 
00138    return len;
00139 }
00140 #endif /* !HAVE_STRNLEN */
00141 
00142 #if !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC)
00143 char *strndup(const char *s, size_t n)
00144 {
00145    size_t len = strnlen(s, n);
00146    char *new = malloc(len + 1);
00147 
00148    if (!new)
00149       return NULL;
00150 
00151    new[len] = '\0';
00152    return memcpy(new, s, len);
00153 }
00154 #endif /* !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC) */
00155 
00156 #if !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC)
00157 int vasprintf(char **strp, const char *fmt, va_list ap)
00158 {
00159    int size;
00160    va_list ap2;
00161    char s;
00162 
00163    *strp = NULL;
00164    va_copy(ap2, ap);
00165    size = vsnprintf(&s, 1, fmt, ap2);
00166    va_end(ap2);
00167    *strp = malloc(size + 1);
00168    if (!*strp)
00169       return -1;
00170    vsnprintf(*strp, size + 1, fmt, ap);
00171 
00172    return size;
00173 }
00174 #endif /* !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC) */
00175 
00176 #ifndef HAVE_TIMERSUB
00177 void timersub(struct timeval *tvend, struct timeval *tvstart, struct timeval *tvdiff)
00178 {
00179    tvdiff->tv_sec = tvend->tv_sec - tvstart->tv_sec;
00180    tvdiff->tv_usec = tvend->tv_usec - tvstart->tv_usec;
00181    if (tvdiff->tv_usec < 0) {
00182       tvdiff->tv_sec --;
00183       tvdiff->tv_usec += 1000000;
00184    }
00185 
00186 }
00187 #endif
00188 
00189 /*
00190  * Based on Code from bsd-asprintf from OpenSSH
00191  * Copyright (c) 2004 Darren Tucker.
00192  *
00193  * Based originally on asprintf.c from OpenBSD:
00194  * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
00195  *
00196  * Permission to use, copy, modify, and distribute this software for any
00197  * purpose with or without fee is hereby granted, provided that the above
00198  * copyright notice and this permission notice appear in all copies.
00199  *
00200  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
00201  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
00202  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
00203  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
00204  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
00205  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
00206  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
00207  */
00208 #if !defined(HAVE_ASPRINTF) && !defined(__AST_DEBUG_MALLOC) 
00209 int asprintf(char **str, const char *fmt, ...)
00210 {
00211    va_list ap;
00212    int ret;
00213 
00214    *str = NULL;
00215    va_start(ap, fmt);
00216    ret = vasprintf(str, fmt, ap);
00217    va_end(ap);
00218 
00219    return ret;
00220 }
00221 #endif /* !defined(HAVE_ASPRINTF) && !defined(__AST_DEBUG_MALLOC) */
00222 
00223 #ifndef HAVE_STRTOQ
00224 #ifndef LONG_MIN
00225 #define LONG_MIN        (-9223372036854775807L-1L)
00226                                     /* min value of a "long int" */
00227 #endif
00228 #ifndef LONG_MAX
00229 #define LONG_MAX        9223372036854775807L
00230                                     /* max value of a "long int" */
00231 #endif
00232 
00233 /*! \brief
00234  * Convert a string to a quad integer.
00235  *
00236  * \note Ignores `locale' stuff.  Assumes that the upper and lower case
00237  * alphabets and digits are each contiguous.
00238  */
00239 uint64_t strtoq(const char *nptr, char **endptr, int base)
00240 {
00241     const char *s;
00242     uint64_t acc;
00243     unsigned char c;
00244     uint64_t qbase, cutoff;
00245     int neg, any, cutlim;
00246 
00247     /*
00248      * Skip white space and pick up leading +/- sign if any.
00249      * If base is 0, allow 0x for hex and 0 for octal, else
00250      * assume decimal; if base is already 16, allow 0x.
00251      */
00252     s = nptr;
00253     do {
00254             c = *s++;
00255     } while (isspace(c));
00256     if (c == '-') {
00257             neg = 1;
00258             c = *s++;
00259     } else {
00260             neg = 0;
00261             if (c == '+')
00262                     c = *s++;
00263     }
00264     if ((base == 0 || base == 16) &&
00265         c == '\0' && (*s == 'x' || *s == 'X')) {
00266             c = s[1];
00267             s += 2;
00268             base = 16;
00269     }
00270     if (base == 0)
00271             base = c == '\0' ? 8 : 10;
00272 
00273     /*
00274      * Compute the cutoff value between legal numbers and illegal
00275      * numbers.  That is the largest legal value, divided by the
00276      * base.  An input number that is greater than this value, if
00277      * followed by a legal input character, is too big.  One that
00278      * is equal to this value may be valid or not; the limit
00279      * between valid and invalid numbers is then based on the last
00280      * digit.  For instance, if the range for quads is
00281      * [-9223372036854775808..9223372036854775807] and the input base
00282      * is 10, cutoff will be set to 922337203685477580 and cutlim to
00283      * either 7 (neg==0) or 8 (neg==1), meaning that if we have
00284      * accumulated a value > 922337203685477580, or equal but the
00285      * next digit is > 7 (or 8), the number is too big, and we will
00286      * return a range error.
00287      *
00288      * Set any if any `digits' consumed; make it negative to indicate
00289      * overflow.
00290      */
00291     qbase = (unsigned)base;
00292     cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
00293     cutlim = cutoff % qbase;
00294     cutoff /= qbase;
00295     for (acc = 0, any = 0;; c = *s++) {
00296             if (!isascii(c))
00297                     break;
00298             if (isdigit(c))
00299                     c -= '\0';
00300             else if (isalpha(c))
00301                     c -= isupper(c) ? 'A' - 10 : 'a' - 10;
00302             else
00303                     break;
00304             if (c >= base)
00305                     break;
00306             if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
00307                     any = -1;
00308             else {
00309                     any = 1;
00310                     acc *= qbase;
00311                     acc += c;
00312             }
00313     }
00314     if (any < 0) {
00315             acc = neg ? LONG_MIN : LONG_MAX;
00316     } else if (neg)
00317             acc = -acc;
00318     if (endptr != 0)
00319             *((const char **)endptr) = any ? s - 1 : nptr;
00320     return acc;
00321 }
00322 #endif /* !HAVE_STRTOQ */
00323 
00324 #ifndef HAVE_GETLOADAVG
00325 #ifdef linux
00326 /*! \brief Alternative method of getting load avg on Linux only */
00327 int getloadavg(double *list, int nelem)
00328 {
00329    FILE *LOADAVG;
00330    double avg[3] = { 0.0, 0.0, 0.0 };
00331    int i, res = -1;
00332 
00333    if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
00334       fscanf(LOADAVG, "%lf %lf %lf", &avg[0], &avg[1], &avg[2]);
00335       res = 0;
00336       fclose(LOADAVG);
00337    }
00338 
00339    for (i = 0; (i < nelem) && (i < 3); i++) {
00340       list[i] = avg[i];
00341    }
00342 
00343    return res;
00344 }
00345 #else /* !linux */
00346 /*! \brief Return something that won't cancel the call, but still return -1, in case
00347  * we correct the implementation to check return value */
00348 int getloadavg(double *list, int nelem)
00349 {
00350    int i;
00351 
00352    for (i = 0; i < nelem; i++) {
00353       list[i] = 0.1;
00354    }
00355    return -1;
00356 }
00357 #endif /* linux */
00358 #endif /* !HAVE_GETLOADAVG */
00359 
00360 #ifndef HAVE_NTOHLL
00361 uint64_t ntohll(uint64_t net64)
00362 {
00363 #if BYTE_ORDER == BIG_ENDIAN
00364    return net64;
00365 #elif BYTE_ORDER == LITTLE_ENDIAN
00366    union {
00367       unsigned char c[8];
00368       uint64_t u;
00369    } number;
00370    number.u = net64;
00371    return
00372       (((uint64_t) number.c[0]) << 56) |
00373       (((uint64_t) number.c[1]) << 48) |
00374       (((uint64_t) number.c[2]) << 40) |
00375       (((uint64_t) number.c[3]) << 32) |
00376       (((uint64_t) number.c[4]) << 24) |
00377       (((uint64_t) number.c[5]) << 16) |
00378       (((uint64_t) number.c[6]) <<  8) |
00379       (((uint64_t) number.c[7]) <<  0);
00380 #else
00381    #error "Unknown byte order"
00382 #endif
00383 }
00384 #endif
00385 
00386 #ifndef HAVE_HTONLL
00387 uint64_t htonll(uint64_t host64)
00388 {
00389 #if BYTE_ORDER == BIG_ENDIAN
00390    return host64;
00391 #elif BYTE_ORDER == LITTLE_ENDIAN
00392    union {
00393       unsigned char c[8];
00394       uint64_t u;
00395    } number;
00396    number.u = host64;
00397    return
00398       (((uint64_t) number.c[0]) << 56) |
00399       (((uint64_t) number.c[1]) << 48) |
00400       (((uint64_t) number.c[2]) << 40) |
00401       (((uint64_t) number.c[3]) << 32) |
00402       (((uint64_t) number.c[4]) << 24) |
00403       (((uint64_t) number.c[5]) << 16) |
00404       (((uint64_t) number.c[6]) <<  8) |
00405       (((uint64_t) number.c[7]) <<  0);
00406 #else
00407    #error "Unknown byte order"
00408 #endif
00409 }
00410 #endif
00411 
00412 #ifndef HAVE_FFSLL
00413 int ffsll(long long n)
00414 {
00415    int i;
00416    for (i = 0; i < 64; i++) {
00417       if ((1LL << i) & n) {
00418          return i + 1;
00419       }
00420    }
00421    return 0;
00422 }
00423 #endif
00424 
00425 #ifndef HAVE_CLOSEFROM
00426 void closefrom(int n)
00427 {
00428    long x;
00429    struct rlimit rl;
00430    DIR *dir;
00431    char path[16], *result;
00432    struct dirent *entry;
00433 
00434    snprintf(path, sizeof(path), "/proc/%d/fd", (int) getpid());
00435    if ((dir = opendir(path))) {
00436       while ((entry = readdir(dir))) {
00437          /* Skip . and .. */
00438          if (entry->d_name[0] == '.') {
00439             continue;
00440          }
00441          if ((x = strtol(entry->d_name, &result, 10)) && x >= n) {
00442 #ifdef STRICT_COMPAT
00443             close(x);
00444 #else
00445             /* This isn't strictly compatible, but it's actually faster
00446              * for our purposes to set the CLOEXEC flag than to close
00447              * file descriptors.
00448              */
00449             long flags = fcntl(x, F_GETFD);
00450             if (flags == -1 && errno == EBADF) {
00451                continue;
00452             }
00453             fcntl(x, F_SETFD, flags | FD_CLOEXEC);
00454 #endif
00455          }
00456       }
00457       closedir(dir);
00458    } else {
00459       getrlimit(RLIMIT_NOFILE, &rl);
00460       if (rl.rlim_cur > 65535) {
00461          /* A more reasonable value.  Consider that the primary source of
00462           * file descriptors in Asterisk are UDP sockets, of which we are
00463           * limited to 65,535 per address.  We additionally limit that down
00464           * to about 10,000 sockets per protocol.  While the kernel will
00465           * allow us to set the fileno limit higher (up to 4.2 billion),
00466           * there really is no practical reason for it to be that high.
00467           */
00468          rl.rlim_cur = 65535;
00469       }
00470       for (x = n; x < rl.rlim_cur; x++) {
00471 #ifdef STRICT_COMPAT
00472          close(x);
00473 #else
00474          long flags = fcntl(x, F_GETFD);
00475          if (flags == -1 && errno == EBADF) {
00476             continue;
00477          }
00478          fcntl(x, F_SETFD, flags | FD_CLOEXEC);
00479 #endif
00480       }
00481    }
00482 }
00483 #endif
00484 
00485 #ifndef HAVE_MKDTEMP
00486 /* $OpenBSD: mktemp.c,v 1.30 2010/03/21 23:09:30 schwarze Exp $ */
00487 /*
00488  * Copyright (c) 1996-1998, 2008 Theo de Raadt
00489  * Copyright (c) 1997, 2008-2009 Todd C. Miller
00490  *
00491  * Permission to use, copy, modify, and distribute this software for any
00492  * purpose with or without fee is hereby granted, provided that the above
00493  * copyright notice and this permission notice appear in all copies.
00494  *
00495  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
00496  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
00497  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
00498  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
00499  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
00500  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
00501  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
00502  */
00503 
00504 #define MKTEMP_NAME  0
00505 #define MKTEMP_FILE  1
00506 #define MKTEMP_DIR   2
00507 
00508 #define TEMPCHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."
00509 #define NUM_CHARS (sizeof(TEMPCHARS) - 1)
00510 
00511 static int mktemp_internal(char *path, int slen, int mode)
00512 {
00513    char *start, *cp, *ep;
00514    const char *tempchars = TEMPCHARS;
00515    unsigned int r, tries;
00516    struct stat sb;
00517    size_t len;
00518    int fd;
00519 
00520    len = strlen(path);
00521    if (len == 0 || slen >= len) {
00522       errno = EINVAL;
00523       return(-1);
00524    }
00525    ep = path + len - slen;
00526 
00527    tries = 1;
00528    for (start = ep; start > path && start[-1] == 'X'; start--) {
00529       if (tries < INT_MAX / NUM_CHARS) {
00530          tries *= NUM_CHARS;
00531       }
00532    }
00533    tries *= 2;
00534 
00535    do {
00536       for (cp = start; cp != ep; cp++) {
00537          r = ast_random() % NUM_CHARS;
00538          *cp = tempchars[r];
00539       }
00540 
00541       switch (mode) {
00542       case MKTEMP_NAME:
00543          if (lstat(path, &sb) != 0) {
00544             return (errno == ENOENT ? 0 : -1);
00545          }
00546          break;
00547       case MKTEMP_FILE:
00548          fd = open(path, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
00549          if (fd != -1 || errno != EEXIST) {
00550             return (fd);
00551          }
00552          break;
00553       case MKTEMP_DIR:
00554          if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR) == 0) {
00555             return (0);
00556          }
00557          if (errno != EEXIST) {
00558             return (-1);
00559          }
00560          break;
00561       }
00562    } while (--tries);
00563 
00564    errno = EEXIST;
00565    return(-1);
00566 }
00567 
00568 char *mkdtemp(char *path)
00569 {
00570    return mktemp_internal(path, 0, MKTEMP_DIR) ? NULL : path;
00571 }
00572 #endif
00573 
00574 #ifndef HAVE_ROUNDF
00575 #ifndef HAVE_ROUND
00576 float roundf(float x) {
00577    if (x < 0.0) {
00578       return (float)(int)((x) - 0.5);
00579    } else {
00580       return (float)(int)((x) + 0.5);
00581    }
00582 }
00583 #endif
00584 #endif

Generated on 27 Jan 2016 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1