Mon Oct 8 12:39:05 2012

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

Generated on Mon Oct 8 12:39:05 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.4.7