Thu Mar 25 10:39:18 2010

Asterisk developer's documentation


main/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 #include "asterisk.h"
00023 
00024 #include <sys/types.h>
00025 #include <ctype.h>
00026 #include <stdio.h>
00027 #include <stdlib.h>
00028 #include <string.h>
00029 #include <stdarg.h>
00030 
00031 #ifdef HAVE_ALLOCA_H
00032 #include <alloca.h>
00033 #endif
00034 
00035 #ifndef HAVE_STRSEP
00036 char *strsep(char **str, const char *delims)
00037 {
00038     char *token;
00039 
00040     if (!*str) {
00041         /* No more tokens */
00042         return NULL;
00043     }
00044 
00045     token = *str;
00046     while (**str != '\0') {
00047         if (strchr(delims, **str)) {
00048             **str = '\0';
00049             (*str)++;
00050             return token;
00051         }
00052         (*str)++;
00053     }
00054 
00055     /* There is no other token */
00056     *str = NULL;
00057 
00058     return token;
00059 }
00060 #endif
00061 
00062 #ifndef HAVE_SETENV
00063 int setenv(const char *name, const char *value, int overwrite)
00064 {
00065    unsigned char *buf;
00066    int buflen;
00067 
00068    buflen = strlen(name) + strlen(value) + 2;
00069    buf = alloca(buflen);
00070 
00071    if (!overwrite && getenv(name))
00072       return 0;
00073 
00074    snprintf(buf, buflen, "%s=%s", name, value);
00075 
00076    return putenv(buf);
00077 }
00078 #endif
00079 
00080 #ifndef HAVE_UNSETENV
00081 int unsetenv(const char *name)
00082 {
00083    return setenv(name, "", 0);
00084 }
00085 #endif
00086 
00087 #ifndef HAVE_STRCASESTR
00088 static char *upper(const char *orig, char *buf, int bufsize)
00089 {
00090    int i = 0;
00091 
00092    while (i < (bufsize - 1) && orig[i]) {
00093       buf[i] = toupper(orig[i]);
00094       i++;
00095    }
00096 
00097    buf[i] = '\0';
00098 
00099    return buf;
00100 }
00101 
00102 char *strcasestr(const char *haystack, const char *needle)
00103 {
00104    char *u1, *u2;
00105    int u1len = strlen(haystack) + 1, u2len = strlen(needle) + 1;
00106 
00107    u1 = alloca(u1len);
00108    u2 = alloca(u2len);
00109    if (u1 && u2) {
00110       char *offset;
00111       if (u2len > u1len) {
00112          /* Needle bigger than haystack */
00113          return NULL;
00114       }
00115       offset = strstr(upper(haystack, u1, u1len), upper(needle, u2, u2len));
00116       if (offset) {
00117          /* Return the offset into the original string */
00118          return ((char *)((unsigned long)haystack + (unsigned long)(offset - u1)));
00119       } else {
00120          return NULL;
00121       }
00122    } else {
00123       return NULL;
00124    }
00125 }
00126 #endif /* !HAVE_STRCASESTR */
00127 
00128 #ifndef HAVE_STRNLEN
00129 size_t strnlen(const char *s, size_t n)
00130 {
00131    size_t len;
00132 
00133    for (len = 0; len < n; len++)
00134       if (s[len] == '\0')
00135          break;
00136 
00137    return len;
00138 }
00139 #endif /* !HAVE_STRNLEN */
00140 
00141 #if !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC)
00142 char *strndup(const char *s, size_t n)
00143 {
00144    size_t len = strnlen(s, n);
00145    char *new = malloc(len + 1);
00146 
00147    if (!new)
00148       return NULL;
00149 
00150    new[len] = '\0';
00151    return memcpy(new, s, len);
00152 }
00153 #endif /* !defined(HAVE_STRNDUP) && !defined(__AST_DEBUG_MALLOC) */
00154 
00155 #if !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC)
00156 int vasprintf(char **strp, const char *fmt, va_list ap)
00157 {
00158    int size;
00159    va_list ap2;
00160    char s;
00161 
00162    *strp = NULL;
00163    va_copy(ap2, ap);
00164    size = vsnprintf(&s, 1, fmt, ap2);
00165    va_end(ap2);
00166    *strp = malloc(size + 1);
00167    if (!*strp)
00168       return -1;
00169    vsnprintf(*strp, size + 1, fmt, ap);
00170 
00171    return size;
00172 }
00173 #endif /* !defined(HAVE_VASPRINTF) && !defined(__AST_DEBUG_MALLOC) */
00174 
00175 /*
00176  * Based on Code from bsd-asprintf from OpenSSH
00177  * Copyright (c) 2004 Darren Tucker.
00178  *
00179  * Based originally on asprintf.c from OpenBSD:
00180  * Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
00181  *
00182  * Permission to use, copy, modify, and distribute this software for any
00183  * purpose with or without fee is hereby granted, provided that the above
00184  * copyright notice and this permission notice appear in all copies.
00185  *
00186  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
00187  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
00188  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
00189  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
00190  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
00191  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
00192  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
00193  */
00194 #if !defined(HAVE_ASPRINTF) && !defined(__AST_DEBUG_MALLOC) 
00195 int asprintf(char **str, const char *fmt, ...)
00196 {
00197         va_list ap;
00198         int ret;
00199 
00200         *str = NULL;
00201         va_start(ap, fmt);
00202         ret = vasprintf(str, fmt, ap);
00203         va_end(ap);
00204 
00205         return ret;
00206 }
00207 #endif /* !defined(HAVE_ASPRINTF) && !defined(__AST_DEBUG_MALLOC) */
00208 
00209 #ifndef HAVE_STRTOQ
00210 #ifndef LONG_MIN
00211 #define LONG_MIN        (-9223372036854775807L-1L)
00212                                     /* min value of a "long int" */
00213 #endif
00214 #ifndef LONG_MAX
00215 #define LONG_MAX        9223372036854775807L
00216                                     /* max value of a "long int" */
00217 #endif
00218 
00219 /*! \brief
00220  * Convert a string to a quad integer.
00221  *
00222  * \note Ignores `locale' stuff.  Assumes that the upper and lower case
00223  * alphabets and digits are each contiguous.
00224  */
00225 uint64_t strtoq(const char *nptr, char **endptr, int base)
00226 {
00227     const char *s;
00228     uint64_t acc;
00229     unsigned char c;
00230     uint64_t qbase, cutoff;
00231     int neg, any, cutlim;
00232 
00233     /*
00234      * Skip white space and pick up leading +/- sign if any.
00235      * If base is 0, allow 0x for hex and 0 for octal, else
00236      * assume decimal; if base is already 16, allow 0x.
00237      */
00238     s = nptr;
00239     do {
00240             c = *s++;
00241     } while (isspace(c));
00242     if (c == '-') {
00243             neg = 1;
00244             c = *s++;
00245     } else {
00246             neg = 0;
00247             if (c == '+')
00248                     c = *s++;
00249     }
00250     if ((base == 0 || base == 16) &&
00251         c == '\0' && (*s == 'x' || *s == 'X')) {
00252             c = s[1];
00253             s += 2;
00254             base = 16;
00255     }
00256     if (base == 0)
00257             base = c == '\0' ? 8 : 10;
00258 
00259     /*
00260      * Compute the cutoff value between legal numbers and illegal
00261      * numbers.  That is the largest legal value, divided by the
00262      * base.  An input number that is greater than this value, if
00263      * followed by a legal input character, is too big.  One that
00264      * is equal to this value may be valid or not; the limit
00265      * between valid and invalid numbers is then based on the last
00266      * digit.  For instance, if the range for quads is
00267      * [-9223372036854775808..9223372036854775807] and the input base
00268      * is 10, cutoff will be set to 922337203685477580 and cutlim to
00269      * either 7 (neg==0) or 8 (neg==1), meaning that if we have
00270      * accumulated a value > 922337203685477580, or equal but the
00271      * next digit is > 7 (or 8), the number is too big, and we will
00272      * return a range error.
00273      *
00274      * Set any if any `digits' consumed; make it negative to indicate
00275      * overflow.
00276      */
00277     qbase = (unsigned)base;
00278     cutoff = neg ? (uint64_t)-(LONG_MIN + LONG_MAX) + LONG_MAX : LONG_MAX;
00279     cutlim = cutoff % qbase;
00280     cutoff /= qbase;
00281     for (acc = 0, any = 0;; c = *s++) {
00282             if (!isascii(c))
00283                     break;
00284             if (isdigit(c))
00285                     c -= '\0';
00286             else if (isalpha(c))
00287                     c -= isupper(c) ? 'A' - 10 : 'a' - 10;
00288             else
00289                     break;
00290             if (c >= base)
00291                     break;
00292             if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
00293                     any = -1;
00294             else {
00295                     any = 1;
00296                     acc *= qbase;
00297                     acc += c;
00298             }
00299     }
00300     if (any < 0) {
00301             acc = neg ? LONG_MIN : LONG_MAX;
00302     } else if (neg)
00303             acc = -acc;
00304     if (endptr != 0)
00305             *((const char **)endptr) = any ? s - 1 : nptr;
00306     return acc;
00307 }
00308 #endif /* !HAVE_STRTOQ */
00309 
00310 #ifndef HAVE_GETLOADAVG
00311 #ifdef linux
00312 /*! \brief Alternative method of getting load avg on Linux only */
00313 int getloadavg(double *list, int nelem)
00314 {
00315    FILE *LOADAVG;
00316    double avg[3] = { 0.0, 0.0, 0.0 };
00317    int i, res = -1;
00318 
00319    if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
00320       fscanf(LOADAVG, "%lf %lf %lf", &avg[0], &avg[1], &avg[2]);
00321       res = 0;
00322       fclose(LOADAVG);
00323    }
00324 
00325    for (i = 0; (i < nelem) && (i < 3); i++) {
00326       list[i] = avg[i];
00327    }
00328 
00329    return res;
00330 }
00331 #else /* !linux */
00332 /*! \brief Return something that won't cancel the call, but still return -1, in case
00333  * we correct the implementation to check return value */
00334 int getloadavg(double *list, int nelem)
00335 {
00336    int i;
00337 
00338    for (i = 0; i < nelem; i++) {
00339       list[i] = 0.1;
00340    }
00341    return -1;
00342 }
00343 #endif /* linux */
00344 #endif /* !HAVE_GETLOADAVG */
00345 
00346 
00347 /*
00348  * For strlcat()
00349  *
00350  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
00351  * All rights reserved.
00352  *
00353  * Redistribution and use in source and binary forms, with or without
00354  * modification, are permitted provided that the following conditions
00355  * are met:
00356  * 1. Redistributions of source code must retain the above copyright
00357  *    notice, this list of conditions and the following disclaimer.
00358  * 2. Redistributions in binary form must reproduce the above copyright
00359  *    notice, this list of conditions and the following disclaimer in the
00360  *    documentation and/or other materials provided with the distribution.
00361  * 3. The name of the author may not be used to endorse or promote products
00362  *    derived from this software without specific prior written permission.
00363  *
00364  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
00365  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
00366  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
00367  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00368  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00369  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
00370  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
00371  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
00372  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
00373  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00374  */
00375 
00376 /*
00377  * Appends src to string dst of size siz (unlike strncat, siz is the
00378  * full size of dst, not space left).  At most siz-1 characters
00379  * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
00380  * Returns strlen(src) + MIN(siz, strlen(initial dst)).
00381  * If retval >= siz, truncation occurred.
00382  */
00383 #ifndef HAVE_STRLCAT
00384 size_t strlcat(char *dst, const char *src, size_t siz)
00385 {
00386    register char *d = dst;
00387    register const char *s = src;
00388    register size_t n = siz;
00389    size_t dlen;
00390 
00391    /* Find the end of dst and adjust bytes left but don't go past end */
00392    while (n-- != 0 && *d != '\0')
00393       d++;
00394    dlen = d - dst;
00395    n = siz - dlen;
00396 
00397    if (n == 0)
00398       return dlen + strlen(s);
00399 
00400    while (*s != '\0') {
00401       if (n != 1) {
00402          *d++ = *s;
00403          n--;
00404       }
00405       s++;
00406    }
00407    *d = '\0';
00408 
00409    return dlen + (s - src);   /* count does not include NUL */
00410 }
00411 #endif /* HAVE_STRLCAT */
00412 
00413 /*
00414  * For strlcpy()
00415  *
00416  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
00417  * All rights reserved.
00418  *
00419  * Redistribution and use in source and binary forms, with or without
00420  * modification, are permitted provided that the following conditions
00421  * are met:
00422  * 1. Redistributions of source code must retain the above copyright
00423  *    notice, this list of conditions and the following disclaimer.
00424  * 2. Redistributions in binary form must reproduce the above copyright
00425  *    notice, this list of conditions and the following disclaimer in the
00426  *    documentation and/or other materials provided with the distribution.
00427  * 3. The name of the author may not be used to endorse or promote products
00428  *    derived from this software without specific prior written permission.
00429  *
00430  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
00431  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
00432  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
00433  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00434  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00435  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
00436  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
00437  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
00438  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
00439  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00440  */
00441 
00442 /*
00443  * Copy src to string dst of size siz.  At most siz-1 characters
00444  * will be copied.  Always NUL terminates (unless siz == 0).
00445  * Returns strlen(src); if retval >= siz, truncation occurred.
00446  */
00447 #ifndef HAVE_STRLCPY
00448 size_t strlcpy(char *dst, const char *src, size_t siz)
00449 {
00450    register char *d = dst;
00451    register const char *s = src;
00452    register size_t n = siz;
00453 
00454    /* Copy as many bytes as will fit */
00455    if (n != 0 && --n != 0) {
00456       do {
00457          if ((*d++ = *s++) == 0)
00458             break;
00459       } while (--n != 0);
00460    }
00461 
00462    /* Not enough room in dst, add NUL and traverse rest of src */
00463    if (n == 0) {
00464       if (siz != 0)
00465          *d = '\0';     /* NUL-terminate dst */
00466       while (*s++)
00467          ;
00468    }
00469 
00470    return s - src - 1;  /* count does not include NUL */
00471 }
00472 #endif /* HAVE_STRLCPY */

Generated on Thu Mar 25 10:39:18 2010 for Asterisk - the Open Source PBX by  doxygen 1.4.7