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

Generated on Thu Oct 11 06:33:56 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6